1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2014 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
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 (eval-when-compile (require 'cl-lib
))
33 (declare-function widget-convert
"wid-edit" (type &rest args
))
34 (declare-function shell-mode
"shell" ())
37 (defvar compilation-current-error
)
38 (defvar compilation-context-lines
)
40 (defcustom idle-update-delay
0.5
41 "Idle time delay before updating various things on the screen.
42 Various Emacs features that update auxiliary information when point moves
43 wait this many seconds after Emacs becomes idle before doing an update."
49 "Killing and yanking commands."
52 (defgroup paren-matching nil
53 "Highlight (un)matching of parens and expressions."
56 ;;; next-error support framework
58 (defgroup next-error nil
59 "`next-error' support framework."
64 '((t (:inherit region
)))
65 "Face used to highlight next error locus."
69 (defcustom next-error-highlight
0.5
70 "Highlighting of locations in selected source buffers.
71 If a number, highlight the locus in `next-error' face for the given time
72 in seconds, or until the next command is executed.
73 If t, highlight the locus until the next command is executed, or until
74 some other locus replaces it.
75 If nil, don't highlight the locus in the source buffer.
76 If `fringe-arrow', indicate the locus by the fringe arrow
77 indefinitely until some other locus replaces it."
78 :type
'(choice (number :tag
"Highlight for specified time")
79 (const :tag
"Semipermanent highlighting" t
)
80 (const :tag
"No highlighting" nil
)
81 (const :tag
"Fringe arrow" fringe-arrow
))
85 (defcustom next-error-highlight-no-select
0.5
86 "Highlighting of locations in `next-error-no-select'.
87 If number, highlight the locus in `next-error' face for given time in seconds.
88 If t, highlight the locus indefinitely until some other locus replaces it.
89 If nil, don't highlight the locus in the source buffer.
90 If `fringe-arrow', indicate the locus by the fringe arrow
91 indefinitely until some other locus replaces it."
92 :type
'(choice (number :tag
"Highlight for specified time")
93 (const :tag
"Semipermanent highlighting" t
)
94 (const :tag
"No highlighting" nil
)
95 (const :tag
"Fringe arrow" fringe-arrow
))
99 (defcustom next-error-recenter nil
100 "Display the line in the visited source file recentered as specified.
101 If non-nil, the value is passed directly to `recenter'."
102 :type
'(choice (integer :tag
"Line to recenter to")
103 (const :tag
"Center of window" (4))
104 (const :tag
"No recentering" nil
))
108 (defcustom next-error-hook nil
109 "List of hook functions run by `next-error' after visiting source file."
113 (defvar next-error-highlight-timer nil
)
115 (defvar next-error-overlay-arrow-position nil
)
116 (put 'next-error-overlay-arrow-position
'overlay-arrow-string
(purecopy "=>"))
117 (add-to-list 'overlay-arrow-variable-list
'next-error-overlay-arrow-position
)
119 (defvar next-error-last-buffer nil
120 "The most recent `next-error' buffer.
121 A buffer becomes most recent when its compilation, grep, or
122 similar mode is started, or when it is used with \\[next-error]
123 or \\[compile-goto-error].")
125 (defvar next-error-function nil
126 "Function to use to find the next error in the current buffer.
127 The function is called with 2 parameters:
128 ARG is an integer specifying by how many errors to move.
129 RESET is a boolean which, if non-nil, says to go back to the beginning
130 of the errors before moving.
131 Major modes providing compile-like functionality should set this variable
132 to indicate to `next-error' that this is a candidate buffer and how
134 (make-variable-buffer-local 'next-error-function
)
136 (defvar next-error-move-function nil
137 "Function to use to move to an error locus.
138 It takes two arguments, a buffer position in the error buffer
139 and a buffer position in the error locus buffer.
140 The buffer for the error locus should already be current.
141 nil means use goto-char using the second argument position.")
142 (make-variable-buffer-local 'next-error-move-function
)
144 (defsubst next-error-buffer-p
(buffer
145 &optional avoid-current
147 extra-test-exclusive
)
148 "Test if BUFFER is a `next-error' capable buffer.
150 If AVOID-CURRENT is non-nil, treat the current buffer
151 as an absolute last resort only.
153 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
154 that normally would not qualify. If it returns t, the buffer
155 in question is treated as usable.
157 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
158 that would normally be considered usable. If it returns nil,
159 that buffer is rejected."
160 (and (buffer-name buffer
) ;First make sure it's live.
161 (not (and avoid-current
(eq buffer
(current-buffer))))
162 (with-current-buffer buffer
163 (if next-error-function
; This is the normal test.
164 ;; Optionally reject some buffers.
165 (if extra-test-exclusive
166 (funcall extra-test-exclusive
)
168 ;; Optionally accept some other buffers.
169 (and extra-test-inclusive
170 (funcall extra-test-inclusive
))))))
172 (defun next-error-find-buffer (&optional avoid-current
174 extra-test-exclusive
)
175 "Return a `next-error' capable buffer.
177 If AVOID-CURRENT is non-nil, treat the current buffer
178 as an absolute last resort only.
180 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
181 that normally would not qualify. If it returns t, the buffer
182 in question is treated as usable.
184 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
185 that would normally be considered usable. If it returns nil,
186 that buffer is rejected."
188 ;; 1. If one window on the selected frame displays such buffer, return it.
189 (let ((window-buffers
191 (delq nil
(mapcar (lambda (w)
192 (if (next-error-buffer-p
195 extra-test-inclusive extra-test-exclusive
)
198 (if (eq (length window-buffers
) 1)
199 (car window-buffers
)))
200 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
201 (if (and next-error-last-buffer
202 (next-error-buffer-p next-error-last-buffer avoid-current
203 extra-test-inclusive extra-test-exclusive
))
204 next-error-last-buffer
)
205 ;; 3. If the current buffer is acceptable, choose it.
206 (if (next-error-buffer-p (current-buffer) avoid-current
207 extra-test-inclusive extra-test-exclusive
)
209 ;; 4. Look for any acceptable buffer.
210 (let ((buffers (buffer-list)))
212 (not (next-error-buffer-p
213 (car buffers
) avoid-current
214 extra-test-inclusive extra-test-exclusive
)))
215 (setq buffers
(cdr buffers
)))
217 ;; 5. Use the current buffer as a last resort if it qualifies,
218 ;; even despite AVOID-CURRENT.
220 (next-error-buffer-p (current-buffer) nil
221 extra-test-inclusive extra-test-exclusive
)
223 (message "This is the only buffer with error message locations")
226 (error "No buffers contain error message locations")))
228 (defun next-error (&optional arg reset
)
229 "Visit next `next-error' message and corresponding source code.
231 If all the error messages parsed so far have been processed already,
232 the message buffer is checked for new ones.
234 A prefix ARG specifies how many error messages to move;
235 negative means move back to previous error messages.
236 Just \\[universal-argument] as a prefix means reparse the error message buffer
237 and start at the first error.
239 The RESET argument specifies that we should restart from the beginning.
241 \\[next-error] normally uses the most recently started
242 compilation, grep, or occur buffer. It can also operate on any
243 buffer with output from the \\[compile], \\[grep] commands, or,
244 more generally, on any buffer in Compilation mode or with
245 Compilation Minor mode enabled, or any buffer in which
246 `next-error-function' is bound to an appropriate function.
247 To specify use of a particular buffer for error messages, type
248 \\[next-error] in that buffer when it is the only one displayed
249 in the current frame.
251 Once \\[next-error] has chosen the buffer for error messages, it
252 runs `next-error-hook' with `run-hooks', and stays with that buffer
253 until you use it in some other buffer which uses Compilation mode
254 or Compilation Minor mode.
256 To control which errors are matched, customize the variable
257 `compilation-error-regexp-alist'."
259 (if (consp arg
) (setq reset t arg nil
))
260 (when (setq next-error-last-buffer
(next-error-find-buffer))
261 ;; we know here that next-error-function is a valid symbol we can funcall
262 (with-current-buffer next-error-last-buffer
263 (funcall next-error-function
(prefix-numeric-value arg
) reset
)
264 (when next-error-recenter
265 (recenter next-error-recenter
))
266 (run-hooks 'next-error-hook
))))
268 (defun next-error-internal ()
269 "Visit the source code corresponding to the `next-error' message at point."
270 (setq next-error-last-buffer
(current-buffer))
271 ;; we know here that next-error-function is a valid symbol we can funcall
272 (with-current-buffer next-error-last-buffer
273 (funcall next-error-function
0 nil
)
274 (when next-error-recenter
275 (recenter next-error-recenter
))
276 (run-hooks 'next-error-hook
)))
278 (defalias 'goto-next-locus
'next-error
)
279 (defalias 'next-match
'next-error
)
281 (defun previous-error (&optional n
)
282 "Visit previous `next-error' message and corresponding source code.
284 Prefix arg N says how many error messages to move backwards (or
285 forwards, if negative).
287 This operates on the output from the \\[compile] and \\[grep] commands."
289 (next-error (- (or n
1))))
291 (defun first-error (&optional n
)
292 "Restart at the first error.
293 Visit corresponding source code.
294 With prefix arg N, visit the source code of the Nth error.
295 This operates on the output from the \\[compile] command, for instance."
299 (defun next-error-no-select (&optional n
)
300 "Move point to the next error in the `next-error' buffer and highlight match.
301 Prefix arg N says how many error messages to move forwards (or
302 backwards, if negative).
303 Finds and highlights the source line like \\[next-error], but does not
304 select the source buffer."
306 (let ((next-error-highlight next-error-highlight-no-select
))
308 (pop-to-buffer next-error-last-buffer
))
310 (defun previous-error-no-select (&optional n
)
311 "Move point to the previous error in the `next-error' buffer and highlight match.
312 Prefix arg N says how many error messages to move backwards (or
313 forwards, if negative).
314 Finds and highlights the source line like \\[previous-error], but does not
315 select the source buffer."
317 (next-error-no-select (- (or n
1))))
319 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
320 (defvar next-error-follow-last-line nil
)
322 (define-minor-mode next-error-follow-minor-mode
323 "Minor mode for compilation, occur and diff modes.
324 With a prefix argument ARG, enable mode if ARG is positive, and
325 disable it otherwise. If called from Lisp, enable mode if ARG is
327 When turned on, cursor motion in the compilation, grep, occur or diff
328 buffer causes automatic display of the corresponding source code location."
329 :group
'next-error
:init-value nil
:lighter
" Fol"
330 (if (not next-error-follow-minor-mode
)
331 (remove-hook 'post-command-hook
'next-error-follow-mode-post-command-hook t
)
332 (add-hook 'post-command-hook
'next-error-follow-mode-post-command-hook nil t
)
333 (make-local-variable 'next-error-follow-last-line
)))
335 ;; Used as a `post-command-hook' by `next-error-follow-mode'
336 ;; for the *Compilation* *grep* and *Occur* buffers.
337 (defun next-error-follow-mode-post-command-hook ()
338 (unless (equal next-error-follow-last-line
(line-number-at-pos))
339 (setq next-error-follow-last-line
(line-number-at-pos))
341 (let ((compilation-context-lines nil
))
342 (setq compilation-current-error
(point))
343 (next-error-no-select 0))
349 (defun fundamental-mode ()
350 "Major mode not specialized for anything in particular.
351 Other major modes are defined by comparison with this one."
353 (kill-all-local-variables)
356 ;; Special major modes to view specially formatted data rather than files.
358 (defvar special-mode-map
359 (let ((map (make-sparse-keymap)))
360 (suppress-keymap map
)
361 (define-key map
"q" 'quit-window
)
362 (define-key map
" " 'scroll-up-command
)
363 (define-key map
[?\S-\
] 'scroll-down-command
)
364 (define-key map
"\C-?" 'scroll-down-command
)
365 (define-key map
"?" 'describe-mode
)
366 (define-key map
"h" 'describe-mode
)
367 (define-key map
">" 'end-of-buffer
)
368 (define-key map
"<" 'beginning-of-buffer
)
369 (define-key map
"g" 'revert-buffer
)
372 (put 'special-mode
'mode-class
'special
)
373 (define-derived-mode special-mode nil
"Special"
374 "Parent major mode from which special major modes should inherit."
375 (setq buffer-read-only t
))
377 ;; Making and deleting lines.
379 (defvar self-insert-uses-region-functions nil
380 "Special hook to tell if `self-insert-command' will use the region.
381 It must be called via `run-hook-with-args-until-success' with no arguments.
382 Any `post-self-insert-command' which consumes the region should
383 register a function on this hook so that things like `delete-selection-mode'
384 can refrain from consuming the region.")
386 (defvar hard-newline
(propertize "\n" 'hard t
'rear-nonsticky
'(hard))
387 "Propertized string representing a hard newline character.")
389 (defun newline (&optional arg interactive
)
390 "Insert a newline, and move to left margin of the new line if it's blank.
391 If option `use-hard-newlines' is non-nil, the newline is marked with the
392 text-property `hard'.
393 With ARG, insert that many newlines.
395 If `electric-indent-mode' is enabled, this indents the final new line
396 that it adds, and reindents the preceding line. To just insert
397 a newline, use \\[electric-indent-just-newline].
399 Calls `auto-fill-function' if the current column number is greater
400 than the value of `fill-column' and ARG is nil.
401 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
402 (interactive "*P\np")
403 (barf-if-buffer-read-only)
404 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
405 ;; Set last-command-event to tell self-insert what to insert.
406 (let* ((was-page-start (and (bolp) (looking-at page-delimiter
)))
408 (last-command-event ?
\n)
409 ;; Don't auto-fill if we have a numeric argument.
410 (auto-fill-function (if arg nil auto-fill-function
))
412 ;; Do the rest in post-self-insert-hook, because we want to do it
413 ;; *before* other functions on that hook.
415 (cl-assert (eq ?
\n (char-before)))
416 ;; Mark the newline(s) `hard'.
417 (if use-hard-newlines
418 (set-hard-newline-properties
419 (- (point) (prefix-numeric-value arg
)) (point)))
420 ;; If the newline leaves the previous line blank, and we
421 ;; have a left margin, delete that from the blank line.
423 (goto-char beforepos
)
425 (and (looking-at "[ \t]$")
426 (> (current-left-margin) 0)
427 (delete-region (point)
428 (line-end-position))))
429 ;; Indent the line after the newline, except in one case:
430 ;; when we added the newline at the beginning of a line which
433 (move-to-left-margin nil t
)))))
435 (if (not interactive
)
436 ;; FIXME: For non-interactive uses, many calls actually just want
437 ;; (insert "\n"), so maybe we should do just that, so as to avoid
438 ;; the risk of filling or running abbrevs unexpectedly.
439 (let ((post-self-insert-hook (list postproc
)))
440 (self-insert-command (prefix-numeric-value arg
)))
443 (add-hook 'post-self-insert-hook postproc
)
444 (self-insert-command (prefix-numeric-value arg
)))
445 ;; We first used let-binding to protect the hook, but that was naive
446 ;; since add-hook affects the symbol-default value of the variable,
447 ;; whereas the let-binding might only protect the buffer-local value.
448 (remove-hook 'post-self-insert-hook postproc
)))
449 (cl-assert (not (member postproc post-self-insert-hook
)))
450 (cl-assert (not (member postproc
(default-value 'post-self-insert-hook
))))))
453 (defun set-hard-newline-properties (from to
)
454 (let ((sticky (get-text-property from
'rear-nonsticky
)))
455 (put-text-property from to
'hard
't
)
456 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
457 (if (and (listp sticky
) (not (memq 'hard sticky
)))
458 (put-text-property from
(point) 'rear-nonsticky
459 (cons 'hard sticky
)))))
462 "Insert a newline and leave point before it.
463 If there is a fill prefix and/or a `left-margin', insert them
464 on the new line if the line would have been blank.
465 With arg N, insert N newlines."
467 (let* ((do-fill-prefix (and fill-prefix
(bolp)))
468 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
470 ;; Don't expand an abbrev before point.
476 (if do-left-margin
(indent-to (current-left-margin)))
477 (if do-fill-prefix
(insert-and-inherit fill-prefix
))))
483 (defun split-line (&optional arg
)
484 "Split current line, moving portion beyond point vertically down.
485 If the current line starts with `fill-prefix', insert it on the new
486 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
488 When called from Lisp code, ARG may be a prefix string to copy."
490 (skip-chars-forward " \t")
491 (let* ((col (current-column))
493 ;; What prefix should we check for (nil means don't).
494 (prefix (cond ((stringp arg
) arg
)
497 ;; Does this line start with it?
498 (have-prfx (and prefix
501 (looking-at (regexp-quote prefix
))))))
503 (if have-prfx
(insert-and-inherit prefix
))
507 (defun delete-indentation (&optional arg
)
508 "Join this line to previous and fix up whitespace at join.
509 If there is a fill prefix, delete it from the beginning of this line.
510 With argument, join this line to following line."
513 (if arg
(forward-line 1))
514 (if (eq (preceding-char) ?
\n)
516 (delete-region (point) (1- (point)))
517 ;; If the second line started with the fill prefix,
518 ;; delete the prefix.
520 (<= (+ (point) (length fill-prefix
)) (point-max))
522 (buffer-substring (point)
523 (+ (point) (length fill-prefix
)))))
524 (delete-region (point) (+ (point) (length fill-prefix
))))
525 (fixup-whitespace))))
527 (defalias 'join-line
#'delete-indentation
) ; easier to find
529 (defun delete-blank-lines ()
530 "On blank line, delete all surrounding blank lines, leaving just one.
531 On isolated blank line, delete that one.
532 On nonblank line, delete any immediately following blank lines."
534 (let (thisblank singleblank
)
537 (setq thisblank
(looking-at "[ \t]*$"))
538 ;; Set singleblank if there is just one blank line here.
541 (not (looking-at "[ \t]*\n[ \t]*$"))
543 (progn (forward-line -
1)
544 (not (looking-at "[ \t]*$")))))))
545 ;; Delete preceding blank lines, and this one too if it's the only one.
549 (if singleblank
(forward-line 1))
550 (delete-region (point)
551 (if (re-search-backward "[^ \t\n]" nil t
)
552 (progn (forward-line 1) (point))
554 ;; Delete following blank lines, unless the current line is blank
555 ;; and there are no following blank lines.
556 (if (not (and thisblank singleblank
))
560 (delete-region (point)
561 (if (re-search-forward "[^ \t\n]" nil t
)
562 (progn (beginning-of-line) (point))
564 ;; Handle the special case where point is followed by newline and eob.
565 ;; Delete the line, leaving point at eob.
566 (if (looking-at "^[ \t]*\n\\'")
567 (delete-region (point) (point-max)))))
569 (defcustom delete-trailing-lines t
570 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
571 Trailing lines are deleted only if `delete-trailing-whitespace'
572 is called on the entire buffer (rather than an active region)."
577 (defun delete-trailing-whitespace (&optional start end
)
578 "Delete trailing whitespace between START and END.
579 If called interactively, START and END are the start/end of the
580 region if the mark is active, or of the buffer's accessible
581 portion if the mark is inactive.
583 This command deletes whitespace characters after the last
584 non-whitespace character in each line between START and END. It
585 does not consider formfeed characters to be whitespace.
587 If this command acts on the entire buffer (i.e. if called
588 interactively with the mark inactive, or called from Lisp with
589 END nil), it also deletes all trailing lines at the end of the
590 buffer if the variable `delete-trailing-lines' is non-nil."
592 (barf-if-buffer-read-only)
594 (list (region-beginning) (region-end))
598 (let ((end-marker (copy-marker (or end
(point-max))))
599 (start (or start
(point-min))))
601 (while (re-search-forward "\\s-$" end-marker t
)
602 (skip-syntax-backward "-" (line-beginning-position))
603 ;; Don't delete formfeeds, even if they are considered whitespace.
604 (if (looking-at-p ".*\f")
605 (goto-char (match-end 0)))
606 (delete-region (point) (match-end 0)))
607 ;; Delete trailing empty lines.
608 (goto-char end-marker
)
610 delete-trailing-lines
611 ;; Really the end of buffer.
612 (= (point-max) (1+ (buffer-size)))
613 (<= (skip-chars-backward "\n") -
2))
614 (delete-region (1+ (point)) end-marker
))
615 (set-marker end-marker nil
))))
616 ;; Return nil for the benefit of `write-file-functions'.
619 (defun newline-and-indent ()
620 "Insert a newline, then indent according to major mode.
621 Indentation is done using the value of `indent-line-function'.
622 In programming language modes, this is the same as TAB.
623 In some text modes, where TAB inserts a tab, this command indents to the
624 column specified by the function `current-left-margin'."
626 (delete-horizontal-space t
)
628 (indent-according-to-mode))
630 (defun reindent-then-newline-and-indent ()
631 "Reindent current line, insert newline, then indent the new line.
632 Indentation of both lines is done according to the current major mode,
633 which means calling the current value of `indent-line-function'.
634 In programming language modes, this is the same as TAB.
635 In some text modes, where TAB inserts a tab, this indents to the
636 column specified by the function `current-left-margin'."
639 ;; Be careful to insert the newline before indenting the line.
640 ;; Otherwise, the indentation might be wrong.
644 ;; We are at EOL before the call to indent-according-to-mode, and
645 ;; after it we usually are as well, but not always. We tried to
646 ;; address it with `save-excursion' but that uses a normal marker
647 ;; whereas we need `move after insertion', so we do the save/restore
649 (setq pos
(copy-marker pos t
))
650 (indent-according-to-mode)
652 ;; Remove the trailing white-space after indentation because
653 ;; indentation may introduce the whitespace.
654 (delete-horizontal-space t
))
655 (indent-according-to-mode)))
657 (defcustom read-quoted-char-radix
8
658 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
659 Legitimate radix values are 8, 10 and 16."
660 :type
'(choice (const 8) (const 10) (const 16))
661 :group
'editing-basics
)
663 (defun read-quoted-char (&optional prompt
)
664 "Like `read-char', but do not allow quitting.
665 Also, if the first character read is an octal digit,
666 we read any number of octal digits and return the
667 specified character code. Any nondigit terminates the sequence.
668 If the terminator is RET, it is discarded;
669 any other terminator is used itself as input.
671 The optional argument PROMPT specifies a string to use to prompt the user.
672 The variable `read-quoted-char-radix' controls which radix to use
674 (let ((message-log-max nil
)
675 (help-events (delq nil
(mapcar (lambda (c) (unless (characterp c
) c
))
677 done
(first t
) (code 0) translated
)
679 (let ((inhibit-quit first
)
680 ;; Don't let C-h or other help chars get the help
681 ;; message--only help function keys. See bug#16617.
683 (help-event-list help-events
)
685 "Type the special character you want to use,
686 or the octal character code.
687 RET terminates the character code and is discarded;
688 any other non-digit terminates the character code and is then used as input."))
689 (setq translated
(read-key (and prompt
(format "%s-" prompt
))))
690 (if inhibit-quit
(setq quit-flag nil
)))
691 (if (integerp translated
)
692 (setq translated
(char-resolve-modifiers translated
)))
693 (cond ((null translated
))
694 ((not (integerp translated
))
695 (setq unread-command-events
696 (listify-key-sequence (this-single-command-raw-keys))
698 ((/= (logand translated ?\M-\^
@) 0)
699 ;; Turn a meta-character into a character with the 0200 bit set.
700 (setq code
(logior (logand translated
(lognot ?\M-\^
@)) 128)
702 ((and (<= ?
0 translated
)
703 (< translated
(+ ?
0 (min 10 read-quoted-char-radix
))))
704 (setq code
(+ (* code read-quoted-char-radix
) (- translated ?
0)))
705 (and prompt
(setq prompt
(message "%s %c" prompt translated
))))
706 ((and (<= ?a
(downcase translated
))
707 (< (downcase translated
)
708 (+ ?a -
10 (min 36 read-quoted-char-radix
))))
709 (setq code
(+ (* code read-quoted-char-radix
)
710 (+ 10 (- (downcase translated
) ?a
))))
711 (and prompt
(setq prompt
(message "%s %c" prompt translated
))))
712 ((and (not first
) (eq translated ?\C-m
))
715 (setq unread-command-events
716 (listify-key-sequence (this-single-command-raw-keys))
718 (t (setq code translated
723 (defun quoted-insert (arg)
724 "Read next input character and insert it.
725 This is useful for inserting control characters.
726 With argument, insert ARG copies of the character.
728 If the first character you type after this command is an octal digit,
729 you should type a sequence of octal digits which specify a character code.
730 Any nondigit terminates the sequence. If the terminator is a RET,
731 it is discarded; any other terminator is used itself as input.
732 The variable `read-quoted-char-radix' specifies the radix for this feature;
733 set it to 10 or 16 to use decimal or hex instead of octal.
735 In overwrite mode, this function inserts the character anyway, and
736 does not handle octal digits specially. This means that if you use
737 overwrite as your normal editing mode, you can use this function to
738 insert characters when necessary.
740 In binary overwrite mode, this function does overwrite, and octal
741 digits are interpreted as a character code. This is intended to be
742 useful for editing binary files."
745 ;; Avoid "obsolete" warnings for translation-table-for-input.
747 (let (translation-table-for-input input-method-function
)
748 (if (or (not overwrite-mode
)
749 (eq overwrite-mode
'overwrite-mode-binary
))
752 ;; This used to assume character codes 0240 - 0377 stand for
753 ;; characters in some single-byte character set, and converted them
754 ;; to Emacs characters. But in 23.1 this feature is deprecated
755 ;; in favor of inserting the corresponding Unicode characters.
756 ;; (if (and enable-multibyte-characters
759 ;; (setq char (unibyte-char-to-multibyte char)))
760 (unless (characterp char
)
761 (user-error "%s is not a valid character"
762 (key-description (vector char
))))
764 (if (eq overwrite-mode
'overwrite-mode-binary
)
767 (insert-and-inherit char
)
768 (setq arg
(1- arg
)))))
770 (defun forward-to-indentation (&optional arg
)
771 "Move forward ARG lines and position at first nonblank character."
773 (forward-line (or arg
1))
774 (skip-chars-forward " \t"))
776 (defun backward-to-indentation (&optional arg
)
777 "Move backward ARG lines and position at first nonblank character."
779 (forward-line (- (or arg
1)))
780 (skip-chars-forward " \t"))
782 (defun back-to-indentation ()
783 "Move point to the first non-whitespace character on this line."
785 (beginning-of-line 1)
786 (skip-syntax-forward " " (line-end-position))
787 ;; Move back over chars that have whitespace syntax but have the p flag.
788 (backward-prefix-chars))
790 (defun fixup-whitespace ()
791 "Fixup white space between objects around point.
792 Leave one space or none, according to the context."
795 (delete-horizontal-space)
796 (if (or (looking-at "^\\|\\s)")
797 (save-excursion (forward-char -
1)
798 (looking-at "$\\|\\s(\\|\\s'")))
802 (defun delete-horizontal-space (&optional backward-only
)
803 "Delete all spaces and tabs around point.
804 If BACKWARD-ONLY is non-nil, only delete them before point."
806 (let ((orig-pos (point)))
811 (skip-chars-forward " \t")
812 (constrain-to-field nil orig-pos t
)))
814 (skip-chars-backward " \t")
815 (constrain-to-field nil orig-pos
)))))
817 (defun just-one-space (&optional n
)
818 "Delete all spaces and tabs around point, leaving one space (or N spaces).
819 If N is negative, delete newlines as well, leaving -N spaces.
820 See also `cycle-spacing'."
822 (cycle-spacing n nil
'single-shot
))
824 (defvar cycle-spacing--context nil
825 "Store context used in consecutive calls to `cycle-spacing' command.
826 The first time `cycle-spacing' runs, it saves in this variable:
827 its N argument, the original point position, and the original spacing
830 (defun cycle-spacing (&optional n preserve-nl-back mode
)
831 "Manipulate whitespace around point in a smart way.
832 In interactive use, this function behaves differently in successive
835 The first call in a sequence acts like `just-one-space'.
836 It deletes all spaces and tabs around point, leaving one space
837 \(or N spaces). N is the prefix argument. If N is negative,
838 it deletes newlines as well, leaving -N spaces.
839 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
841 The second call in a sequence deletes all spaces.
843 The third call in a sequence restores the original whitespace (and point).
845 If MODE is `single-shot', it only performs the first step in the sequence.
846 If MODE is `fast' and the first step would not result in any change
847 \(i.e., there are exactly (abs N) spaces around point),
848 the function goes straight to the second step.
850 Repeatedly calling the function with different values of N starts a
851 new sequence each time."
853 (let ((orig-pos (point))
854 (skip-characters (if (and n
(< n
0)) " \t\n\r" " \t"))
855 (num (abs (or n
1))))
856 (skip-chars-backward (if preserve-nl-back
" \t" skip-characters
))
857 (constrain-to-field nil orig-pos
)
859 ;; Command run for the first time, single-shot mode or different argument
860 ((or (eq 'single-shot mode
)
861 (not (equal last-command this-command
))
862 (not cycle-spacing--context
)
863 (not (eq (car cycle-spacing--context
) n
)))
864 (let* ((start (point))
865 (num (- num
(skip-chars-forward " " (+ num
(point)))))
868 (skip-chars-forward skip-characters
)
869 (constrain-to-field nil orig-pos t
))))
870 (setq cycle-spacing--context
;; Save for later.
871 ;; Special handling for case where there was no space at all.
872 (unless (= start end
)
873 (cons n
(cons orig-pos
(buffer-substring start
(point))))))
874 ;; If this run causes no change in buffer content, delete all spaces,
875 ;; otherwise delete all excess spaces.
876 (delete-region (if (and (eq mode
'fast
) (zerop num
) (= mid end
))
878 (insert (make-string num ?\s
))))
880 ;; Command run for the second time.
881 ((not (equal orig-pos
(point)))
882 (delete-region (point) orig-pos
))
884 ;; Command run for the third time.
886 (insert (cddr cycle-spacing--context
))
887 (goto-char (cadr cycle-spacing--context
))
888 (setq cycle-spacing--context nil
)))))
890 (defun beginning-of-buffer (&optional arg
)
891 "Move point to the beginning of the buffer.
892 With numeric arg N, put point N/10 of the way from the beginning.
893 If the buffer is narrowed, this command uses the beginning of the
894 accessible part of the buffer.
896 If Transient Mark mode is disabled, leave mark at previous
897 position, unless a \\[universal-argument] prefix is supplied."
898 (declare (interactive-only "use `(goto-char (point-min))' instead."))
903 (let ((size (- (point-max) (point-min))))
904 (goto-char (if (and arg
(not (consp arg
)))
907 ;; Avoid overflow for large buffer sizes!
908 (* (prefix-numeric-value arg
)
910 (/ (+ 10 (* size
(prefix-numeric-value arg
))) 10)))
912 (if (and arg
(not (consp arg
))) (forward-line 1)))
914 (defun end-of-buffer (&optional arg
)
915 "Move point to the end of the buffer.
916 With numeric arg N, put point N/10 of the way from the end.
917 If the buffer is narrowed, this command uses the end of the
918 accessible part of the buffer.
920 If Transient Mark mode is disabled, leave mark at previous
921 position, unless a \\[universal-argument] prefix is supplied."
922 (declare (interactive-only "use `(goto-char (point-max))' instead."))
924 (or (consp arg
) (region-active-p) (push-mark))
925 (let ((size (- (point-max) (point-min))))
926 (goto-char (if (and arg
(not (consp arg
)))
929 ;; Avoid overflow for large buffer sizes!
930 (* (prefix-numeric-value arg
)
932 (/ (* size
(prefix-numeric-value arg
)) 10)))
934 ;; If we went to a place in the middle of the buffer,
935 ;; adjust it to the beginning of a line.
936 (cond ((and arg
(not (consp arg
))) (forward-line 1))
937 ((and (eq (current-buffer) (window-buffer))
938 (> (point) (window-end nil t
)))
939 ;; If the end of the buffer is not already on the screen,
940 ;; then scroll specially to put it near, but not at, the bottom.
941 (overlay-recenter (point))
944 (defcustom delete-active-region t
945 "Whether single-char deletion commands delete an active region.
946 This has an effect only if Transient Mark mode is enabled, and
947 affects `delete-forward-char' and `delete-backward-char', though
950 If the value is the symbol `kill', the active region is killed
952 :type
'(choice (const :tag
"Delete active region" t
)
953 (const :tag
"Kill active region" kill
)
954 (const :tag
"Do ordinary deletion" nil
))
958 (defvar region-extract-function
960 (when (region-beginning)
961 (if (eq delete
'delete-only
)
962 (delete-region (region-beginning) (region-end))
963 (filter-buffer-substring (region-beginning) (region-end) delete
))))
964 "Function to get the region's content.
965 Called with one argument DELETE.
966 If DELETE is `delete-only', then only delete the region and the return value
967 is undefined. If DELETE is nil, just return the content as a string.
968 If anything else, delete the region and return its content as a string.")
970 (defun delete-backward-char (n &optional killflag
)
971 "Delete the previous N characters (following if N is negative).
972 If Transient Mark mode is enabled, the mark is active, and N is 1,
973 delete the text in the region and deactivate the mark instead.
974 To disable this, set option `delete-active-region' to nil.
976 Optional second arg KILLFLAG, if non-nil, means to kill (save in
977 kill ring) instead of delete. Interactively, N is the prefix
978 arg, and KILLFLAG is set if N is explicitly specified.
980 In Overwrite mode, single character backward deletion may replace
981 tabs with spaces so as to back over columns, unless point is at
982 the end of the line."
983 (declare (interactive-only delete-char
))
986 (signal 'wrong-type-argument
(list 'integerp n
)))
987 (cond ((and (use-region-p)
990 ;; If a region is active, kill or delete it.
991 (if (eq delete-active-region
'kill
)
992 (kill-region (region-beginning) (region-end) 'region
)
993 (funcall region-extract-function
'delete-only
)))
994 ;; In Overwrite mode, maybe untabify while deleting
995 ((null (or (null overwrite-mode
)
997 (memq (char-before) '(?
\t ?
\n))
999 (eq (char-after) ?
\n)))
1000 (let ((ocol (current-column)))
1001 (delete-char (- n
) killflag
)
1003 (insert-char ?\s
(- ocol
(current-column)) nil
))))
1004 ;; Otherwise, do simple deletion.
1005 (t (delete-char (- n
) killflag
))))
1007 (defun delete-forward-char (n &optional killflag
)
1008 "Delete the following N characters (previous if N is negative).
1009 If Transient Mark mode is enabled, the mark is active, and N is 1,
1010 delete the text in the region and deactivate the mark instead.
1011 To disable this, set variable `delete-active-region' to nil.
1013 Optional second arg KILLFLAG non-nil means to kill (save in kill
1014 ring) instead of delete. Interactively, N is the prefix arg, and
1015 KILLFLAG is set if N was explicitly specified."
1016 (declare (interactive-only delete-char
))
1017 (interactive "p\nP")
1018 (unless (integerp n
)
1019 (signal 'wrong-type-argument
(list 'integerp n
)))
1020 (cond ((and (use-region-p)
1021 delete-active-region
1023 ;; If a region is active, kill or delete it.
1024 (if (eq delete-active-region
'kill
)
1025 (kill-region (region-beginning) (region-end) 'region
)
1026 (funcall region-extract-function
'delete-only
)))
1028 ;; Otherwise, do simple deletion.
1029 (t (delete-char n killflag
))))
1031 (defun mark-whole-buffer ()
1032 "Put point at beginning and mark at end of buffer.
1033 If narrowing is in effect, only uses the accessible part of the buffer.
1034 You probably should not use this function in Lisp programs;
1035 it is usually a mistake for a Lisp function to use any subroutine
1036 that uses or sets the mark."
1037 (declare (interactive-only t
))
1040 (push-mark (point-max) nil t
)
1041 (goto-char (point-min)))
1044 ;; Counting lines, one way or another.
1046 (defun goto-line (line &optional buffer
)
1047 "Go to LINE, counting from line 1 at beginning of buffer.
1048 If called interactively, a numeric prefix argument specifies
1049 LINE; without a numeric prefix argument, read LINE from the
1052 If optional argument BUFFER is non-nil, switch to that buffer and
1053 move to line LINE there. If called interactively with \\[universal-argument]
1054 as argument, BUFFER is the most recently selected other buffer.
1056 Prior to moving point, this function sets the mark (without
1057 activating it), unless Transient Mark mode is enabled and the
1058 mark is already active.
1060 This function is usually the wrong thing to use in a Lisp program.
1061 What you probably want instead is something like:
1062 (goto-char (point-min))
1063 (forward-line (1- N))
1064 If at all possible, an even better solution is to use char counts
1065 rather than line counts."
1066 (declare (interactive-only forward-line
))
1068 (if (and current-prefix-arg
(not (consp current-prefix-arg
)))
1069 (list (prefix-numeric-value current-prefix-arg
))
1070 ;; Look for a default, a number in the buffer at point.
1073 (skip-chars-backward "0-9")
1074 (if (looking-at "[0-9]")
1076 (buffer-substring-no-properties
1078 (progn (skip-chars-forward "0-9")
1080 ;; Decide if we're switching buffers.
1082 (if (consp current-prefix-arg
)
1083 (other-buffer (current-buffer) t
)))
1086 (concat " in " (buffer-name buffer
))
1088 ;; Read the argument, offering that number (if any) as default.
1089 (list (read-number (format "Goto line%s: " buffer-prompt
)
1090 (list default
(line-number-at-pos)))
1092 ;; Switch to the desired buffer, one way or another.
1094 (let ((window (get-buffer-window buffer
)))
1095 (if window
(select-window window
)
1096 (switch-to-buffer-other-window buffer
))))
1097 ;; Leave mark at previous position
1098 (or (region-active-p) (push-mark))
1099 ;; Move to the specified line number in that buffer.
1102 (goto-char (point-min))
1103 (if (eq selective-display t
)
1104 (re-search-forward "[\n\C-m]" nil
'end
(1- line
))
1105 (forward-line (1- line
)))))
1107 (defun count-words-region (start end
&optional arg
)
1108 "Count the number of words in the region.
1109 If called interactively, print a message reporting the number of
1110 lines, words, and characters in the region (whether or not the
1111 region is active); with prefix ARG, report for the entire buffer
1112 rather than the region.
1114 If called from Lisp, return the number of words between positions
1116 (interactive (if current-prefix-arg
1117 (list nil nil current-prefix-arg
)
1118 (list (region-beginning) (region-end) nil
)))
1119 (cond ((not (called-interactively-p 'any
))
1120 (count-words start end
))
1122 (count-words--buffer-message))
1124 (count-words--message "Region" start end
))))
1126 (defun count-words (start end
)
1127 "Count words between START and END.
1128 If called interactively, START and END are normally the start and
1129 end of the buffer; but if the region is active, START and END are
1130 the start and end of the region. Print a message reporting the
1131 number of lines, words, and chars.
1133 If called from Lisp, return the number of words between START and
1134 END, without printing any message."
1135 (interactive (list nil nil
))
1136 (cond ((not (called-interactively-p 'any
))
1140 (narrow-to-region start end
)
1141 (goto-char (point-min))
1142 (while (forward-word 1)
1143 (setq words
(1+ words
)))))
1146 (call-interactively 'count-words-region
))
1148 (count-words--buffer-message))))
1150 (defun count-words--buffer-message ()
1151 (count-words--message
1152 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1153 (point-min) (point-max)))
1155 (defun count-words--message (str start end
)
1156 (let ((lines (count-lines start end
))
1157 (words (count-words start end
))
1158 (chars (- end start
)))
1159 (message "%s has %d line%s, %d word%s, and %d character%s."
1161 lines
(if (= lines
1) "" "s")
1162 words
(if (= words
1) "" "s")
1163 chars
(if (= chars
1) "" "s"))))
1165 (define-obsolete-function-alias 'count-lines-region
'count-words-region
"24.1")
1168 "Print the current buffer line number and narrowed line number of point."
1170 (let ((start (point-min))
1171 (n (line-number-at-pos)))
1173 (message "Line %d" n
)
1177 (message "line %d (narrowed line %d)"
1178 (+ n
(line-number-at-pos start
) -
1) n
))))))
1180 (defun count-lines (start end
)
1181 "Return number of lines between START and END.
1182 This is usually the number of newlines between them,
1183 but can be one more if START is not equal to END
1184 and the greater of them is not at the start of a line."
1187 (narrow-to-region start end
)
1188 (goto-char (point-min))
1189 (if (eq selective-display t
)
1192 (while (re-search-forward "[\n\C-m]" nil t
40)
1193 (setq done
(+ 40 done
)))
1194 (while (re-search-forward "[\n\C-m]" nil t
1)
1195 (setq done
(+ 1 done
)))
1196 (goto-char (point-max))
1197 (if (and (/= start end
)
1201 (- (buffer-size) (forward-line (buffer-size)))))))
1203 (defun line-number-at-pos (&optional pos
)
1204 "Return (narrowed) buffer line number at position POS.
1205 If POS is nil, use current buffer location.
1206 Counting starts at (point-min), so the value refers
1207 to the contents of the accessible portion of the buffer."
1208 (let ((opoint (or pos
(point))) start
)
1210 (goto-char (point-min))
1211 (setq start
(point))
1214 (1+ (count-lines start
(point))))))
1216 (defun what-cursor-position (&optional detail
)
1217 "Print info on cursor position (on screen and within buffer).
1218 Also describe the character after point, and give its character code
1219 in octal, decimal and hex.
1221 For a non-ASCII multibyte character, also give its encoding in the
1222 buffer's selected coding system if the coding system encodes the
1223 character safely. If the character is encoded into one byte, that
1224 code is shown in hex. If the character is encoded into more than one
1225 byte, just \"...\" is shown.
1227 In addition, with prefix argument, show details about that character
1228 in *Help* buffer. See also the command `describe-char'."
1230 (let* ((char (following-char))
1232 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1233 ;; start a directional embedding, which could completely
1234 ;; disrupt the rest of the line (e.g., RLO will display the
1235 ;; rest of the line right-to-left). So we put an invisible
1236 ;; PDF character after these characters, to end the
1237 ;; embedding, which eliminates any effects on the rest of
1238 ;; the line. For RLE and RLO we also append an invisible
1239 ;; LRM, to avoid reordering the following numerical
1240 ;; characters. For LRI/RLI/FSI we append a PDI.
1241 (cond ((memq char
'(?
\x202a ?
\x202d
))
1242 (propertize (string ?
\x202c
) 'invisible t
))
1243 ((memq char
'(?
\x202b ?
\x202e
))
1244 (propertize (string ?
\x202c ?
\x200e
) 'invisible t
))
1245 ((memq char
'(?
\x2066 ?
\x2067 ?
\x2068
))
1246 (propertize (string ?
\x2069
) 'invisible t
))
1247 ;; Strong right-to-left characters cause reordering of
1248 ;; the following numerical characters which show the
1249 ;; codepoint, so append LRM to countermand that.
1250 ((memq (get-char-code-property char
'bidi-class
) '(R AL
))
1251 (propertize (string ?
\x200e
) 'invisible t
))
1257 (total (buffer-size))
1258 (percent (if (> total
50000)
1259 ;; Avoid overflow from multiplying by 100!
1260 (/ (+ (/ total
200) (1- pos
)) (max (/ total
100) 1))
1261 (/ (+ (/ total
2) (* 100 (1- pos
))) (max total
1))))
1262 (hscroll (if (= (window-hscroll) 0)
1264 (format " Hscroll=%d" (window-hscroll))))
1265 (col (current-column)))
1267 (if (or (/= beg
1) (/= end
(1+ total
)))
1268 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1269 pos total percent beg end col hscroll
)
1270 (message "point=%d of %d (EOB) column=%d%s"
1271 pos total col hscroll
))
1272 (let ((coding buffer-file-coding-system
)
1273 encoded encoding-msg display-prop under-display
)
1274 (if (or (not coding
)
1275 (eq (coding-system-type coding
) t
))
1276 (setq coding
(default-value 'buffer-file-coding-system
)))
1277 (if (eq (char-charset char
) 'eight-bit
)
1279 (format "(%d, #o%o, #x%x, raw-byte)" char char char
))
1280 ;; Check if the character is displayed with some `display'
1281 ;; text property. In that case, set under-display to the
1282 ;; buffer substring covered by that property.
1283 (setq display-prop
(get-char-property pos
'display
))
1285 (let ((to (or (next-single-char-property-change pos
'display
)
1287 (if (< to
(+ pos
4))
1288 (setq under-display
"")
1289 (setq under-display
"..."
1292 (concat (buffer-substring-no-properties pos to
)
1294 (setq encoded
(and (>= char
128) (encode-coding-char char coding
))))
1297 (if (not (stringp display-prop
))
1298 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1299 char char char under-display
)
1300 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1301 char char char under-display display-prop
))
1303 (format "(%d, #o%o, #x%x, file %s)"
1305 (if (> (length encoded
) 1)
1307 (encoded-string-description encoded coding
)))
1308 (format "(%d, #o%o, #x%x)" char char char
)))))
1310 ;; We show the detailed information about CHAR.
1311 (describe-char (point)))
1312 (if (or (/= beg
1) (/= end
(1+ total
)))
1313 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1315 (single-key-description char
)
1316 (buffer-substring-no-properties (point) (1+ (point))))
1318 encoding-msg pos total percent beg end col hscroll
)
1319 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1320 (if enable-multibyte-characters
1322 (single-key-description char
)
1323 (buffer-substring-no-properties (point) (1+ (point))))
1324 (single-key-description char
))
1325 bidi-fixer encoding-msg pos total percent col hscroll
))))))
1327 ;; Initialize read-expression-map. It is defined at C level.
1328 (defvar read-expression-map
1329 (let ((m (make-sparse-keymap)))
1330 (define-key m
"\M-\t" 'completion-at-point
)
1331 ;; Might as well bind TAB to completion, since inserting a TAB char is
1332 ;; much too rarely useful.
1333 (define-key m
"\t" 'completion-at-point
)
1334 (set-keymap-parent m minibuffer-local-map
)
1337 (defun read-minibuffer (prompt &optional initial-contents
)
1338 "Return a Lisp object read using the minibuffer, unevaluated.
1339 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1340 is a string to insert in the minibuffer before reading.
1341 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1342 Such arguments are used as in `read-from-minibuffer'.)"
1343 ;; Used for interactive spec `x'.
1344 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1345 t
'minibuffer-history
))
1347 (defun eval-minibuffer (prompt &optional initial-contents
)
1348 "Return value of Lisp expression read using the minibuffer.
1349 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1350 is a string to insert in the minibuffer before reading.
1351 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1352 Such arguments are used as in `read-from-minibuffer'.)"
1353 ;; Used for interactive spec `X'.
1354 (eval (read--expression prompt initial-contents
)))
1356 (defvar minibuffer-completing-symbol nil
1357 "Non-nil means completing a Lisp symbol in the minibuffer.")
1358 (make-obsolete-variable 'minibuffer-completing-symbol nil
"24.1" 'get
)
1360 (defvar minibuffer-default nil
1361 "The current default value or list of default values in the minibuffer.
1362 The functions `read-from-minibuffer' and `completing-read' bind
1363 this variable locally.")
1365 (defcustom eval-expression-print-level
4
1366 "Value for `print-level' while printing value in `eval-expression'.
1367 A value of nil means no limit."
1369 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1372 (defcustom eval-expression-print-length
12
1373 "Value for `print-length' while printing value in `eval-expression'.
1374 A value of nil means no limit."
1376 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1379 (defcustom eval-expression-debug-on-error t
1380 "If non-nil set `debug-on-error' to t in `eval-expression'.
1381 If nil, don't change the value of `debug-on-error'."
1386 (defun eval-expression-print-format (value)
1387 "Format VALUE as a result of evaluated expression.
1388 Return a formatted string which is displayed in the echo area
1389 in addition to the value printed by prin1 in functions which
1390 display the result of expression evaluation."
1391 (if (and (integerp value
)
1392 (or (eq standard-output t
)
1393 (zerop (prefix-numeric-value current-prefix-arg
))))
1395 (if (and (characterp value
)
1396 (char-displayable-p value
))
1397 (prin1-char value
))))
1399 (format " (#o%o, #x%x, %s)" value value char-string
)
1400 (format " (#o%o, #x%x)" value value
)))))
1402 (defvar eval-expression-minibuffer-setup-hook nil
1403 "Hook run by `eval-expression' when entering the minibuffer.")
1405 (defun read--expression (prompt &optional initial-contents
)
1406 (let ((minibuffer-completing-symbol t
))
1407 (minibuffer-with-setup-hook
1409 ;; FIXME: call emacs-lisp-mode?
1410 (setq-local eldoc-documentation-function
1411 #'elisp-eldoc-documentation-function
)
1412 (add-hook 'completion-at-point-functions
1413 #'elisp-completion-at-point nil t
)
1414 (run-hooks 'eval-expression-minibuffer-setup-hook
))
1415 (read-from-minibuffer prompt initial-contents
1416 read-expression-map t
1417 'read-expression-history
))))
1419 ;; We define this, rather than making `eval' interactive,
1420 ;; for the sake of completion of names like eval-region, eval-buffer.
1421 (defun eval-expression (exp &optional insert-value
)
1422 "Evaluate EXP and print value in the echo area.
1423 When called interactively, read an Emacs Lisp expression and evaluate it.
1424 Value is also consed on to front of the variable `values'.
1425 Optional argument INSERT-VALUE non-nil (interactively, with prefix
1426 argument) means insert the result into the current buffer instead of
1427 printing it in the echo area.
1429 Normally, this function truncates long output according to the value
1430 of the variables `eval-expression-print-length' and
1431 `eval-expression-print-level'. With a prefix argument of zero,
1432 however, there is no such truncation. Such a prefix argument
1433 also causes integers to be printed in several additional formats
1434 \(octal, hexadecimal, and character).
1436 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1439 If `eval-expression-debug-on-error' is non-nil, which is the default,
1440 this command arranges for all errors to enter the debugger."
1442 (list (read--expression "Eval: ")
1443 current-prefix-arg
))
1445 (if (null eval-expression-debug-on-error
)
1446 (push (eval exp lexical-binding
) values
)
1447 (let ((old-value (make-symbol "t")) new-value
)
1448 ;; Bind debug-on-error to something unique so that we can
1449 ;; detect when evalled code changes it.
1450 (let ((debug-on-error old-value
))
1451 (push (eval exp lexical-binding
) values
)
1452 (setq new-value debug-on-error
))
1453 ;; If evalled code has changed the value of debug-on-error,
1454 ;; propagate that change to the global binding.
1455 (unless (eq old-value new-value
)
1456 (setq debug-on-error new-value
))))
1458 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value
)))
1459 eval-expression-print-length
))
1460 (print-level (and (not (zerop (prefix-numeric-value insert-value
)))
1461 eval-expression-print-level
))
1465 (let ((standard-output (current-buffer)))
1467 (prin1 (car values
))
1468 (when (zerop (prefix-numeric-value insert-value
))
1469 (let ((str (eval-expression-print-format (car values
))))
1470 (if str
(princ str
)))))))
1472 (prin1 (car values
) t
)
1473 (let ((str (eval-expression-print-format (car values
))))
1474 (if str
(princ str t
)))))))
1476 (defun edit-and-eval-command (prompt command
)
1477 "Prompting with PROMPT, let user edit COMMAND and eval result.
1478 COMMAND is a Lisp expression. Let user edit that expression in
1479 the minibuffer, then read and evaluate the result."
1481 (let ((print-level nil
)
1482 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1484 (read-from-minibuffer prompt
1485 (prin1-to-string command
)
1486 read-expression-map t
1488 ;; If command was added to command-history as a string,
1489 ;; get rid of that. We want only evaluable expressions there.
1490 (if (stringp (car command-history
))
1491 (setq command-history
(cdr command-history
)))))))
1493 ;; If command to be redone does not match front of history,
1494 ;; add it to the history.
1495 (or (equal command
(car command-history
))
1496 (setq command-history
(cons command command-history
)))
1499 (defun repeat-complex-command (arg)
1500 "Edit and re-evaluate last complex command, or ARGth from last.
1501 A complex command is one which used the minibuffer.
1502 The command is placed in the minibuffer as a Lisp form for editing.
1503 The result is executed, repeating the command as changed.
1504 If the command has been changed or is not the most recent previous
1505 command it is added to the front of the command history.
1506 You can use the minibuffer history commands \
1507 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1508 to get different commands to edit and resubmit."
1510 (let ((elt (nth (1- arg
) command-history
))
1515 (let ((print-level nil
)
1516 (minibuffer-history-position arg
)
1517 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1519 (read-from-minibuffer
1520 "Redo: " (prin1-to-string elt
) read-expression-map t
1521 (cons 'command-history arg
))
1523 ;; If command was added to command-history as a
1524 ;; string, get rid of that. We want only
1525 ;; evaluable expressions there.
1526 (if (stringp (car command-history
))
1527 (setq command-history
(cdr command-history
))))))
1529 ;; If command to be redone does not match front of history,
1530 ;; add it to the history.
1531 (or (equal newcmd
(car command-history
))
1532 (setq command-history
(cons newcmd command-history
)))
1533 (apply #'funcall-interactively
1535 (mapcar (lambda (e) (eval e t
)) (cdr newcmd
))))
1537 (error "Argument %d is beyond length of command history" arg
)
1538 (error "There are no previous complex commands to repeat")))))
1541 (defvar extended-command-history nil
)
1543 (defun read-extended-command ()
1544 "Read command name to invoke in `execute-extended-command'."
1545 (minibuffer-with-setup-hook
1547 (set (make-local-variable 'minibuffer-default-add-function
)
1549 ;; Get a command name at point in the original buffer
1550 ;; to propose it after M-n.
1551 (with-current-buffer (window-buffer (minibuffer-selected-window))
1552 (and (commandp (function-called-at-point))
1553 (format "%S" (function-called-at-point)))))))
1554 ;; Read a string, completing from and restricting to the set of
1555 ;; all defined commands. Don't provide any initial input.
1556 ;; Save the command read on the extended-command history list.
1559 ((eq current-prefix-arg
'-
) "- ")
1560 ((and (consp current-prefix-arg
)
1561 (eq (car current-prefix-arg
) 4)) "C-u ")
1562 ((and (consp current-prefix-arg
)
1563 (integerp (car current-prefix-arg
)))
1564 (format "%d " (car current-prefix-arg
)))
1565 ((integerp current-prefix-arg
)
1566 (format "%d " current-prefix-arg
)))
1567 ;; This isn't strictly correct if `execute-extended-command'
1568 ;; is bound to anything else (e.g. [menu]).
1569 ;; It could use (key-description (this-single-command-keys)),
1570 ;; but actually a prompt other than "M-x" would be confusing,
1571 ;; because "M-x" is a well-known prompt to read a command
1572 ;; and it serves as a shorthand for "Extended command: ".
1574 obarray
'commandp t nil
'extended-command-history
)))
1576 (defcustom suggest-key-bindings t
1577 "Non-nil means show the equivalent key-binding when M-x command has one.
1578 The value can be a length of time to show the message for.
1579 If the value is non-nil and not a number, we wait 2 seconds."
1581 :type
'(choice (const :tag
"off" nil
)
1582 (integer :tag
"time" 2)
1585 (defun execute-extended-command (prefixarg &optional command-name
)
1586 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1587 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1588 "Read a command name, then read the arguments and call the command.
1589 Interactively, to pass a prefix argument to the command you are
1590 invoking, give a prefix argument to `execute-extended-command'.
1591 Noninteractively, the argument PREFIXARG is the prefix argument to
1592 give to the command you invoke."
1593 (interactive (list current-prefix-arg
(read-extended-command)))
1594 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1595 (if (null command-name
)
1596 (setq command-name
(let ((current-prefix-arg prefixarg
)) ; for prompt
1597 (read-extended-command))))
1598 (let* ((function (and (stringp command-name
) (intern-soft command-name
)))
1599 (binding (and suggest-key-bindings
1600 (not executing-kbd-macro
)
1601 (where-is-internal function overriding-local-map t
))))
1602 (unless (commandp function
)
1603 (error "`%s' is not a valid command name" command-name
))
1604 (setq this-command function
)
1605 ;; Normally `real-this-command' should never be changed, but here we really
1606 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1607 ;; binding" for <cmd>, so the command the user really wanted to run is
1608 ;; `function' and not `execute-extended-command'. The difference is
1609 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1610 (setq real-this-command function
)
1611 (let ((prefix-arg prefixarg
))
1612 (command-execute function
'record
))
1613 ;; If enabled, show which key runs this command.
1615 ;; But first wait, and skip the message if there is input.
1617 ;; If this command displayed something in the echo area;
1618 ;; wait a few seconds, then display our suggestion message.
1620 ((zerop (length (current-message))) 0)
1621 ((numberp suggest-key-bindings
) suggest-key-bindings
)
1623 (when (and waited
(not (consp unread-command-events
)))
1625 (format "You can run the command `%s' with %s"
1626 function
(key-description binding
))
1627 (sit-for (if (numberp suggest-key-bindings
)
1628 suggest-key-bindings
1631 (defun command-execute (cmd &optional record-flag keys special
)
1632 ;; BEWARE: Called directly from the C code.
1633 "Execute CMD as an editor command.
1634 CMD must be a symbol that satisfies the `commandp' predicate.
1635 Optional second arg RECORD-FLAG non-nil
1636 means unconditionally put this command in the variable `command-history'.
1637 Otherwise, that is done only if an arg is read using the minibuffer.
1638 The argument KEYS specifies the value to use instead of (this-command-keys)
1639 when reading the arguments; if it is nil, (this-command-keys) is used.
1640 The argument SPECIAL, if non-nil, means that this command is executing
1641 a special event, so ignore the prefix argument and don't clear it."
1642 (setq debug-on-next-call nil
)
1643 (let ((prefixarg (unless special
1645 (setq current-prefix-arg prefix-arg
)
1646 (setq prefix-arg nil
)))))
1647 (if (and (symbolp cmd
)
1649 disabled-command-function
)
1650 ;; FIXME: Weird calling convention!
1651 (run-hooks 'disabled-command-function
)
1655 (setq final
(indirect-function final
))
1656 (if (autoloadp final
)
1657 (setq final
(autoload-do-load final cmd
)))))
1660 ;; If requested, place the macro in the command history. For
1661 ;; other sorts of commands, call-interactively takes care of this.
1663 (push `(execute-kbd-macro ,final
,prefixarg
) command-history
)
1664 ;; Don't keep command history around forever.
1665 (when (and (numberp history-length
) (> history-length
0))
1666 (let ((cell (nthcdr history-length command-history
)))
1667 (if (consp cell
) (setcdr cell nil
)))))
1668 (execute-kbd-macro final prefixarg
))
1670 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1671 (prog1 (call-interactively cmd record-flag keys
)
1672 (when (and (symbolp cmd
)
1673 (get cmd
'byte-obsolete-info
)
1674 (not (get cmd
'command-execute-obsolete-warned
)))
1675 (put cmd
'command-execute-obsolete-warned t
)
1676 (message "%s" (macroexp--obsolete-warning
1677 cmd
(get cmd
'byte-obsolete-info
) "command"))))))))))
1679 (defvar minibuffer-history nil
1680 "Default minibuffer history list.
1681 This is used for all minibuffer input
1682 except when an alternate history list is specified.
1684 Maximum length of the history list is determined by the value
1685 of `history-length', which see.")
1686 (defvar minibuffer-history-sexp-flag nil
1687 "Control whether history list elements are expressions or strings.
1688 If the value of this variable equals current minibuffer depth,
1689 they are expressions; otherwise they are strings.
1690 \(That convention is designed to do the right thing for
1691 recursive uses of the minibuffer.)")
1692 (setq minibuffer-history-variable
'minibuffer-history
)
1693 (setq minibuffer-history-position nil
) ;; Defvar is in C code.
1694 (defvar minibuffer-history-search-history nil
)
1696 (defvar minibuffer-text-before-history nil
1697 "Text that was in this minibuffer before any history commands.
1698 This is nil if there have not yet been any history commands
1699 in this use of the minibuffer.")
1701 (add-hook 'minibuffer-setup-hook
'minibuffer-history-initialize
)
1703 (defun minibuffer-history-initialize ()
1704 (setq minibuffer-text-before-history nil
))
1706 (defun minibuffer-avoid-prompt (_new _old
)
1707 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1708 (constrain-to-field nil
(point-max)))
1710 (defcustom minibuffer-history-case-insensitive-variables nil
1711 "Minibuffer history variables for which matching should ignore case.
1712 If a history variable is a member of this list, then the
1713 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1714 commands ignore case when searching it, regardless of `case-fold-search'."
1715 :type
'(repeat variable
)
1718 (defun previous-matching-history-element (regexp n
)
1719 "Find the previous history element that matches REGEXP.
1720 \(Previous history elements refer to earlier actions.)
1721 With prefix argument N, search for Nth previous match.
1722 If N is negative, find the next or Nth next match.
1723 Normally, history elements are matched case-insensitively if
1724 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1725 makes the search case-sensitive.
1726 See also `minibuffer-history-case-insensitive-variables'."
1728 (let* ((enable-recursive-minibuffers t
)
1729 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1731 minibuffer-local-map
1733 'minibuffer-history-search-history
1734 (car minibuffer-history-search-history
))))
1735 ;; Use the last regexp specified, by default, if input is empty.
1736 (list (if (string= regexp
"")
1737 (if minibuffer-history-search-history
1738 (car minibuffer-history-search-history
)
1739 (user-error "No previous history search regexp"))
1741 (prefix-numeric-value current-prefix-arg
))))
1743 (if (and (zerop minibuffer-history-position
)
1744 (null minibuffer-text-before-history
))
1745 (setq minibuffer-text-before-history
1746 (minibuffer-contents-no-properties)))
1747 (let ((history (symbol-value minibuffer-history-variable
))
1749 (if (isearch-no-upper-case-p regexp t
) ; assume isearch.el is dumped
1750 ;; On some systems, ignore case for file names.
1751 (if (memq minibuffer-history-variable
1752 minibuffer-history-case-insensitive-variables
)
1754 ;; Respect the user's setting for case-fold-search:
1760 (pos minibuffer-history-position
))
1763 (setq pos
(min (max 1 (+ pos
(if (< n
0) -
1 1))) (length history
)))
1764 (when (= pos prevpos
)
1765 (user-error (if (= pos
1)
1766 "No later matching history item"
1767 "No earlier matching history item")))
1769 (if (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1770 (let ((print-level nil
))
1771 (prin1-to-string (nth (1- pos
) history
)))
1772 (nth (1- pos
) history
)))
1775 (and (string-match regexp match-string
)
1777 (and (string-match (concat ".*\\(" regexp
"\\)") match-string
)
1778 (match-beginning 1))))
1780 (setq n
(+ n
(if (< n
0) 1 -
1)))))
1781 (setq minibuffer-history-position pos
)
1782 (goto-char (point-max))
1783 (delete-minibuffer-contents)
1784 (insert match-string
)
1785 (goto-char (+ (minibuffer-prompt-end) match-offset
))))
1786 (if (memq (car (car command-history
)) '(previous-matching-history-element
1787 next-matching-history-element
))
1788 (setq command-history
(cdr command-history
))))
1790 (defun next-matching-history-element (regexp n
)
1791 "Find the next history element that matches REGEXP.
1792 \(The next history element refers to a more recent action.)
1793 With prefix argument N, search for Nth next match.
1794 If N is negative, find the previous or Nth previous match.
1795 Normally, history elements are matched case-insensitively if
1796 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1797 makes the search case-sensitive."
1799 (let* ((enable-recursive-minibuffers t
)
1800 (regexp (read-from-minibuffer "Next element matching (regexp): "
1802 minibuffer-local-map
1804 'minibuffer-history-search-history
1805 (car minibuffer-history-search-history
))))
1806 ;; Use the last regexp specified, by default, if input is empty.
1807 (list (if (string= regexp
"")
1808 (if minibuffer-history-search-history
1809 (car minibuffer-history-search-history
)
1810 (user-error "No previous history search regexp"))
1812 (prefix-numeric-value current-prefix-arg
))))
1813 (previous-matching-history-element regexp
(- n
)))
1815 (defvar minibuffer-temporary-goal-position nil
)
1817 (defvar minibuffer-default-add-function
'minibuffer-default-add-completions
1818 "Function run by `goto-history-element' before consuming default values.
1819 This is useful to dynamically add more elements to the list of default values
1820 when `goto-history-element' reaches the end of this list.
1821 Before calling this function `goto-history-element' sets the variable
1822 `minibuffer-default-add-done' to t, so it will call this function only
1823 once. In special cases, when this function needs to be called more
1824 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1825 overriding the setting of this variable to t in `goto-history-element'.")
1827 (defvar minibuffer-default-add-done nil
1828 "When nil, add more elements to the end of the list of default values.
1829 The value nil causes `goto-history-element' to add more elements to
1830 the list of defaults when it reaches the end of this list. It does
1831 this by calling a function defined by `minibuffer-default-add-function'.")
1833 (make-variable-buffer-local 'minibuffer-default-add-done
)
1835 (defun minibuffer-default-add-completions ()
1836 "Return a list of all completions without the default value.
1837 This function is used to add all elements of the completion table to
1838 the end of the list of defaults just after the default value."
1839 (let ((def minibuffer-default
)
1840 (all (all-completions ""
1841 minibuffer-completion-table
1842 minibuffer-completion-predicate
)))
1845 (cons def
(delete def all
)))))
1847 (defun goto-history-element (nabs)
1848 "Puts element of the minibuffer history in the minibuffer.
1849 The argument NABS specifies the absolute history position."
1851 (when (and (not minibuffer-default-add-done
)
1852 (functionp minibuffer-default-add-function
)
1853 (< nabs
(- (if (listp minibuffer-default
)
1854 (length minibuffer-default
)
1856 (setq minibuffer-default-add-done t
1857 minibuffer-default
(funcall minibuffer-default-add-function
)))
1858 (let ((minimum (if minibuffer-default
1859 (- (if (listp minibuffer-default
)
1860 (length minibuffer-default
)
1863 elt minibuffer-returned-to-present
)
1864 (if (and (zerop minibuffer-history-position
)
1865 (null minibuffer-text-before-history
))
1866 (setq minibuffer-text-before-history
1867 (minibuffer-contents-no-properties)))
1868 (if (< nabs minimum
)
1869 (user-error (if minibuffer-default
1870 "End of defaults; no next item"
1871 "End of history; no default available")))
1872 (if (> nabs
(length (symbol-value minibuffer-history-variable
)))
1873 (user-error "Beginning of history; no preceding item"))
1874 (unless (memq last-command
'(next-history-element
1875 previous-history-element
))
1876 (let ((prompt-end (minibuffer-prompt-end)))
1877 (set (make-local-variable 'minibuffer-temporary-goal-position
)
1878 (cond ((<= (point) prompt-end
) prompt-end
)
1881 (goto-char (point-max))
1882 (delete-minibuffer-contents)
1883 (setq minibuffer-history-position nabs
)
1885 (setq elt
(if (listp minibuffer-default
)
1886 (nth (1- (abs nabs
)) minibuffer-default
)
1887 minibuffer-default
)))
1889 (setq elt
(or minibuffer-text-before-history
""))
1890 (setq minibuffer-returned-to-present t
)
1891 (setq minibuffer-text-before-history nil
))
1892 (t (setq elt
(nth (1- minibuffer-history-position
)
1893 (symbol-value minibuffer-history-variable
)))))
1895 (if (and (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1896 (not minibuffer-returned-to-present
))
1897 (let ((print-level nil
))
1898 (prin1-to-string elt
))
1900 (goto-char (or minibuffer-temporary-goal-position
(point-max)))))
1902 (defun next-history-element (n)
1903 "Puts next element of the minibuffer history in the minibuffer.
1904 With argument N, it uses the Nth following element."
1907 (goto-history-element (- minibuffer-history-position n
))))
1909 (defun previous-history-element (n)
1910 "Puts previous element of the minibuffer history in the minibuffer.
1911 With argument N, it uses the Nth previous element."
1914 (goto-history-element (+ minibuffer-history-position n
))))
1916 (defun next-complete-history-element (n)
1917 "Get next history element which completes the minibuffer before the point.
1918 The contents of the minibuffer after the point are deleted, and replaced
1919 by the new completion."
1921 (let ((point-at-start (point)))
1922 (next-matching-history-element
1924 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1926 ;; next-matching-history-element always puts us at (point-min).
1927 ;; Move to the position we were at before changing the buffer contents.
1928 ;; This is still sensible, because the text before point has not changed.
1929 (goto-char point-at-start
)))
1931 (defun previous-complete-history-element (n)
1933 Get previous history element which completes the minibuffer before the point.
1934 The contents of the minibuffer after the point are deleted, and replaced
1935 by the new completion."
1937 (next-complete-history-element (- n
)))
1939 ;; For compatibility with the old subr of the same name.
1940 (defun minibuffer-prompt-width ()
1941 "Return the display width of the minibuffer prompt.
1942 Return 0 if current buffer is not a minibuffer."
1943 ;; Return the width of everything before the field at the end of
1944 ;; the buffer; this should be 0 for normal buffers.
1945 (1- (minibuffer-prompt-end)))
1947 ;; isearch minibuffer history
1948 (add-hook 'minibuffer-setup-hook
'minibuffer-history-isearch-setup
)
1950 (defvar minibuffer-history-isearch-message-overlay
)
1951 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay
)
1953 (defun minibuffer-history-isearch-setup ()
1954 "Set up a minibuffer for using isearch to search the minibuffer history.
1955 Intended to be added to `minibuffer-setup-hook'."
1956 (set (make-local-variable 'isearch-search-fun-function
)
1957 'minibuffer-history-isearch-search
)
1958 (set (make-local-variable 'isearch-message-function
)
1959 'minibuffer-history-isearch-message
)
1960 (set (make-local-variable 'isearch-wrap-function
)
1961 'minibuffer-history-isearch-wrap
)
1962 (set (make-local-variable 'isearch-push-state-function
)
1963 'minibuffer-history-isearch-push-state
)
1964 (add-hook 'isearch-mode-end-hook
'minibuffer-history-isearch-end nil t
))
1966 (defun minibuffer-history-isearch-end ()
1967 "Clean up the minibuffer after terminating isearch in the minibuffer."
1968 (if minibuffer-history-isearch-message-overlay
1969 (delete-overlay minibuffer-history-isearch-message-overlay
)))
1971 (defun minibuffer-history-isearch-search ()
1972 "Return the proper search function, for isearch in minibuffer history."
1973 (lambda (string bound noerror
)
1975 ;; Use standard functions to search within minibuffer text
1976 (isearch-search-fun-default))
1978 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
1979 ;; searching forward. Lazy-highlight calls this lambda with the
1980 ;; bound arg, so skip the minibuffer prompt.
1981 (if (and bound isearch-forward
(< (point) (minibuffer-prompt-end)))
1982 (goto-char (minibuffer-prompt-end)))
1984 ;; 1. First try searching in the initial minibuffer text
1985 (funcall search-fun string
1986 (if isearch-forward bound
(minibuffer-prompt-end))
1988 ;; 2. If the above search fails, start putting next/prev history
1989 ;; elements in the minibuffer successively, and search the string
1990 ;; in them. Do this only when bound is nil (i.e. not while
1991 ;; lazy-highlighting search strings in the current minibuffer text).
1996 (cond (isearch-forward
1997 (next-history-element 1)
1998 (goto-char (minibuffer-prompt-end)))
2000 (previous-history-element 1)
2001 (goto-char (point-max))))
2002 (setq isearch-barrier
(point) isearch-opoint
(point))
2003 ;; After putting the next/prev history element, search
2004 ;; the string in them again, until next-history-element
2005 ;; or previous-history-element raises an error at the
2006 ;; beginning/end of history.
2007 (setq found
(funcall search-fun string
2008 (unless isearch-forward
2009 ;; For backward search, don't search
2010 ;; in the minibuffer prompt
2011 (minibuffer-prompt-end))
2013 ;; Return point of the new search result
2015 ;; Return nil when next(prev)-history-element fails
2018 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis
)
2019 "Display the minibuffer history search prompt.
2020 If there are no search errors, this function displays an overlay with
2021 the isearch prompt which replaces the original minibuffer prompt.
2022 Otherwise, it displays the standard isearch message returned from
2023 the function `isearch-message'."
2024 (if (not (and (minibufferp) isearch-success
(not isearch-error
)))
2025 ;; Use standard function `isearch-message' when not in the minibuffer,
2026 ;; or search fails, or has an error (like incomplete regexp).
2027 ;; This function overwrites minibuffer text with isearch message,
2028 ;; so it's possible to see what is wrong in the search string.
2029 (isearch-message c-q-hack ellipsis
)
2030 ;; Otherwise, put the overlay with the standard isearch prompt over
2031 ;; the initial minibuffer prompt.
2032 (if (overlayp minibuffer-history-isearch-message-overlay
)
2033 (move-overlay minibuffer-history-isearch-message-overlay
2034 (point-min) (minibuffer-prompt-end))
2035 (setq minibuffer-history-isearch-message-overlay
2036 (make-overlay (point-min) (minibuffer-prompt-end)))
2037 (overlay-put minibuffer-history-isearch-message-overlay
'evaporate t
))
2038 (overlay-put minibuffer-history-isearch-message-overlay
2039 'display
(isearch-message-prefix c-q-hack ellipsis
))
2040 ;; And clear any previous isearch message.
2043 (defun minibuffer-history-isearch-wrap ()
2044 "Wrap the minibuffer history search when search fails.
2045 Move point to the first history element for a forward search,
2046 or to the last history element for a backward search."
2047 ;; When `minibuffer-history-isearch-search' fails on reaching the
2048 ;; beginning/end of the history, wrap the search to the first/last
2049 ;; minibuffer history element.
2051 (goto-history-element (length (symbol-value minibuffer-history-variable
)))
2052 (goto-history-element 0))
2053 (setq isearch-success t
)
2054 (goto-char (if isearch-forward
(minibuffer-prompt-end) (point-max))))
2056 (defun minibuffer-history-isearch-push-state ()
2057 "Save a function restoring the state of minibuffer history search.
2058 Save `minibuffer-history-position' to the additional state parameter
2059 in the search status stack."
2060 (let ((pos minibuffer-history-position
))
2062 (minibuffer-history-isearch-pop-state cmd pos
))))
2064 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos
)
2065 "Restore the minibuffer history search state.
2066 Go to the history element by the absolute history position HIST-POS."
2067 (goto-history-element hist-pos
))
2070 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2071 (define-obsolete-function-alias 'advertised-undo
'undo
"23.2")
2073 (defconst undo-equiv-table
(make-hash-table :test
'eq
:weakness t
)
2074 "Table mapping redo records to the corresponding undo one.
2075 A redo record for undo-in-region maps to t.
2076 A redo record for ordinary undo maps to the following (earlier) undo.")
2078 (defvar undo-in-region nil
2079 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2081 (defvar undo-no-redo nil
2082 "If t, `undo' doesn't go through redo entries.")
2084 (defvar pending-undo-list nil
2085 "Within a run of consecutive undo commands, list remaining to be undone.
2086 If t, we undid all the way to the end of it.")
2088 (defun undo (&optional arg
)
2089 "Undo some previous changes.
2090 Repeat this command to undo more changes.
2091 A numeric ARG serves as a repeat count.
2093 In Transient Mark mode when the mark is active, only undo changes within
2094 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2095 as an argument limits undo to changes within the current region."
2097 ;; Make last-command indicate for the next command that this was an undo.
2098 ;; That way, another undo will undo more.
2099 ;; If we get to the end of the undo history and get an error,
2100 ;; another undo command will find the undo history empty
2101 ;; and will get another error. To begin undoing the undos,
2102 ;; you must type some other command.
2103 (let* ((modified (buffer-modified-p))
2104 ;; For an indirect buffer, look in the base buffer for the
2106 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2107 (recent-save (with-current-buffer base-buffer
2108 (recent-auto-save-p)))
2110 ;; If we get an error in undo-start,
2111 ;; the next command should not be a "consecutive undo".
2112 ;; So set `this-command' to something other than `undo'.
2113 (setq this-command
'undo-start
)
2115 (unless (and (eq last-command
'undo
)
2116 (or (eq pending-undo-list t
)
2117 ;; If something (a timer or filter?) changed the buffer
2118 ;; since the previous command, don't continue the undo seq.
2119 (let ((list buffer-undo-list
))
2120 (while (eq (car list
) nil
)
2121 (setq list
(cdr list
)))
2122 ;; If the last undo record made was made by undo
2123 ;; it shows nothing else happened in between.
2124 (gethash list undo-equiv-table
))))
2125 (setq undo-in-region
2126 (or (region-active-p) (and arg
(not (numberp arg
)))))
2128 (undo-start (region-beginning) (region-end))
2130 ;; get rid of initial undo boundary
2132 ;; If we got this far, the next command should be a consecutive undo.
2133 (setq this-command
'undo
)
2134 ;; Check to see whether we're hitting a redo record, and if
2135 ;; so, ask the user whether she wants to skip the redo/undo pair.
2136 (let ((equiv (gethash pending-undo-list undo-equiv-table
)))
2137 (or (eq (selected-window) (minibuffer-window))
2138 (setq message
(format "%s%s!"
2139 (if (or undo-no-redo
(not equiv
))
2141 (if undo-in-region
" in region" ""))))
2142 (when (and (consp equiv
) undo-no-redo
)
2143 ;; The equiv entry might point to another redo record if we have done
2144 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2145 (while (let ((next (gethash equiv undo-equiv-table
)))
2146 (if next
(setq equiv next
))))
2147 (setq pending-undo-list equiv
)))
2150 (prefix-numeric-value arg
)
2152 ;; Record the fact that the just-generated undo records come from an
2153 ;; undo operation--that is, they are redo records.
2154 ;; In the ordinary case (not within a region), map the redo
2155 ;; record to the following undos.
2156 ;; I don't know how to do that in the undo-in-region case.
2157 (let ((list buffer-undo-list
))
2158 ;; Strip any leading undo boundaries there might be, like we do
2159 ;; above when checking.
2160 (while (eq (car list
) nil
)
2161 (setq list
(cdr list
)))
2163 ;; Prevent identity mapping. This can happen if
2164 ;; consecutive nils are erroneously in undo list.
2165 (if (or undo-in-region
(eq list pending-undo-list
))
2169 ;; Don't specify a position in the undo record for the undo command.
2170 ;; Instead, undoing this should move point to where the change is.
2171 (let ((tail buffer-undo-list
)
2174 (when (integerp (car tail
))
2175 (let ((pos (car tail
)))
2177 (setcdr prev
(cdr tail
))
2178 (setq buffer-undo-list
(cdr tail
)))
2179 (setq tail
(cdr tail
))
2181 (if (eq pos
(car tail
))
2183 (setcdr prev
(cdr tail
))
2184 (setq buffer-undo-list
(cdr tail
)))
2186 (setq tail
(cdr tail
)))
2188 (setq prev tail tail
(cdr tail
))))
2189 ;; Record what the current undo list says,
2190 ;; so the next command can tell if the buffer was modified in between.
2191 (and modified
(not (buffer-modified-p))
2192 (with-current-buffer base-buffer
2193 (delete-auto-save-file-if-necessary recent-save
)))
2194 ;; Display a message announcing success.
2196 (message "%s" message
))))
2198 (defun buffer-disable-undo (&optional buffer
)
2199 "Make BUFFER stop keeping undo information.
2200 No argument or nil as argument means do this for the current buffer."
2202 (with-current-buffer (if buffer
(get-buffer buffer
) (current-buffer))
2203 (setq buffer-undo-list t
)))
2205 (defun undo-only (&optional arg
)
2206 "Undo some previous changes.
2207 Repeat this command to undo more changes.
2208 A numeric ARG serves as a repeat count.
2209 Contrary to `undo', this will not redo a previous undo."
2211 (let ((undo-no-redo t
)) (undo arg
)))
2213 (defvar undo-in-progress nil
2214 "Non-nil while performing an undo.
2215 Some change-hooks test this variable to do something different.")
2217 (defun undo-more (n)
2218 "Undo back N undo-boundaries beyond what was already undone recently.
2219 Call `undo-start' to get ready to undo recent changes,
2220 then call `undo-more' one or more times to undo them."
2221 (or (listp pending-undo-list
)
2222 (user-error (concat "No further undo information"
2223 (and undo-in-region
" for region"))))
2224 (let ((undo-in-progress t
))
2225 ;; Note: The following, while pulling elements off
2226 ;; `pending-undo-list' will call primitive change functions which
2227 ;; will push more elements onto `buffer-undo-list'.
2228 (setq pending-undo-list
(primitive-undo n pending-undo-list
))
2229 (if (null pending-undo-list
)
2230 (setq pending-undo-list t
))))
2232 (defun primitive-undo (n list
)
2233 "Undo N records from the front of the list LIST.
2234 Return what remains of the list."
2236 ;; This is a good feature, but would make undo-start
2237 ;; unable to do what is expected.
2238 ;;(when (null (car (list)))
2239 ;; ;; If the head of the list is a boundary, it is the boundary
2240 ;; ;; preceding this command. Get rid of it and don't count it.
2241 ;; (setq list (cdr list))))
2244 ;; In a writable buffer, enable undoing read-only text that is
2245 ;; so because of text properties.
2246 (inhibit-read-only t
)
2247 ;; Don't let `intangible' properties interfere with undo.
2248 (inhibit-point-motion-hooks t
)
2249 ;; We use oldlist only to check for EQ. ++kfs
2250 (oldlist buffer-undo-list
)
2254 (while (setq next
(pop list
)) ;Exit inner loop at undo boundary.
2255 ;; Handle an integer by setting point to that value.
2257 ((pred integerp
) (goto-char next
))
2258 ;; Element (t . TIME) records previous modtime.
2259 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2260 ;; UNKNOWN_MODTIME_NSECS.
2262 ;; If this records an obsolete save
2263 ;; (not matching the actual disk file)
2264 ;; then don't mark unmodified.
2265 (when (or (equal time
(visited-file-modtime))
2267 (equal (list (car time
) (cdr time
))
2268 (visited-file-modtime))))
2269 (when (fboundp 'unlock-buffer
)
2271 (set-buffer-modified-p nil
)))
2272 ;; Element (nil PROP VAL BEG . END) is property change.
2273 (`(nil .
,(or `(,prop
,val
,beg .
,end
) pcase--dontcare
))
2274 (when (or (> (point-min) beg
) (< (point-max) end
))
2275 (error "Changes to be undone are outside visible portion of buffer"))
2276 (put-text-property beg end prop val
))
2277 ;; Element (BEG . END) means range was inserted.
2278 (`(,(and beg
(pred integerp
)) .
,(and end
(pred integerp
)))
2279 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2280 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2281 (when (or (> (point-min) beg
) (< (point-max) end
))
2282 (error "Changes to be undone are outside visible portion of buffer"))
2283 ;; Set point first thing, so that undoing this undo
2284 ;; does not send point back to where it is now.
2286 (delete-region beg end
))
2287 ;; Element (apply FUN . ARGS) means call FUN to undo.
2288 (`(apply .
,fun-args
)
2289 (let ((currbuff (current-buffer)))
2290 (if (integerp (car fun-args
))
2291 ;; Long format: (apply DELTA START END FUN . ARGS).
2292 (pcase-let* ((`(,delta
,start
,end
,fun .
,args
) fun-args
)
2293 (start-mark (copy-marker start nil
))
2294 (end-mark (copy-marker end t
)))
2295 (when (or (> (point-min) start
) (< (point-max) end
))
2296 (error "Changes to be undone are outside visible portion of buffer"))
2297 (apply fun args
) ;; Use `save-current-buffer'?
2298 ;; Check that the function did what the entry
2299 ;; said it would do.
2300 (unless (and (= start start-mark
)
2301 (= (+ delta end
) end-mark
))
2302 (error "Changes to be undone by function different than announced"))
2303 (set-marker start-mark nil
)
2304 (set-marker end-mark nil
))
2306 (unless (eq currbuff
(current-buffer))
2307 (error "Undo function switched buffer"))
2308 (setq did-apply t
)))
2309 ;; Element (STRING . POS) means STRING was deleted.
2310 (`(,(and string
(pred stringp
)) .
,(and pos
(pred integerp
)))
2311 (when (let ((apos (abs pos
)))
2312 (or (< apos
(point-min)) (> apos
(point-max))))
2313 (error "Changes to be undone are outside visible portion of buffer"))
2314 (let (valid-marker-adjustments)
2315 ;; Check that marker adjustments which were recorded
2316 ;; with the (STRING . POS) record are still valid, ie
2317 ;; the markers haven't moved. We check their validity
2318 ;; before reinserting the string so as we don't need to
2319 ;; mind marker insertion-type.
2320 (while (and (markerp (car-safe (car list
)))
2321 (integerp (cdr-safe (car list
))))
2322 (let* ((marker-adj (pop list
))
2323 (m (car marker-adj
)))
2324 (and (eq (marker-buffer m
) (current-buffer))
2326 (push marker-adj valid-marker-adjustments
))))
2327 ;; Insert string and adjust point
2335 ;; Adjust the valid marker adjustments
2336 (dolist (adj valid-marker-adjustments
)
2337 (set-marker (car adj
)
2338 (- (car adj
) (cdr adj
))))))
2339 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2340 (`(,(and marker
(pred markerp
)) .
,(and offset
(pred integerp
)))
2341 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2343 ;; Even though these elements are not expected in the undo
2344 ;; list, adjust them to be conservative for the 24.4
2345 ;; release. (Bug#16818)
2346 (when (marker-buffer marker
)
2349 (marker-buffer marker
))))
2350 (_ (error "Unrecognized entry in undo list %S" next
))))
2351 (setq arg
(1- arg
)))
2352 ;; Make sure an apply entry produces at least one undo entry,
2353 ;; so the test in `undo' for continuing an undo series
2356 (eq oldlist buffer-undo-list
))
2357 (setq buffer-undo-list
2358 (cons (list 'apply
'cdr nil
) buffer-undo-list
))))
2361 ;; Deep copy of a list
2362 (defun undo-copy-list (list)
2363 "Make a copy of undo list LIST."
2364 (mapcar 'undo-copy-list-1 list
))
2366 (defun undo-copy-list-1 (elt)
2368 (cons (car elt
) (undo-copy-list-1 (cdr elt
)))
2371 (defun undo-start (&optional beg end
)
2372 "Set `pending-undo-list' to the front of the undo list.
2373 The next call to `undo-more' will undo the most recently made change.
2374 If BEG and END are specified, then only undo elements
2375 that apply to text between BEG and END are used; other undo elements
2376 are ignored. If BEG and END are nil, all undo elements are used."
2377 (if (eq buffer-undo-list t
)
2378 (user-error "No undo information in this buffer"))
2379 (setq pending-undo-list
2380 (if (and beg end
(not (= beg end
)))
2381 (undo-make-selective-list (min beg end
) (max beg end
))
2384 ;; The positions given in elements of the undo list are the positions
2385 ;; as of the time that element was recorded to undo history. In
2386 ;; general, subsequent buffer edits render those positions invalid in
2387 ;; the current buffer, unless adjusted according to the intervening
2390 ;; Undo in region is a use case that requires adjustments to undo
2391 ;; elements. It must adjust positions of elements in the region based
2392 ;; on newer elements not in the region so as they may be correctly
2393 ;; applied in the current buffer. undo-make-selective-list
2394 ;; accomplishes this with its undo-deltas list of adjustments. An
2395 ;; example undo history from oldest to newest:
2398 ;; 123456789 buffer-undo-list undo-deltas
2399 ;; --------- ---------------- -----------
2400 ;; aaa (1 . 4) (1 . -3)
2401 ;; aaba (3 . 4) N/A (in region)
2402 ;; ccaaba (1 . 3) (1 . -2)
2403 ;; ccaabaddd (7 . 10) (7 . -3)
2404 ;; ccaabdd ("ad" . 6) (6 . 2)
2405 ;; ccaabaddd (6 . 8) (6 . -2)
2406 ;; | |<-- region: "caab", from 2 to 6
2408 ;; When the user starts a run of undos in region,
2409 ;; undo-make-selective-list is called to create the full list of in
2410 ;; region elements. Each element is adjusted forward chronologically
2411 ;; through undo-deltas to determine if it is in the region.
2413 ;; In the above example, the insertion of "b" is (3 . 4) in the
2414 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2415 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2416 ;; . 6) is assessed as in the region and placed in the selective list.
2417 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2418 ;; due to the selected element. The "b" insertion is the only element
2419 ;; fully in the region, so in this example undo-make-selective-list
2420 ;; returns (nil (5 . 6)).
2422 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2423 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2424 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2425 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2426 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2428 ;; More interesting is how to adjust the "ddd" insertion due to the
2429 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2430 ;; If the reinsertion was a manual retyping of "ad", then the total
2431 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2432 ;; the reinsertion was due to undo, one might expect the first "d"
2433 ;; character would again be a part of the "ddd" text, meaning its
2434 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2436 ;; undo-make-selective-list assumes in this situation that "ad" was a
2437 ;; new edit, even if it was inserted because of an undo.
2438 ;; Consequently, if the user undos in region "8 to 10" of the
2439 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2440 ;; "ccaabad", as though the first "d" became detached from the
2441 ;; original "ddd" insertion. This quirk is a FIXME.
2443 (defun undo-make-selective-list (start end
)
2444 "Return a list of undo elements for the region START to END.
2445 The elements come from `buffer-undo-list', but we keep only the
2446 elements inside this region, and discard those outside this
2447 region. The elements' positions are adjusted so as the returned
2448 list can be applied to the current buffer."
2449 (let ((ulist buffer-undo-list
)
2450 ;; A list of position adjusted undo elements in the region.
2451 (selective-list (list nil
))
2452 ;; A list of undo-deltas for out of region undo elements.
2457 (while (gethash ulist undo-equiv-table
)
2458 (setq ulist
(gethash ulist undo-equiv-table
))))
2459 (setq undo-elt
(car ulist
))
2462 ;; Don't put two nils together in the list
2463 (when (car selective-list
)
2464 (push nil selective-list
)))
2465 ((and (consp undo-elt
) (eq (car undo-elt
) t
))
2466 ;; This is a "was unmodified" element. Keep it
2467 ;; if we have kept everything thus far.
2468 (when (not undo-deltas
)
2469 (push undo-elt selective-list
)))
2470 ;; Skip over marker adjustments, instead relying
2471 ;; on finding them after (TEXT . POS) elements
2472 ((markerp (car-safe undo-elt
))
2475 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2477 (if (undo-elt-in-region adjusted-undo-elt start end
)
2479 (setq end
(+ end
(cdr (undo-delta adjusted-undo-elt
))))
2480 (push adjusted-undo-elt selective-list
)
2481 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2482 ;; kept. primitive-undo may discard them later.
2483 (when (and (stringp (car-safe adjusted-undo-elt
))
2484 (integerp (cdr-safe adjusted-undo-elt
)))
2485 (let ((list-i (cdr ulist
)))
2486 (while (markerp (car-safe (car list-i
)))
2487 (push (pop list-i
) selective-list
)))))
2488 (let ((delta (undo-delta undo-elt
)))
2489 (when (/= 0 (cdr delta
))
2490 (push delta undo-deltas
)))))))
2492 (nreverse selective-list
)))
2494 (defun undo-elt-in-region (undo-elt start end
)
2495 "Determine whether UNDO-ELT falls inside the region START ... END.
2496 If it crosses the edge, we return nil.
2498 Generally this function is not useful for determining
2499 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2500 because markers can be arbitrarily relocated. Instead, pass the
2501 marker adjustment's corresponding (TEXT . POS) element."
2502 (cond ((integerp undo-elt
)
2503 (and (>= undo-elt start
)
2509 ((stringp (car undo-elt
))
2510 ;; (TEXT . POSITION)
2511 (and (>= (abs (cdr undo-elt
)) start
)
2512 (<= (abs (cdr undo-elt
)) end
)))
2513 ((and (consp undo-elt
) (markerp (car undo-elt
)))
2514 ;; (MARKER . ADJUSTMENT)
2515 (<= start
(car undo-elt
) end
))
2516 ((null (car undo-elt
))
2517 ;; (nil PROPERTY VALUE BEG . END)
2518 (let ((tail (nthcdr 3 undo-elt
)))
2519 (and (>= (car tail
) start
)
2520 (<= (cdr tail
) end
))))
2521 ((integerp (car undo-elt
))
2523 (and (>= (car undo-elt
) start
)
2524 (<= (cdr undo-elt
) end
)))))
2526 (defun undo-elt-crosses-region (undo-elt start end
)
2527 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2528 This assumes we have already decided that UNDO-ELT
2529 is not *inside* the region START...END."
2530 (declare (obsolete nil
"25.1"))
2531 (cond ((atom undo-elt
) nil
)
2532 ((null (car undo-elt
))
2533 ;; (nil PROPERTY VALUE BEG . END)
2534 (let ((tail (nthcdr 3 undo-elt
)))
2535 (and (< (car tail
) end
)
2536 (> (cdr tail
) start
))))
2537 ((integerp (car undo-elt
))
2539 (and (< (car undo-elt
) end
)
2540 (> (cdr undo-elt
) start
)))))
2542 (defun undo-adjust-elt (elt deltas
)
2543 "Return adjustment of undo element ELT by the undo DELTAS
2548 (undo-adjust-pos elt deltas
))
2550 (`(,(and beg
(pred integerp
)) .
,(and end
(pred integerp
)))
2551 (undo-adjust-beg-end beg end deltas
))
2552 ;; (TEXT . POSITION)
2553 (`(,(and text
(pred stringp
)) .
,(and pos
(pred integerp
)))
2554 (cons text
(* (if (< pos
0) -
1 1)
2555 (undo-adjust-pos (abs pos
) deltas
))))
2556 ;; (nil PROPERTY VALUE BEG . END)
2557 (`(nil .
,(or `(,prop
,val
,beg .
,end
) pcase--dontcare
))
2558 `(nil ,prop
,val .
,(undo-adjust-beg-end beg end deltas
)))
2559 ;; (apply DELTA START END FUN . ARGS)
2561 ;; All others return same elt
2564 ;; (BEG . END) can adjust to the same positions, commonly when an
2565 ;; insertion was undone and they are out of region, for example:
2568 ;; 123456789 buffer-undo-list undo-deltas
2569 ;; --------- ---------------- -----------
2571 ;; abbaa (2 . 4) (2 . -2)
2572 ;; aaa ("bb" . 2) (2 . 2)
2575 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2576 ;; undo. Further adjustments to such an element should be the same as
2577 ;; for (TEXT . POSITION) elements. The options are:
2579 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2580 ;; analogous to marker insertion-type t.
2582 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2583 ;; marker insertion-type nil.
2585 ;; There was no strong reason to prefer one or the other, except that
2586 ;; the first is more consistent with prior undo in region behavior.
2587 (defun undo-adjust-beg-end (beg end deltas
)
2588 "Return cons of adjustments to BEG and END by the undo DELTAS
2590 (let ((adj-beg (undo-adjust-pos beg deltas
)))
2591 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2593 (max adj-beg
(undo-adjust-pos end deltas t
)))))
2595 (defun undo-adjust-pos (pos deltas
&optional use-
<)
2596 "Return adjustment of POS by the undo DELTAS list, comparing
2597 with < or <= based on USE-<."
2598 (dolist (d deltas pos
)
2603 ;; Don't allow pos to become less than the undo-delta
2604 ;; position. This edge case is described in the overview
2606 (max (car d
) (- pos
(cdr d
)))))))
2608 ;; Return the first affected buffer position and the delta for an undo element
2609 ;; delta is defined as the change in subsequent buffer positions if we *did*
2611 (defun undo-delta (undo-elt)
2612 (if (consp undo-elt
)
2613 (cond ((stringp (car undo-elt
))
2614 ;; (TEXT . POSITION)
2615 (cons (abs (cdr undo-elt
)) (length (car undo-elt
))))
2616 ((integerp (car undo-elt
))
2618 (cons (car undo-elt
) (- (car undo-elt
) (cdr undo-elt
))))
2623 (defcustom undo-ask-before-discard nil
2624 "If non-nil ask about discarding undo info for the current command.
2625 Normally, Emacs discards the undo info for the current command if
2626 it exceeds `undo-outer-limit'. But if you set this option
2627 non-nil, it asks in the echo area whether to discard the info.
2628 If you answer no, there is a slight risk that Emacs might crash, so
2629 only do it if you really want to undo the command.
2631 This option is mainly intended for debugging. You have to be
2632 careful if you use it for other purposes. Garbage collection is
2633 inhibited while the question is asked, meaning that Emacs might
2634 leak memory. So you should make sure that you do not wait
2635 excessively long before answering the question."
2640 (defvar undo-extra-outer-limit nil
2641 "If non-nil, an extra level of size that's ok in an undo item.
2642 We don't ask the user about truncating the undo list until the
2643 current item gets bigger than this amount.
2645 This variable only matters if `undo-ask-before-discard' is non-nil.")
2646 (make-variable-buffer-local 'undo-extra-outer-limit
)
2648 ;; When the first undo batch in an undo list is longer than
2649 ;; undo-outer-limit, this function gets called to warn the user that
2650 ;; the undo info for the current command was discarded. Garbage
2651 ;; collection is inhibited around the call, so it had better not do a
2653 (setq undo-outer-limit-function
'undo-outer-limit-truncate
)
2654 (defun undo-outer-limit-truncate (size)
2655 (if undo-ask-before-discard
2656 (when (or (null undo-extra-outer-limit
)
2657 (> size undo-extra-outer-limit
))
2658 ;; Don't ask the question again unless it gets even bigger.
2659 ;; This applies, in particular, if the user quits from the question.
2660 ;; Such a quit quits out of GC, but something else will call GC
2661 ;; again momentarily. It will call this function again,
2662 ;; but we don't want to ask the question again.
2663 (setq undo-extra-outer-limit
(+ size
50000))
2664 (if (let (use-dialog-box track-mouse executing-kbd-macro
)
2665 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
2666 (buffer-name) size
)))
2667 (progn (setq buffer-undo-list nil
)
2668 (setq undo-extra-outer-limit nil
)
2671 (display-warning '(undo discard-info
)
2673 (format "Buffer `%s' undo info was %d bytes long.\n"
2675 "The undo info was discarded because it exceeded \
2678 This is normal if you executed a command that made a huge change
2679 to the buffer. In that case, to prevent similar problems in the
2680 future, set `undo-outer-limit' to a value that is large enough to
2681 cover the maximum size of normal changes you expect a single
2682 command to make, but not so large that it might exceed the
2683 maximum memory allotted to Emacs.
2685 If you did not execute any such command, the situation is
2686 probably due to a bug and you should report it.
2688 You can disable the popping up of this buffer by adding the entry
2689 \(undo discard-info) to the user option `warning-suppress-types',
2690 which is defined in the `warnings' library.\n")
2692 (setq buffer-undo-list nil
)
2695 (defcustom password-word-equivalents
2696 '("password" "passphrase" "pass phrase"
2697 ; These are sorted according to the GNU en_US locale.
2700 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
2726 "пароль" ; kk, ru, uk
2741 "List of words equivalent to \"password\".
2742 This is used by Shell mode and other parts of Emacs to recognize
2743 password prompts, including prompts in languages other than
2744 English. Different case choices should not be assumed to be
2745 included; callers should bind `case-fold-search' to t."
2746 :type
'(repeat string
)
2750 (defvar shell-command-history nil
2751 "History list for some commands that read shell commands.
2753 Maximum length of the history list is determined by the value
2754 of `history-length', which see.")
2756 (defvar shell-command-switch
(purecopy "-c")
2757 "Switch used to have the shell execute its command line argument.")
2759 (defvar shell-command-default-error-buffer nil
2760 "Buffer name for `shell-command' and `shell-command-on-region' error output.
2761 This buffer is used when `shell-command' or `shell-command-on-region'
2762 is run interactively. A value of nil means that output to stderr and
2763 stdout will be intermixed in the output stream.")
2765 (declare-function mailcap-file-default-commands
"mailcap" (files))
2766 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
2768 (defun minibuffer-default-add-shell-commands ()
2769 "Return a list of all commands associated with the current file.
2770 This function is used to add all related commands retrieved by `mailcap'
2771 to the end of the list of defaults just after the default value."
2773 (let* ((filename (if (listp minibuffer-default
)
2774 (car minibuffer-default
)
2775 minibuffer-default
))
2776 (commands (and filename
(require 'mailcap nil t
)
2777 (mailcap-file-default-commands (list filename
)))))
2778 (setq commands
(mapcar (lambda (command)
2779 (concat command
" " filename
))
2781 (if (listp minibuffer-default
)
2782 (append minibuffer-default commands
)
2783 (cons minibuffer-default commands
))))
2785 (declare-function shell-completion-vars
"shell" ())
2787 (defvar minibuffer-local-shell-command-map
2788 (let ((map (make-sparse-keymap)))
2789 (set-keymap-parent map minibuffer-local-map
)
2790 (define-key map
"\t" 'completion-at-point
)
2792 "Keymap used for completing shell commands in minibuffer.")
2794 (defun read-shell-command (prompt &optional initial-contents hist
&rest args
)
2795 "Read a shell command from the minibuffer.
2796 The arguments are the same as the ones of `read-from-minibuffer',
2797 except READ and KEYMAP are missing and HIST defaults
2798 to `shell-command-history'."
2800 (minibuffer-with-setup-hook
2802 (shell-completion-vars)
2803 (set (make-local-variable 'minibuffer-default-add-function
)
2804 'minibuffer-default-add-shell-commands
))
2805 (apply 'read-from-minibuffer prompt initial-contents
2806 minibuffer-local-shell-command-map
2808 (or hist
'shell-command-history
)
2811 (defcustom async-shell-command-buffer
'confirm-new-buffer
2812 "What to do when the output buffer is used by another shell command.
2813 This option specifies how to resolve the conflict where a new command
2814 wants to direct its output to the buffer `*Async Shell Command*',
2815 but this buffer is already taken by another running shell command.
2817 The value `confirm-kill-process' is used to ask for confirmation before
2818 killing the already running process and running a new process
2819 in the same buffer, `confirm-new-buffer' for confirmation before running
2820 the command in a new buffer with a name other than the default buffer name,
2821 `new-buffer' for doing the same without confirmation,
2822 `confirm-rename-buffer' for confirmation before renaming the existing
2823 output buffer and running a new command in the default buffer,
2824 `rename-buffer' for doing the same without confirmation."
2825 :type
'(choice (const :tag
"Confirm killing of running command"
2826 confirm-kill-process
)
2827 (const :tag
"Confirm creation of a new buffer"
2829 (const :tag
"Create a new buffer"
2831 (const :tag
"Confirm renaming of existing buffer"
2832 confirm-rename-buffer
)
2833 (const :tag
"Rename the existing buffer"
2838 (defun async-shell-command (command &optional output-buffer error-buffer
)
2839 "Execute string COMMAND asynchronously in background.
2841 Like `shell-command', but adds `&' at the end of COMMAND
2842 to execute it asynchronously.
2844 The output appears in the buffer `*Async Shell Command*'.
2845 That buffer is in shell mode.
2847 You can configure `async-shell-command-buffer' to specify what to do in
2848 case when `*Async Shell Command*' buffer is already taken by another
2849 running shell command. To run COMMAND without displaying the output
2850 in a window you can configure `display-buffer-alist' to use the action
2851 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
2853 In Elisp, you will often be better served by calling `start-process'
2854 directly, since it offers more control and does not impose the use of a
2855 shell (with its need to quote arguments)."
2858 (read-shell-command "Async shell command: " nil nil
2862 ((eq major-mode
'dired-mode
)
2863 (dired-get-filename nil t
)))))
2864 (and filename
(file-relative-name filename
))))
2866 shell-command-default-error-buffer
))
2867 (unless (string-match "&[ \t]*\\'" command
)
2868 (setq command
(concat command
" &")))
2869 (shell-command command output-buffer error-buffer
))
2871 (defun shell-command (command &optional output-buffer error-buffer
)
2872 "Execute string COMMAND in inferior shell; display output, if any.
2873 With prefix argument, insert the COMMAND's output at point.
2875 If COMMAND ends in `&', execute it asynchronously.
2876 The output appears in the buffer `*Async Shell Command*'.
2877 That buffer is in shell mode. You can also use
2878 `async-shell-command' that automatically adds `&'.
2880 Otherwise, COMMAND is executed synchronously. The output appears in
2881 the buffer `*Shell Command Output*'. If the output is short enough to
2882 display in the echo area (which is determined by the variables
2883 `resize-mini-windows' and `max-mini-window-height'), it is shown
2884 there, but it is nonetheless available in buffer `*Shell Command
2885 Output*' even though that buffer is not automatically displayed.
2887 To specify a coding system for converting non-ASCII characters
2888 in the shell command output, use \\[universal-coding-system-argument] \
2889 before this command.
2891 Noninteractive callers can specify coding systems by binding
2892 `coding-system-for-read' and `coding-system-for-write'.
2894 The optional second argument OUTPUT-BUFFER, if non-nil,
2895 says to put the output in some other buffer.
2896 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2897 If OUTPUT-BUFFER is not a buffer and not nil,
2898 insert output in current buffer. (This cannot be done asynchronously.)
2899 In either case, the buffer is first erased, and the output is
2900 inserted after point (leaving mark after it).
2902 If the command terminates without error, but generates output,
2903 and you did not specify \"insert it in the current buffer\",
2904 the output can be displayed in the echo area or in its buffer.
2905 If the output is short enough to display in the echo area
2906 \(determined by the variable `max-mini-window-height' if
2907 `resize-mini-windows' is non-nil), it is shown there.
2908 Otherwise,the buffer containing the output is displayed.
2910 If there is output and an error, and you did not specify \"insert it
2911 in the current buffer\", a message about the error goes at the end
2914 If there is no output, or if output is inserted in the current buffer,
2915 then `*Shell Command Output*' is deleted.
2917 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2918 or buffer name to which to direct the command's standard error output.
2919 If it is nil, error output is mingled with regular output.
2920 In an interactive call, the variable `shell-command-default-error-buffer'
2921 specifies the value of ERROR-BUFFER.
2923 In Elisp, you will often be better served by calling `call-process' or
2924 `start-process' directly, since it offers more control and does not impose
2925 the use of a shell (with its need to quote arguments)."
2929 (read-shell-command "Shell command: " nil nil
2933 ((eq major-mode
'dired-mode
)
2934 (dired-get-filename nil t
)))))
2935 (and filename
(file-relative-name filename
))))
2937 shell-command-default-error-buffer
))
2938 ;; Look for a handler in case default-directory is a remote file name.
2940 (find-file-name-handler (directory-file-name default-directory
)
2943 (funcall handler
'shell-command command output-buffer error-buffer
)
2944 (if (and output-buffer
2945 (not (or (bufferp output-buffer
) (stringp output-buffer
))))
2946 ;; Output goes in current buffer.
2950 (expand-file-name "scor"
2951 (or small-temporary-file-directory
2952 temporary-file-directory
)))
2954 (barf-if-buffer-read-only)
2956 ;; We do not use -f for csh; we will not support broken use of
2957 ;; .cshrcs. Even the BSD csh manual says to use
2958 ;; "if ($?prompt) exit" before things which are not useful
2959 ;; non-interactively. Besides, if someone wants their other
2960 ;; aliases for shell commands then they can still have them.
2961 (call-process shell-file-name nil
2965 nil shell-command-switch command
)
2966 (when (and error-file
(file-exists-p error-file
))
2967 (if (< 0 (nth 7 (file-attributes error-file
)))
2968 (with-current-buffer (get-buffer-create error-buffer
)
2969 (let ((pos-from-end (- (point-max) (point))))
2972 ;; Do no formatting while reading error file,
2973 ;; because that can run a shell command, and we
2974 ;; don't want that to cause an infinite recursion.
2975 (format-insert-file error-file nil
)
2976 ;; Put point after the inserted errors.
2977 (goto-char (- (point-max) pos-from-end
)))
2978 (display-buffer (current-buffer))))
2979 (delete-file error-file
))
2980 ;; This is like exchange-point-and-mark, but doesn't
2981 ;; activate the mark. It is cleaner to avoid activation,
2982 ;; even though the command loop would deactivate the mark
2983 ;; because we inserted text.
2984 (goto-char (prog1 (mark t
)
2985 (set-marker (mark-marker) (point)
2986 (current-buffer)))))
2987 ;; Output goes in a separate buffer.
2988 ;; Preserve the match data in case called from a program.
2990 (if (string-match "[ \t]*&[ \t]*\\'" command
)
2991 ;; Command ending with ampersand means asynchronous.
2992 (let ((buffer (get-buffer-create
2993 (or output-buffer
"*Async Shell Command*")))
2994 (directory default-directory
)
2996 ;; Remove the ampersand.
2997 (setq command
(substring command
0 (match-beginning 0)))
2998 ;; Ask the user what to do with already running process.
2999 (setq proc
(get-buffer-process buffer
))
3002 ((eq async-shell-command-buffer
'confirm-kill-process
)
3003 ;; If will kill a process, query first.
3004 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3006 (error "Shell command in progress")))
3007 ((eq async-shell-command-buffer
'confirm-new-buffer
)
3008 ;; If will create a new buffer, query first.
3009 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3010 (setq buffer
(generate-new-buffer
3011 (or output-buffer
"*Async Shell Command*")))
3012 (error "Shell command in progress")))
3013 ((eq async-shell-command-buffer
'new-buffer
)
3014 ;; It will create a new buffer.
3015 (setq buffer
(generate-new-buffer
3016 (or output-buffer
"*Async Shell Command*"))))
3017 ((eq async-shell-command-buffer
'confirm-rename-buffer
)
3018 ;; If will rename the buffer, query first.
3019 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3021 (with-current-buffer buffer
3023 (setq buffer
(get-buffer-create
3024 (or output-buffer
"*Async Shell Command*"))))
3025 (error "Shell command in progress")))
3026 ((eq async-shell-command-buffer
'rename-buffer
)
3027 ;; It will rename the buffer.
3028 (with-current-buffer buffer
3030 (setq buffer
(get-buffer-create
3031 (or output-buffer
"*Async Shell Command*"))))))
3032 (with-current-buffer buffer
3033 (setq buffer-read-only nil
)
3034 ;; Setting buffer-read-only to nil doesn't suffice
3035 ;; if some text has a non-nil read-only property,
3036 ;; which comint sometimes adds for prompts.
3037 (let ((inhibit-read-only t
))
3039 (display-buffer buffer
'(nil (allow-no-window . t
)))
3040 (setq default-directory directory
)
3041 (setq proc
(start-process "Shell" buffer shell-file-name
3042 shell-command-switch command
))
3043 (setq mode-line-process
'(":%s"))
3044 (require 'shell
) (shell-mode)
3045 (set-process-sentinel proc
'shell-command-sentinel
)
3046 ;; Use the comint filter for proper handling of carriage motion
3047 ;; (see `comint-inhibit-carriage-motion'),.
3048 (set-process-filter proc
'comint-output-filter
)
3050 ;; Otherwise, command is executed synchronously.
3051 (shell-command-on-region (point) (point) command
3052 output-buffer nil error-buffer
)))))))
3054 (defun display-message-or-buffer (message
3055 &optional buffer-name not-this-window frame
)
3056 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3057 MESSAGE may be either a string or a buffer.
3059 A buffer is displayed using `display-buffer' if MESSAGE is too long for
3060 the maximum height of the echo area, as defined by `max-mini-window-height'
3061 if `resize-mini-windows' is non-nil.
3063 Returns either the string shown in the echo area, or when a pop-up
3064 buffer is used, the window used to display it.
3066 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3067 name of the buffer used to display it in the case where a pop-up buffer
3068 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3069 string and it is displayed in the echo area, it is not specified whether
3070 the contents are inserted into the buffer anyway.
3072 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
3073 and only used if a buffer is displayed."
3074 (cond ((and (stringp message
) (not (string-match "\n" message
)))
3075 ;; Trivial case where we can use the echo area
3076 (message "%s" message
))
3077 ((and (stringp message
)
3078 (= (string-match "\n" message
) (1- (length message
))))
3079 ;; Trivial case where we can just remove single trailing newline
3080 (message "%s" (substring message
0 (1- (length message
)))))
3083 (with-current-buffer
3084 (if (bufferp message
)
3086 (get-buffer-create (or buffer-name
"*Message*")))
3088 (unless (bufferp message
)
3093 (if (= (buffer-size) 0)
3095 (count-screen-lines nil nil nil
(minibuffer-window)))))
3097 ((and (or (<= lines
1)
3099 (if resize-mini-windows
3100 (cond ((floatp max-mini-window-height
)
3102 max-mini-window-height
))
3103 ((integerp max-mini-window-height
)
3104 max-mini-window-height
)
3108 ;; Don't use the echo area if the output buffer is
3109 ;; already displayed in the selected frame.
3110 (not (get-buffer-window (current-buffer))))
3112 (goto-char (point-max))
3115 (message "%s" (buffer-substring (point-min) (point))))
3118 (goto-char (point-min))
3119 (display-buffer (current-buffer)
3120 not-this-window frame
))))))))
3123 ;; We have a sentinel to prevent insertion of a termination message
3124 ;; in the buffer itself.
3125 (defun shell-command-sentinel (process signal
)
3126 (if (memq (process-status process
) '(exit signal
))
3128 (car (cdr (cdr (process-command process
))))
3129 (substring signal
0 -
1))))
3131 (defun shell-command-on-region (start end command
3132 &optional output-buffer replace
3133 error-buffer display-error-buffer
)
3134 "Execute string COMMAND in inferior shell with region as input.
3135 Normally display output (if any) in temp buffer `*Shell Command Output*';
3136 Prefix arg means replace the region with it. Return the exit code of
3139 To specify a coding system for converting non-ASCII characters
3140 in the input and output to the shell command, use \\[universal-coding-system-argument]
3141 before this command. By default, the input (from the current buffer)
3142 is encoded using coding-system specified by `process-coding-system-alist',
3143 falling back to `default-process-coding-system' if no match for COMMAND
3144 is found in `process-coding-system-alist'.
3146 Noninteractive callers can specify coding systems by binding
3147 `coding-system-for-read' and `coding-system-for-write'.
3149 If the command generates output, the output may be displayed
3150 in the echo area or in a buffer.
3151 If the output is short enough to display in the echo area
3152 \(determined by the variable `max-mini-window-height' if
3153 `resize-mini-windows' is non-nil), it is shown there.
3154 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3155 The output is available in that buffer in both cases.
3157 If there is output and an error, a message about the error
3158 appears at the end of the output. If there is no output, or if
3159 output is inserted in the current buffer, the buffer `*Shell
3160 Command Output*' is deleted.
3162 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3163 command's output. If the value is a buffer or buffer name,
3164 put the output there. If the value is nil, use the buffer
3165 `*Shell Command Output*'. Any other value, excluding nil,
3166 means to insert the output in the current buffer. In either case,
3167 the output is inserted after point (leaving mark after it).
3169 Optional fifth arg REPLACE, if non-nil, means to insert the
3170 output in place of text from START to END, putting point and mark
3173 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3174 or buffer name to which to direct the command's standard error
3175 output. If nil, error output is mingled with regular output.
3176 When called interactively, `shell-command-default-error-buffer'
3177 is used for ERROR-BUFFER.
3179 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3180 display the error buffer if there were any errors. When called
3181 interactively, this is t."
3182 (interactive (let (string)
3184 (error "The mark is not set now, so there is no region"))
3185 ;; Do this before calling region-beginning
3186 ;; and region-end, in case subprocess output
3187 ;; relocates them while we are in the minibuffer.
3188 (setq string
(read-shell-command "Shell command on region: "))
3189 ;; call-interactively recognizes region-beginning and
3190 ;; region-end specially, leaving them in the history.
3191 (list (region-beginning) (region-end)
3195 shell-command-default-error-buffer
3200 (expand-file-name "scor"
3201 (or small-temporary-file-directory
3202 temporary-file-directory
)))
3207 (not (or (bufferp output-buffer
) (stringp output-buffer
)))))
3208 ;; Replace specified region with output from command.
3209 (let ((swap (and replace
(< start end
))))
3210 ;; Don't muck with mark unless REPLACE says we should.
3212 (and replace
(push-mark (point) 'nomsg
))
3214 (call-process-region start end shell-file-name replace
3218 nil shell-command-switch command
))
3219 ;; It is rude to delete a buffer which the command is not using.
3220 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3221 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3222 ;; (kill-buffer shell-buffer)))
3223 ;; Don't muck with mark unless REPLACE says we should.
3224 (and replace swap
(exchange-point-and-mark)))
3225 ;; No prefix argument: put the output in a temp buffer,
3226 ;; replacing its entire contents.
3227 (let ((buffer (get-buffer-create
3228 (or output-buffer
"*Shell Command Output*"))))
3230 (if (eq buffer
(current-buffer))
3231 ;; If the input is the same buffer as the output,
3232 ;; delete everything but the specified region,
3233 ;; then replace that region with the output.
3234 (progn (setq buffer-read-only nil
)
3235 (delete-region (max start end
) (point-max))
3236 (delete-region (point-min) (min start end
))
3238 (call-process-region (point-min) (point-max)
3243 nil shell-command-switch
3245 ;; Clear the output buffer, then run the command with
3247 (let ((directory default-directory
))
3248 (with-current-buffer buffer
3249 (setq buffer-read-only nil
)
3250 (if (not output-buffer
)
3251 (setq default-directory directory
))
3254 (call-process-region start end shell-file-name nil
3256 (list buffer error-file
)
3258 nil shell-command-switch command
)))
3259 ;; Report the output.
3260 (with-current-buffer buffer
3261 (setq mode-line-process
3262 (cond ((null exit-status
)
3264 ((stringp exit-status
)
3265 (format " - Signal [%s]" exit-status
))
3266 ((not (equal 0 exit-status
))
3267 (format " - Exit [%d]" exit-status
)))))
3268 (if (with-current-buffer buffer
(> (point-max) (point-min)))
3269 ;; There's some output, display it
3270 (display-message-or-buffer buffer
)
3271 ;; No output; error?
3274 (< 0 (nth 7 (file-attributes error-file
))))
3275 (format "some error output%s"
3276 (if shell-command-default-error-buffer
3277 (format " to the \"%s\" buffer"
3278 shell-command-default-error-buffer
)
3281 (cond ((null exit-status
)
3282 (message "(Shell command failed with error)"))
3283 ((equal 0 exit-status
)
3284 (message "(Shell command succeeded with %s)"
3286 ((stringp exit-status
)
3287 (message "(Shell command killed by signal %s)"
3290 (message "(Shell command failed with code %d and %s)"
3291 exit-status output
))))
3292 ;; Don't kill: there might be useful info in the undo-log.
3293 ;; (kill-buffer buffer)
3296 (when (and error-file
(file-exists-p error-file
))
3297 (if (< 0 (nth 7 (file-attributes error-file
)))
3298 (with-current-buffer (get-buffer-create error-buffer
)
3299 (let ((pos-from-end (- (point-max) (point))))
3302 ;; Do no formatting while reading error file,
3303 ;; because that can run a shell command, and we
3304 ;; don't want that to cause an infinite recursion.
3305 (format-insert-file error-file nil
)
3306 ;; Put point after the inserted errors.
3307 (goto-char (- (point-max) pos-from-end
)))
3308 (and display-error-buffer
3309 (display-buffer (current-buffer)))))
3310 (delete-file error-file
))
3313 (defun shell-command-to-string (command)
3314 "Execute shell command COMMAND and return its output as a string."
3315 (with-output-to-string
3316 (with-current-buffer
3318 (process-file shell-file-name nil t nil shell-command-switch command
))))
3320 (defun process-file (program &optional infile buffer display
&rest args
)
3321 "Process files synchronously in a separate process.
3322 Similar to `call-process', but may invoke a file handler based on
3323 `default-directory'. The current working directory of the
3324 subprocess is `default-directory'.
3326 File names in INFILE and BUFFER are handled normally, but file
3327 names in ARGS should be relative to `default-directory', as they
3328 are passed to the process verbatim. (This is a difference to
3329 `call-process' which does not support file handlers for INFILE
3332 Some file handlers might not support all variants, for example
3333 they might behave as if DISPLAY was nil, regardless of the actual
3335 (let ((fh (find-file-name-handler default-directory
'process-file
))
3338 (if fh
(apply fh
'process-file program infile buffer display args
)
3339 (when infile
(setq lc
(file-local-copy infile
)))
3340 (setq stderr-file
(when (and (consp buffer
) (stringp (cadr buffer
)))
3341 (make-temp-file "emacs")))
3343 (apply 'call-process program
3345 (if stderr-file
(list (car buffer
) stderr-file
) buffer
)
3347 (when stderr-file
(copy-file stderr-file
(cadr buffer
) t
))))
3348 (when stderr-file
(delete-file stderr-file
))
3349 (when lc
(delete-file lc
)))))
3351 (defvar process-file-side-effects t
3352 "Whether a call of `process-file' changes remote files.
3354 By default, this variable is always set to `t', meaning that a
3355 call of `process-file' could potentially change any file on a
3356 remote host. When set to `nil', a file handler could optimize
3357 its behavior with respect to remote file attribute caching.
3359 You should only ever change this variable with a let-binding;
3360 never with `setq'.")
3362 (defun start-file-process (name buffer program
&rest program-args
)
3363 "Start a program in a subprocess. Return the process object for it.
3365 Similar to `start-process', but may invoke a file handler based on
3366 `default-directory'. See Info node `(elisp)Magic File Names'.
3368 This handler ought to run PROGRAM, perhaps on the local host,
3369 perhaps on a remote host that corresponds to `default-directory'.
3370 In the latter case, the local part of `default-directory' becomes
3371 the working directory of the process.
3373 PROGRAM and PROGRAM-ARGS might be file names. They are not
3374 objects of file handler invocation. File handlers might not
3375 support pty association, if PROGRAM is nil."
3376 (let ((fh (find-file-name-handler default-directory
'start-file-process
)))
3377 (if fh
(apply fh
'start-file-process name buffer program program-args
)
3378 (apply 'start-process name buffer program program-args
))))
3382 (defvar tabulated-list-format
)
3383 (defvar tabulated-list-entries
)
3384 (defvar tabulated-list-sort-key
)
3385 (declare-function tabulated-list-init-header
"tabulated-list" ())
3386 (declare-function tabulated-list-print
"tabulated-list"
3387 (&optional remember-pos
))
3389 (defvar process-menu-query-only nil
)
3391 (defvar process-menu-mode-map
3392 (let ((map (make-sparse-keymap)))
3393 (define-key map
[?d
] 'process-menu-delete-process
)
3396 (define-derived-mode process-menu-mode tabulated-list-mode
"Process Menu"
3397 "Major mode for listing the processes called by Emacs."
3398 (setq tabulated-list-format
[("Process" 15 t
)
3403 (make-local-variable 'process-menu-query-only
)
3404 (setq tabulated-list-sort-key
(cons "Process" nil
))
3405 (add-hook 'tabulated-list-revert-hook
'list-processes--refresh nil t
)
3406 (tabulated-list-init-header))
3408 (defun process-menu-delete-process ()
3409 "Kill process at point in a `list-processes' buffer."
3411 (delete-process (tabulated-list-get-id))
3414 (defun list-processes--refresh ()
3415 "Recompute the list of processes for the Process List buffer.
3416 Also, delete any process that is exited or signaled."
3417 (setq tabulated-list-entries nil
)
3418 (dolist (p (process-list))
3419 (cond ((memq (process-status p
) '(exit signal closed
))
3421 ((or (not process-menu-query-only
)
3422 (process-query-on-exit-flag p
))
3423 (let* ((buf (process-buffer p
))
3424 (type (process-type p
))
3425 (name (process-name p
))
3426 (status (symbol-name (process-status p
)))
3427 (buf-label (if (buffer-live-p buf
)
3428 `(,(buffer-name buf
)
3430 help-echo
,(concat "Visit buffer `"
3431 (buffer-name buf
) "'")
3434 action process-menu-visit-buffer
)
3436 (tty (or (process-tty-name p
) "--"))
3438 (if (memq type
'(network serial
))
3439 (let ((contact (process-contact p t
)))
3440 (if (eq type
'network
)
3442 (if (plist-get contact
:type
)
3445 (if (plist-get contact
:server
)
3446 (format "server on %s"
3448 (plist-get contact
:host
)
3449 (plist-get contact
:local
)))
3450 (format "connection to %s"
3451 (plist-get contact
:host
))))
3452 (format "(serial port %s%s)"
3453 (or (plist-get contact
:port
) "?")
3454 (let ((speed (plist-get contact
:speed
)))
3456 (format " at %s b/s" speed
)
3458 (mapconcat 'identity
(process-command p
) " "))))
3459 (push (list p
(vector name status buf-label tty cmd
))
3460 tabulated-list-entries
))))))
3462 (defun process-menu-visit-buffer (button)
3463 (display-buffer (button-get button
'process-buffer
)))
3465 (defun list-processes (&optional query-only buffer
)
3466 "Display a list of all processes that are Emacs sub-processes.
3467 If optional argument QUERY-ONLY is non-nil, only processes with
3468 the query-on-exit flag set are listed.
3469 Any process listed as exited or signaled is actually eliminated
3470 after the listing is made.
3471 Optional argument BUFFER specifies a buffer to use, instead of
3473 The return value is always nil.
3475 This function lists only processes that were launched by Emacs. To
3476 see other processes running on the system, use `list-system-processes'."
3478 (or (fboundp 'process-list
)
3479 (error "Asynchronous subprocesses are not supported on this system"))
3480 (unless (bufferp buffer
)
3481 (setq buffer
(get-buffer-create "*Process List*")))
3482 (with-current-buffer buffer
3484 (setq process-menu-query-only query-only
)
3485 (list-processes--refresh)
3486 (tabulated-list-print))
3487 (display-buffer buffer
)
3490 (defvar universal-argument-map
3491 (let ((map (make-sparse-keymap))
3492 (universal-argument-minus
3493 ;; For backward compatibility, minus with no modifiers is an ordinary
3494 ;; command if digits have already been entered.
3495 `(menu-item "" negative-argument
3496 :filter
,(lambda (cmd)
3497 (if (integerp prefix-arg
) nil cmd
)))))
3498 (define-key map
[switch-frame
]
3499 (lambda (e) (interactive "e")
3500 (handle-switch-frame e
) (universal-argument--mode)))
3501 (define-key map
[?\C-u
] 'universal-argument-more
)
3502 (define-key map
[?-
] universal-argument-minus
)
3503 (define-key map
[?
0] 'digit-argument
)
3504 (define-key map
[?
1] 'digit-argument
)
3505 (define-key map
[?
2] 'digit-argument
)
3506 (define-key map
[?
3] 'digit-argument
)
3507 (define-key map
[?
4] 'digit-argument
)
3508 (define-key map
[?
5] 'digit-argument
)
3509 (define-key map
[?
6] 'digit-argument
)
3510 (define-key map
[?
7] 'digit-argument
)
3511 (define-key map
[?
8] 'digit-argument
)
3512 (define-key map
[?
9] 'digit-argument
)
3513 (define-key map
[kp-0
] 'digit-argument
)
3514 (define-key map
[kp-1
] 'digit-argument
)
3515 (define-key map
[kp-2
] 'digit-argument
)
3516 (define-key map
[kp-3
] 'digit-argument
)
3517 (define-key map
[kp-4
] 'digit-argument
)
3518 (define-key map
[kp-5
] 'digit-argument
)
3519 (define-key map
[kp-6
] 'digit-argument
)
3520 (define-key map
[kp-7
] 'digit-argument
)
3521 (define-key map
[kp-8
] 'digit-argument
)
3522 (define-key map
[kp-9
] 'digit-argument
)
3523 (define-key map
[kp-subtract
] universal-argument-minus
)
3525 "Keymap used while processing \\[universal-argument].")
3527 (defun universal-argument--mode ()
3528 (set-transient-map universal-argument-map
))
3530 (defun universal-argument ()
3531 "Begin a numeric argument for the following command.
3532 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3533 \\[universal-argument] following the digits or minus sign ends the argument.
3534 \\[universal-argument] without digits or minus sign provides 4 as argument.
3535 Repeating \\[universal-argument] without digits or minus sign
3536 multiplies the argument by 4 each time.
3537 For some commands, just \\[universal-argument] by itself serves as a flag
3538 which is different in effect from any particular numeric argument.
3539 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3541 (setq prefix-arg
(list 4))
3542 (universal-argument--mode))
3544 (defun universal-argument-more (arg)
3545 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3546 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3548 (setq prefix-arg
(if (consp arg
)
3549 (list (* 4 (car arg
)))
3553 (when (consp prefix-arg
) (universal-argument--mode)))
3555 (defun negative-argument (arg)
3556 "Begin a negative numeric argument for the next command.
3557 \\[universal-argument] following digits or minus sign ends the argument."
3559 (setq prefix-arg
(cond ((integerp arg
) (- arg
))
3562 (universal-argument--mode))
3564 (defun digit-argument (arg)
3565 "Part of the numeric argument for the next command.
3566 \\[universal-argument] following digits or minus sign ends the argument."
3568 (let* ((char (if (integerp last-command-event
)
3570 (get last-command-event
'ascii-character
)))
3571 (digit (- (logand char ?
\177) ?
0)))
3572 (setq prefix-arg
(cond ((integerp arg
)
3574 (if (< arg
0) (- digit
) digit
)))
3576 ;; Treat -0 as just -, so that -01 will work.
3577 (if (zerop digit
) '-
(- digit
)))
3580 (universal-argument--mode))
3583 (defvar filter-buffer-substring-functions nil
3584 "This variable is a wrapper hook around `buffer-substring--filter'.")
3585 (make-obsolete-variable 'filter-buffer-substring-functions
3586 'filter-buffer-substring-function
"24.4")
3588 (defvar filter-buffer-substring-function
#'buffer-substring--filter
3589 "Function to perform the filtering in `filter-buffer-substring'.
3590 The function is called with the same 3 arguments (BEG END DELETE)
3591 that `filter-buffer-substring' received. It should return the
3592 buffer substring between BEG and END, after filtering. If DELETE is
3593 non-nil, it should delete the text between BEG and END from the buffer.")
3595 (defvar buffer-substring-filters nil
3596 "List of filter functions for `buffer-substring--filter'.
3597 Each function must accept a single argument, a string, and return a string.
3598 The buffer substring is passed to the first function in the list,
3599 and the return value of each function is passed to the next.
3600 As a special convention, point is set to the start of the buffer text
3601 being operated on (i.e., the first argument of `buffer-substring--filter')
3602 before these functions are called.")
3603 (make-obsolete-variable 'buffer-substring-filters
3604 'filter-buffer-substring-function
"24.1")
3606 (defun filter-buffer-substring (beg end
&optional delete
)
3607 "Return the buffer substring between BEG and END, after filtering.
3608 If DELETE is non-nil, delete the text between BEG and END from the buffer.
3610 This calls the function that `filter-buffer-substring-function' specifies
3611 \(passing the same three arguments that it received) to do the work,
3612 and returns whatever it does. The default function does no filtering,
3613 unless a hook has been set.
3615 Use `filter-buffer-substring' instead of `buffer-substring',
3616 `buffer-substring-no-properties', or `delete-and-extract-region' when
3617 you want to allow filtering to take place. For example, major or minor
3618 modes can use `filter-buffer-substring-function' to extract characters
3619 that are special to a buffer, and should not be copied into other buffers."
3620 (funcall filter-buffer-substring-function beg end delete
))
3622 (defun buffer-substring--filter (beg end
&optional delete
)
3623 "Default function to use for `filter-buffer-substring-function'.
3624 Its arguments and return value are as specified for `filter-buffer-substring'.
3625 This respects the wrapper hook `filter-buffer-substring-functions',
3626 and the abnormal hook `buffer-substring-filters'.
3627 No filtering is done unless a hook says to."
3628 (with-wrapper-hook filter-buffer-substring-functions
(beg end delete
)
3630 ((or delete buffer-substring-filters
)
3633 (let ((string (if delete
(delete-and-extract-region beg end
)
3634 (buffer-substring beg end
))))
3635 (dolist (filter buffer-substring-filters
)
3636 (setq string
(funcall filter string
)))
3639 (buffer-substring beg end
)))))
3642 ;;;; Window system cut and paste hooks.
3644 (defvar interprogram-cut-function
#'gui-select-text
3645 "Function to call to make a killed region available to other programs.
3646 Most window systems provide a facility for cutting and pasting
3647 text between different programs, such as the clipboard on X and
3648 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3650 This variable holds a function that Emacs calls whenever text is
3651 put in the kill ring, to make the new kill available to other
3652 programs. The function takes one argument, TEXT, which is a
3653 string containing the text which should be made available.")
3655 (defvar interprogram-paste-function
#'gui-selection-value
3656 "Function to call to get text cut from other programs.
3657 Most window systems provide a facility for cutting and pasting
3658 text between different programs, such as the clipboard on X and
3659 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3661 This variable holds a function that Emacs calls to obtain text
3662 that other programs have provided for pasting. The function is
3663 called with no arguments. If no other program has provided text
3664 to paste, the function should return nil (in which case the
3665 caller, usually `current-kill', should use the top of the Emacs
3666 kill ring). If another program has provided text to paste, the
3667 function should return that text as a string (in which case the
3668 caller should put this string in the kill ring as the latest
3671 The function may also return a list of strings if the window
3672 system supports multiple selections. The first string will be
3673 used as the pasted text, but the other will be placed in the kill
3674 ring for easy access via `yank-pop'.
3676 Note that the function should return a string only if a program
3677 other than Emacs has provided a string for pasting; if Emacs
3678 provided the most recent string, the function should return nil.
3679 If it is difficult to tell whether Emacs or some other program
3680 provided the current string, it is probably good enough to return
3681 nil if the string is equal (according to `string=') to the last
3682 text Emacs provided.")
3686 ;;;; The kill ring data structure.
3688 (defvar kill-ring nil
3689 "List of killed text sequences.
3690 Since the kill ring is supposed to interact nicely with cut-and-paste
3691 facilities offered by window systems, use of this variable should
3692 interact nicely with `interprogram-cut-function' and
3693 `interprogram-paste-function'. The functions `kill-new',
3694 `kill-append', and `current-kill' are supposed to implement this
3695 interaction; you may want to use them instead of manipulating the kill
3698 (defcustom kill-ring-max
60
3699 "Maximum length of kill ring before oldest elements are thrown away."
3703 (defvar kill-ring-yank-pointer nil
3704 "The tail of the kill ring whose car is the last thing yanked.")
3706 (defcustom save-interprogram-paste-before-kill nil
3707 "Save clipboard strings into kill ring before replacing them.
3708 When one selects something in another program to paste it into Emacs,
3709 but kills something in Emacs before actually pasting it,
3710 this selection is gone unless this variable is non-nil,
3711 in which case the other program's selection is saved in the `kill-ring'
3712 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
3717 (defcustom kill-do-not-save-duplicates nil
3718 "Do not add a new string to `kill-ring' if it duplicates the last one.
3719 The comparison is done using `equal-including-properties'."
3724 (defun kill-new (string &optional replace
)
3725 "Make STRING the latest kill in the kill ring.
3726 Set `kill-ring-yank-pointer' to point to it.
3727 If `interprogram-cut-function' is non-nil, apply it to STRING.
3728 Optional second argument REPLACE non-nil means that STRING will replace
3729 the front of the kill ring, rather than being added to the list.
3731 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
3732 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3735 When the yank handler has a non-nil PARAM element, the original STRING
3736 argument is not used by `insert-for-yank'. However, since Lisp code
3737 may access and use elements from the kill ring directly, the STRING
3738 argument should still be a \"useful\" string for such uses."
3739 (unless (and kill-do-not-save-duplicates
3740 ;; Due to text properties such as 'yank-handler that
3741 ;; can alter the contents to yank, comparison using
3742 ;; `equal' is unsafe.
3743 (equal-including-properties string
(car kill-ring
)))
3744 (if (fboundp 'menu-bar-update-yank-menu
)
3745 (menu-bar-update-yank-menu string
(and replace
(car kill-ring
)))))
3746 (when save-interprogram-paste-before-kill
3747 (let ((interprogram-paste (and interprogram-paste-function
3748 (funcall interprogram-paste-function
))))
3749 (when interprogram-paste
3750 (dolist (s (if (listp interprogram-paste
)
3751 (nreverse interprogram-paste
)
3752 (list interprogram-paste
)))
3753 (unless (and kill-do-not-save-duplicates
3754 (equal-including-properties s
(car kill-ring
)))
3755 (push s kill-ring
))))))
3756 (unless (and kill-do-not-save-duplicates
3757 (equal-including-properties string
(car kill-ring
)))
3758 (if (and replace kill-ring
)
3759 (setcar kill-ring string
)
3760 (push string kill-ring
)
3761 (if (> (length kill-ring
) kill-ring-max
)
3762 (setcdr (nthcdr (1- kill-ring-max
) kill-ring
) nil
))))
3763 (setq kill-ring-yank-pointer kill-ring
)
3764 (if interprogram-cut-function
3765 (funcall interprogram-cut-function string
)))
3767 ;; It has been argued that this should work similar to `self-insert-command'
3768 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
3769 (defcustom kill-append-merge-undo nil
3770 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
3775 (defun kill-append (string before-p
)
3776 "Append STRING to the end of the latest kill in the kill ring.
3777 If BEFORE-P is non-nil, prepend STRING to the kill.
3778 Also removes the last undo boundary in the current buffer,
3779 depending on `kill-append-merge-undo'.
3780 If `interprogram-cut-function' is set, pass the resulting kill to it."
3781 (let* ((cur (car kill-ring
)))
3782 (kill-new (if before-p
(concat string cur
) (concat cur string
))
3783 (or (= (length cur
) 0)
3784 (equal nil
(get-text-property 0 'yank-handler cur
))))
3785 (when (and kill-append-merge-undo
(not buffer-read-only
))
3786 (let ((prev buffer-undo-list
)
3787 (next (cdr buffer-undo-list
)))
3788 ;; find the next undo boundary
3792 ;; remove this undo boundary
3794 (setcdr prev
(cdr next
)))))))
3796 (defcustom yank-pop-change-selection nil
3797 "Whether rotating the kill ring changes the window system selection.
3798 If non-nil, whenever the kill ring is rotated (usually via the
3799 `yank-pop' command), Emacs also calls `interprogram-cut-function'
3800 to copy the new kill to the window system selection."
3805 (defun current-kill (n &optional do-not-move
)
3806 "Rotate the yanking point by N places, and then return that kill.
3807 If N is zero and `interprogram-paste-function' is set to a
3808 function that returns a string or a list of strings, and if that
3809 function doesn't return nil, then that string (or list) is added
3810 to the front of the kill ring and the string (or first string in
3811 the list) is returned as the latest kill.
3813 If N is not zero, and if `yank-pop-change-selection' is
3814 non-nil, use `interprogram-cut-function' to transfer the
3815 kill at the new yank point into the window system selection.
3817 If optional arg DO-NOT-MOVE is non-nil, then don't actually
3818 move the yanking point; just return the Nth kill forward."
3820 (let ((interprogram-paste (and (= n
0)
3821 interprogram-paste-function
3822 (funcall interprogram-paste-function
))))
3823 (if interprogram-paste
3825 ;; Disable the interprogram cut function when we add the new
3826 ;; text to the kill ring, so Emacs doesn't try to own the
3827 ;; selection, with identical text.
3828 (let ((interprogram-cut-function nil
))
3829 (if (listp interprogram-paste
)
3830 (mapc 'kill-new
(nreverse interprogram-paste
))
3831 (kill-new interprogram-paste
)))
3833 (or kill-ring
(error "Kill ring is empty"))
3834 (let ((ARGth-kill-element
3835 (nthcdr (mod (- n
(length kill-ring-yank-pointer
))
3839 (setq kill-ring-yank-pointer ARGth-kill-element
)
3840 (when (and yank-pop-change-selection
3842 interprogram-cut-function
)
3843 (funcall interprogram-cut-function
(car ARGth-kill-element
))))
3844 (car ARGth-kill-element
)))))
3848 ;;;; Commands for manipulating the kill ring.
3850 (defcustom kill-read-only-ok nil
3851 "Non-nil means don't signal an error for killing read-only text."
3855 (defun kill-region (beg end
&optional region
)
3856 "Kill (\"cut\") text between point and mark.
3857 This deletes the text from the buffer and saves it in the kill ring.
3858 The command \\[yank] can retrieve it from there.
3859 \(If you want to save the region without killing it, use \\[kill-ring-save].)
3861 If you want to append the killed region to the last killed text,
3862 use \\[append-next-kill] before \\[kill-region].
3864 If the buffer is read-only, Emacs will beep and refrain from deleting
3865 the text, but put the text in the kill ring anyway. This means that
3866 you can use the killing commands to copy text from a read-only buffer.
3868 Lisp programs should use this function for killing text.
3869 (To delete text, use `delete-region'.)
3870 Supply two arguments, character positions indicating the stretch of text
3872 Any command that calls this function is a \"kill command\".
3873 If the previous command was also a kill command,
3874 the text killed this time appends to the text killed last time
3875 to make one entry in the kill ring.
3877 The optional argument REGION if non-nil, indicates that we're not just killing
3878 some text between BEG and END, but we're killing the region."
3879 ;; Pass mark first, then point, because the order matters when
3880 ;; calling `kill-append'.
3881 (interactive (list (mark) (point) 'region
))
3882 (unless (and beg end
)
3883 (error "The mark is not set now, so there is no region"))
3885 (let ((string (if region
3886 (funcall region-extract-function
'delete
)
3887 (filter-buffer-substring beg end
'delete
))))
3888 (when string
;STRING is nil if BEG = END
3889 ;; Add that string to the kill ring, one way or another.
3890 (if (eq last-command
'kill-region
)
3891 (kill-append string
(< end beg
))
3893 (when (or string
(eq last-command
'kill-region
))
3894 (setq this-command
'kill-region
))
3895 (setq deactivate-mark t
)
3897 ((buffer-read-only text-read-only
)
3898 ;; The code above failed because the buffer, or some of the characters
3899 ;; in the region, are read-only.
3900 ;; We should beep, in case the user just isn't aware of this.
3901 ;; However, there's no harm in putting
3902 ;; the region's text in the kill ring, anyway.
3903 (copy-region-as-kill beg end region
)
3904 ;; Set this-command now, so it will be set even if we get an error.
3905 (setq this-command
'kill-region
)
3906 ;; This should barf, if appropriate, and give us the correct error.
3907 (if kill-read-only-ok
3908 (progn (message "Read only text copied to kill ring") nil
)
3909 ;; Signal an error if the buffer is read-only.
3910 (barf-if-buffer-read-only)
3911 ;; If the buffer isn't read-only, the text is.
3912 (signal 'text-read-only
(list (current-buffer)))))))
3914 ;; copy-region-as-kill no longer sets this-command, because it's confusing
3915 ;; to get two copies of the text when the user accidentally types M-w and
3916 ;; then corrects it with the intended C-w.
3917 (defun copy-region-as-kill (beg end
&optional region
)
3918 "Save the region as if killed, but don't kill it.
3919 In Transient Mark mode, deactivate the mark.
3920 If `interprogram-cut-function' is non-nil, also save the text for a window
3921 system cut and paste.
3923 The optional argument REGION if non-nil, indicates that we're not just copying
3924 some text between BEG and END, but we're copying the region.
3926 This command's old key binding has been given to `kill-ring-save'."
3927 ;; Pass mark first, then point, because the order matters when
3928 ;; calling `kill-append'.
3929 (interactive (list (mark) (point)
3930 (prefix-numeric-value current-prefix-arg
)))
3931 (let ((str (if region
3932 (funcall region-extract-function nil
)
3933 (filter-buffer-substring beg end
))))
3934 (if (eq last-command
'kill-region
)
3935 (kill-append str
(< end beg
))
3937 (setq deactivate-mark t
)
3940 (defun kill-ring-save (beg end
&optional region
)
3941 "Save the region as if killed, but don't kill it.
3942 In Transient Mark mode, deactivate the mark.
3943 If `interprogram-cut-function' is non-nil, also save the text for a window
3944 system cut and paste.
3946 If you want to append the killed line to the last killed text,
3947 use \\[append-next-kill] before \\[kill-ring-save].
3949 The optional argument REGION if non-nil, indicates that we're not just copying
3950 some text between BEG and END, but we're copying the region.
3952 This command is similar to `copy-region-as-kill', except that it gives
3953 visual feedback indicating the extent of the region being copied."
3954 ;; Pass mark first, then point, because the order matters when
3955 ;; calling `kill-append'.
3956 (interactive (list (mark) (point)
3957 (prefix-numeric-value current-prefix-arg
)))
3958 (copy-region-as-kill beg end region
)
3959 ;; This use of called-interactively-p is correct because the code it
3960 ;; controls just gives the user visual feedback.
3961 (if (called-interactively-p 'interactive
)
3962 (indicate-copied-region)))
3964 (defun indicate-copied-region (&optional message-len
)
3965 "Indicate that the region text has been copied interactively.
3966 If the mark is visible in the selected window, blink the cursor
3967 between point and mark if there is currently no active region
3970 If the mark lies outside the selected window, display an
3971 informative message containing a sample of the copied text. The
3972 optional argument MESSAGE-LEN, if non-nil, specifies the length
3973 of this sample text; it defaults to 40."
3974 (let ((mark (mark t
))
3976 ;; Inhibit quitting so we can make a quit here
3977 ;; look like a C-g typed as a command.
3979 (if (pos-visible-in-window-p mark
(selected-window))
3980 ;; Swap point-and-mark quickly so as to show the region that
3981 ;; was selected. Don't do it if the region is highlighted.
3982 (unless (and (region-active-p)
3983 (face-background 'region
))
3984 ;; Swap point and mark.
3985 (set-marker (mark-marker) (point) (current-buffer))
3987 (sit-for blink-matching-delay
)
3989 (set-marker (mark-marker) mark
(current-buffer))
3991 ;; If user quit, deactivate the mark
3992 ;; as C-g would as a command.
3993 (and quit-flag mark-active
3995 (let ((len (min (abs (- mark point
))
3996 (or message-len
40))))
3998 ;; Don't say "killed"; that is misleading.
3999 (message "Saved text until \"%s\""
4000 (buffer-substring-no-properties (- mark len
) mark
))
4001 (message "Saved text from \"%s\""
4002 (buffer-substring-no-properties mark
(+ mark len
))))))))
4004 (defun append-next-kill (&optional interactive
)
4005 "Cause following command, if it kills, to add to previous kill.
4006 If the next command kills forward from point, the kill is
4007 appended to the previous killed text. If the command kills
4008 backward, the kill is prepended. Kill commands that act on the
4009 region, such as `kill-region', are regarded as killing forward if
4010 point is after mark, and killing backward if point is before
4013 If the next command is not a kill command, `append-next-kill' has
4016 The argument is used for internal purposes; do not supply one."
4018 ;; We don't use (interactive-p), since that breaks kbd macros.
4021 (setq this-command
'kill-region
)
4022 (message "If the next command is a kill, it will append"))
4023 (setq last-command
'kill-region
)))
4027 (defcustom yank-handled-properties
4028 '((font-lock-face . yank-handle-font-lock-face-property
)
4029 (category . yank-handle-category-property
))
4030 "List of special text property handling conditions for yanking.
4031 Each element should have the form (PROP . FUN), where PROP is a
4032 property symbol and FUN is a function. When the `yank' command
4033 inserts text into the buffer, it scans the inserted text for
4034 stretches of text that have `eq' values of the text property
4035 PROP; for each such stretch of text, FUN is called with three
4036 arguments: the property's value in that text, and the start and
4037 end positions of the text.
4039 This is done prior to removing the properties specified by
4040 `yank-excluded-properties'."
4042 :type
'(repeat (cons (symbol :tag
"property symbol")
4046 ;; This is actually used in subr.el but defcustom does not work there.
4047 (defcustom yank-excluded-properties
4048 '(category field follow-link fontified font-lock-face help-echo
4049 intangible invisible keymap local-map mouse-face read-only
4051 "Text properties to discard when yanking.
4052 The value should be a list of text properties to discard or t,
4053 which means to discard all text properties.
4055 See also `yank-handled-properties'."
4056 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
4060 (defvar yank-window-start nil
)
4061 (defvar yank-undo-function nil
4062 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4063 Function is called with two parameters, START and END corresponding to
4064 the value of the mark and point; it is guaranteed that START <= END.
4065 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4067 (defun yank-pop (&optional arg
)
4068 "Replace just-yanked stretch of killed text with a different stretch.
4069 This command is allowed only immediately after a `yank' or a `yank-pop'.
4070 At such a time, the region contains a stretch of reinserted
4071 previously-killed text. `yank-pop' deletes that text and inserts in its
4072 place a different stretch of killed text.
4074 With no argument, the previous kill is inserted.
4075 With argument N, insert the Nth previous kill.
4076 If N is negative, this is a more recent kill.
4078 The sequence of kills wraps around, so that after the oldest one
4079 comes the newest one.
4081 When this command inserts killed text into the buffer, it honors
4082 `yank-excluded-properties' and `yank-handler' as described in the
4083 doc string for `insert-for-yank-1', which see."
4085 (if (not (eq last-command
'yank
))
4086 (error "Previous command was not a yank"))
4087 (setq this-command
'yank
)
4088 (unless arg
(setq arg
1))
4089 (let ((inhibit-read-only t
)
4090 (before (< (point) (mark t
))))
4092 (funcall (or yank-undo-function
'delete-region
) (point) (mark t
))
4093 (funcall (or yank-undo-function
'delete-region
) (mark t
) (point)))
4094 (setq yank-undo-function nil
)
4095 (set-marker (mark-marker) (point) (current-buffer))
4096 (insert-for-yank (current-kill arg
))
4097 ;; Set the window start back where it was in the yank command,
4099 (set-window-start (selected-window) yank-window-start t
)
4101 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4102 ;; It is cleaner to avoid activation, even though the command
4103 ;; loop would deactivate the mark because we inserted text.
4104 (goto-char (prog1 (mark t
)
4105 (set-marker (mark-marker) (point) (current-buffer))))))
4108 (defun yank (&optional arg
)
4109 "Reinsert (\"paste\") the last stretch of killed text.
4110 More precisely, reinsert the most recent kill, which is the
4111 stretch of killed text most recently killed OR yanked. Put point
4112 at the end, and set mark at the beginning without activating it.
4113 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4114 With argument N, reinsert the Nth most recent kill.
4116 When this command inserts text into the buffer, it honors the
4117 `yank-handled-properties' and `yank-excluded-properties'
4118 variables, and the `yank-handler' text property. See
4119 `insert-for-yank-1' for details.
4121 See also the command `yank-pop' (\\[yank-pop])."
4123 (setq yank-window-start
(window-start))
4124 ;; If we don't get all the way thru, make last-command indicate that
4125 ;; for the following command.
4126 (setq this-command t
)
4128 (insert-for-yank (current-kill (cond
4133 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4134 ;; It is cleaner to avoid activation, even though the command
4135 ;; loop would deactivate the mark because we inserted text.
4136 (goto-char (prog1 (mark t
)
4137 (set-marker (mark-marker) (point) (current-buffer)))))
4138 ;; If we do get all the way thru, make this-command indicate that.
4139 (if (eq this-command t
)
4140 (setq this-command
'yank
))
4143 (defun rotate-yank-pointer (arg)
4144 "Rotate the yanking point in the kill ring.
4145 With ARG, rotate that many kills forward (or backward, if negative)."
4149 ;; Some kill commands.
4151 ;; Internal subroutine of delete-char
4152 (defun kill-forward-chars (arg)
4153 (if (listp arg
) (setq arg
(car arg
)))
4154 (if (eq arg
'-
) (setq arg -
1))
4155 (kill-region (point) (+ (point) arg
)))
4157 ;; Internal subroutine of backward-delete-char
4158 (defun kill-backward-chars (arg)
4159 (if (listp arg
) (setq arg
(car arg
)))
4160 (if (eq arg
'-
) (setq arg -
1))
4161 (kill-region (point) (- (point) arg
)))
4163 (defcustom backward-delete-char-untabify-method
'untabify
4164 "The method for untabifying when deleting backward.
4165 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4166 `hungry' -- delete all whitespace, both tabs and spaces;
4167 `all' -- delete all whitespace, including tabs, spaces and newlines;
4168 nil -- just delete one character."
4169 :type
'(choice (const untabify
) (const hungry
) (const all
) (const nil
))
4173 (defun backward-delete-char-untabify (arg &optional killp
)
4174 "Delete characters backward, changing tabs into spaces.
4175 The exact behavior depends on `backward-delete-char-untabify-method'.
4176 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4177 Interactively, ARG is the prefix arg (default 1)
4178 and KILLP is t if a prefix arg was specified."
4179 (interactive "*p\nP")
4180 (when (eq backward-delete-char-untabify-method
'untabify
)
4183 (while (and (> count
0) (not (bobp)))
4184 (if (= (preceding-char) ?
\t)
4185 (let ((col (current-column)))
4187 (setq col
(- col
(current-column)))
4188 (insert-char ?\s col
)
4191 (setq count
(1- count
))))))
4192 (let* ((skip (cond ((eq backward-delete-char-untabify-method
'hungry
) " \t")
4193 ((eq backward-delete-char-untabify-method
'all
)
4196 (let* ((oldpt (point))
4197 (wh (- oldpt
(save-excursion
4198 (skip-chars-backward skip
)
4199 (constrain-to-field nil oldpt
)))))
4200 (+ arg
(if (zerop wh
) 0 (1- wh
))))
4202 ;; Avoid warning about delete-backward-char
4203 (with-no-warnings (delete-backward-char n killp
))))
4205 (defun zap-to-char (arg char
)
4206 "Kill up to and including ARGth occurrence of CHAR.
4207 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4208 Goes backward if ARG is negative; error if CHAR not found."
4209 (interactive (list (prefix-numeric-value current-prefix-arg
)
4210 (read-char "Zap to char: " t
)))
4211 ;; Avoid "obsolete" warnings for translation-table-for-input.
4213 (if (char-table-p translation-table-for-input
)
4214 (setq char
(or (aref translation-table-for-input char
) char
))))
4215 (kill-region (point) (progn
4216 (search-forward (char-to-string char
) nil nil arg
)
4219 ;; kill-line and its subroutines.
4221 (defcustom kill-whole-line nil
4222 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4226 (defun kill-line (&optional arg
)
4227 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4228 With prefix argument ARG, kill that many lines from point.
4229 Negative arguments kill lines backward.
4230 With zero argument, kills the text before point on the current line.
4232 When calling from a program, nil means \"no arg\",
4233 a number counts as a prefix arg.
4235 To kill a whole line, when point is not at the beginning, type \
4236 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4238 If `show-trailing-whitespace' is non-nil, this command will just
4239 kill the rest of the current line, even if there are only
4242 If option `kill-whole-line' is non-nil, then this command kills the whole line
4243 including its terminating newline, when used at the beginning of a line
4244 with no argument. As a consequence, you can always kill a whole line
4245 by typing \\[move-beginning-of-line] \\[kill-line].
4247 If you want to append the killed line to the last killed text,
4248 use \\[append-next-kill] before \\[kill-line].
4250 If the buffer is read-only, Emacs will beep and refrain from deleting
4251 the line, but put the line in the kill ring anyway. This means that
4252 you can use this command to copy text from a read-only buffer.
4253 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4256 (kill-region (point)
4257 ;; It is better to move point to the other end of the kill
4258 ;; before killing. That way, in a read-only buffer, point
4259 ;; moves across the text that is copied to the kill ring.
4260 ;; The choice has no effect on undo now that undo records
4261 ;; the value of point from before the command was run.
4264 (forward-visible-line (prefix-numeric-value arg
))
4266 (signal 'end-of-buffer nil
))
4269 (end-of-visible-line) (point))))
4270 (if (or (save-excursion
4271 ;; If trailing whitespace is visible,
4272 ;; don't treat it as nothing.
4273 (unless show-trailing-whitespace
4274 (skip-chars-forward " \t" end
))
4276 (and kill-whole-line
(bolp)))
4277 (forward-visible-line 1)
4281 (defun kill-whole-line (&optional arg
)
4283 With prefix ARG, kill that many lines starting from the current line.
4284 If ARG is negative, kill backward. Also kill the preceding newline.
4285 \(This is meant to make \\[repeat] work well with negative arguments.)
4286 If ARG is zero, kill current line but exclude the trailing newline."
4288 (or arg
(setq arg
1))
4289 (if (and (> arg
0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4290 (signal 'end-of-buffer nil
))
4291 (if (and (< arg
0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4292 (signal 'beginning-of-buffer nil
))
4293 (unless (eq last-command
'kill-region
)
4295 (setq last-command
'kill-region
))
4297 ;; We need to kill in two steps, because the previous command
4298 ;; could have been a kill command, in which case the text
4299 ;; before point needs to be prepended to the current kill
4300 ;; ring entry and the text after point appended. Also, we
4301 ;; need to use save-excursion to avoid copying the same text
4302 ;; twice to the kill ring in read-only buffers.
4304 (kill-region (point) (progn (forward-visible-line 0) (point))))
4305 (kill-region (point) (progn (end-of-visible-line) (point))))
4308 (kill-region (point) (progn (end-of-visible-line) (point))))
4309 (kill-region (point)
4310 (progn (forward-visible-line (1+ arg
))
4311 (unless (bobp) (backward-char))
4315 (kill-region (point) (progn (forward-visible-line 0) (point))))
4316 (kill-region (point)
4317 (progn (forward-visible-line arg
) (point))))))
4319 (defun forward-visible-line (arg)
4320 "Move forward by ARG lines, ignoring currently invisible newlines only.
4321 If ARG is negative, move backward -ARG lines.
4322 If ARG is zero, move to the beginning of the current line."
4327 (or (zerop (forward-line 1))
4328 (signal 'end-of-buffer nil
))
4329 ;; If the newline we just skipped is invisible,
4332 (get-char-property (1- (point)) 'invisible
)))
4333 (if (if (eq buffer-invisibility-spec t
)
4335 (or (memq prop buffer-invisibility-spec
)
4336 (assq prop buffer-invisibility-spec
)))
4337 (setq arg
(1+ arg
))))
4338 (setq arg
(1- arg
)))
4339 ;; If invisible text follows, and it is a number of complete lines,
4341 (let ((opoint (point)))
4342 (while (and (not (eobp))
4344 (get-char-property (point) 'invisible
)))
4345 (if (eq buffer-invisibility-spec t
)
4347 (or (memq prop buffer-invisibility-spec
)
4348 (assq prop buffer-invisibility-spec
)))))
4350 (if (get-text-property (point) 'invisible
)
4351 (or (next-single-property-change (point) 'invisible
)
4353 (next-overlay-change (point)))))
4355 (goto-char opoint
))))
4357 (while (or first
(<= arg
0))
4360 (or (zerop (forward-line -
1))
4361 (signal 'beginning-of-buffer nil
)))
4362 ;; If the newline we just moved to is invisible,
4366 (get-char-property (1- (point)) 'invisible
)))
4367 (unless (if (eq buffer-invisibility-spec t
)
4369 (or (memq prop buffer-invisibility-spec
)
4370 (assq prop buffer-invisibility-spec
)))
4371 (setq arg
(1+ arg
)))))
4373 ;; If invisible text follows, and it is a number of complete lines,
4375 (let ((opoint (point)))
4376 (while (and (not (bobp))
4378 (get-char-property (1- (point)) 'invisible
)))
4379 (if (eq buffer-invisibility-spec t
)
4381 (or (memq prop buffer-invisibility-spec
)
4382 (assq prop buffer-invisibility-spec
)))))
4384 (if (get-text-property (1- (point)) 'invisible
)
4385 (or (previous-single-property-change (point) 'invisible
)
4387 (previous-overlay-change (point)))))
4389 (goto-char opoint
)))))
4390 ((beginning-of-buffer end-of-buffer
)
4393 (defun end-of-visible-line ()
4394 "Move to end of current visible line."
4396 ;; If the following character is currently invisible,
4397 ;; skip all characters with that same `invisible' property value,
4398 ;; then find the next newline.
4399 (while (and (not (eobp))
4401 (skip-chars-forward "^\n")
4403 (get-char-property (point) 'invisible
)))
4404 (if (eq buffer-invisibility-spec t
)
4406 (or (memq prop buffer-invisibility-spec
)
4407 (assq prop buffer-invisibility-spec
))))))
4408 (skip-chars-forward "^\n")
4409 (if (get-text-property (point) 'invisible
)
4410 (goto-char (or (next-single-property-change (point) 'invisible
)
4412 (goto-char (next-overlay-change (point))))
4415 (defun insert-buffer (buffer)
4416 "Insert after point the contents of BUFFER.
4417 Puts mark after the inserted text.
4418 BUFFER may be a buffer or a buffer name."
4419 (declare (interactive-only insert-buffer-substring
))
4423 (barf-if-buffer-read-only)
4424 (read-buffer "Insert buffer: "
4425 (if (eq (selected-window) (next-window))
4426 (other-buffer (current-buffer))
4427 (window-buffer (next-window)))
4431 (insert-buffer-substring (get-buffer buffer
))
4435 (defun append-to-buffer (buffer start end
)
4436 "Append to specified buffer the text of the region.
4437 It is inserted into that buffer before its point.
4439 When calling from a program, give three arguments:
4440 BUFFER (or buffer name), START and END.
4441 START and END specify the portion of the current buffer to be copied."
4443 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t
))
4444 (region-beginning) (region-end)))
4445 (let* ((oldbuf (current-buffer))
4446 (append-to (get-buffer-create buffer
))
4447 (windows (get-buffer-window-list append-to t t
))
4450 (with-current-buffer append-to
4451 (setq point
(point))
4452 (barf-if-buffer-read-only)
4453 (insert-buffer-substring oldbuf start end
)
4454 (dolist (window windows
)
4455 (when (= (window-point window
) point
)
4456 (set-window-point window
(point))))))))
4458 (defun prepend-to-buffer (buffer start end
)
4459 "Prepend to specified buffer the text of the region.
4460 It is inserted into that buffer after its point.
4462 When calling from a program, give three arguments:
4463 BUFFER (or buffer name), START and END.
4464 START and END specify the portion of the current buffer to be copied."
4465 (interactive "BPrepend to buffer: \nr")
4466 (let ((oldbuf (current-buffer)))
4467 (with-current-buffer (get-buffer-create buffer
)
4468 (barf-if-buffer-read-only)
4470 (insert-buffer-substring oldbuf start end
)))))
4472 (defun copy-to-buffer (buffer start end
)
4473 "Copy to specified buffer the text of the region.
4474 It is inserted into that buffer, replacing existing text there.
4476 When calling from a program, give three arguments:
4477 BUFFER (or buffer name), START and END.
4478 START and END specify the portion of the current buffer to be copied."
4479 (interactive "BCopy to buffer: \nr")
4480 (let ((oldbuf (current-buffer)))
4481 (with-current-buffer (get-buffer-create buffer
)
4482 (barf-if-buffer-read-only)
4485 (insert-buffer-substring oldbuf start end
)))))
4487 (define-error 'mark-inactive
(purecopy "The mark is not active now"))
4489 (defvar activate-mark-hook nil
4490 "Hook run when the mark becomes active.
4491 It is also run at the end of a command, if the mark is active and
4492 it is possible that the region may have changed.")
4494 (defvar deactivate-mark-hook nil
4495 "Hook run when the mark becomes inactive.")
4497 (defun mark (&optional force
)
4498 "Return this buffer's mark value as integer, or nil if never set.
4500 In Transient Mark mode, this function signals an error if
4501 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
4502 or the argument FORCE is non-nil, it disregards whether the mark
4503 is active, and returns an integer or nil in the usual way.
4505 If you are using this in an editing command, you are most likely making
4506 a mistake; see the documentation of `set-mark'."
4507 (if (or force
(not transient-mark-mode
) mark-active mark-even-if-inactive
)
4508 (marker-position (mark-marker))
4509 (signal 'mark-inactive nil
)))
4511 ;; Behind display-selections-p.
4513 (defun deactivate-mark (&optional force
)
4514 "Deactivate the mark.
4515 If Transient Mark mode is disabled, this function normally does
4516 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
4518 Deactivating the mark sets `mark-active' to nil, updates the
4519 primary selection according to `select-active-regions', and runs
4520 `deactivate-mark-hook'.
4522 If Transient Mark mode was temporarily enabled, reset the value
4523 of the variable `transient-mark-mode'; if this causes Transient
4524 Mark mode to be disabled, don't change `mark-active' to nil or
4525 run `deactivate-mark-hook'."
4526 (when (or transient-mark-mode force
)
4527 (when (and (if (eq select-active-regions
'only
)
4528 (eq (car-safe transient-mark-mode
) 'only
)
4529 select-active-regions
)
4531 (display-selections-p))
4532 ;; The var `saved-region-selection', if non-nil, is the text in
4533 ;; the region prior to the last command modifying the buffer.
4534 ;; Set the selection to that, or to the current region.
4535 (cond (saved-region-selection
4536 (gui-set-selection 'PRIMARY saved-region-selection
)
4537 (setq saved-region-selection nil
))
4538 ;; If another program has acquired the selection, region
4539 ;; deactivation should not clobber it (Bug#11772).
4540 ((and (/= (region-beginning) (region-end))
4541 (or (gui-call gui-selection-owner-p
'PRIMARY
)
4542 (null (gui-call gui-selection-exists-p
'PRIMARY
))))
4543 (gui-set-selection 'PRIMARY
4544 (funcall region-extract-function nil
)))))
4545 (when mark-active
(force-mode-line-update)) ;Refresh toolbar (bug#16382).
4547 ((eq (car-safe transient-mark-mode
) 'only
)
4548 (setq transient-mark-mode
(cdr transient-mark-mode
))
4549 (if (eq transient-mark-mode
(default-value 'transient-mark-mode
))
4550 (kill-local-variable 'transient-mark-mode
)))
4551 ((eq transient-mark-mode
'lambda
)
4552 (kill-local-variable 'transient-mark-mode
)))
4553 (setq mark-active nil
)
4554 (run-hooks 'deactivate-mark-hook
)
4555 (redisplay--update-region-highlight (selected-window))))
4557 (defun activate-mark (&optional no-tmm
)
4559 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
4561 (unless (region-active-p)
4562 (force-mode-line-update) ;Refresh toolbar (bug#16382).
4563 (setq mark-active t
)
4564 (unless (or transient-mark-mode no-tmm
)
4565 (setq-local transient-mark-mode
'lambda
))
4566 (run-hooks 'activate-mark-hook
))))
4568 (defun set-mark (pos)
4569 "Set this buffer's mark to POS. Don't use this function!
4570 That is to say, don't use this function unless you want
4571 the user to see that the mark has moved, and you want the previous
4572 mark position to be lost.
4574 Normally, when a new mark is set, the old one should go on the stack.
4575 This is why most applications should use `push-mark', not `set-mark'.
4577 Novice Emacs Lisp programmers often try to use the mark for the wrong
4578 purposes. The mark saves a location for the user's convenience.
4579 Most editing commands should not alter the mark.
4580 To remember a location for internal use in the Lisp program,
4581 store it in a Lisp variable. Example:
4583 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
4586 (set-marker (mark-marker) pos
(current-buffer))
4587 (activate-mark 'no-tmm
))
4588 ;; Normally we never clear mark-active except in Transient Mark mode.
4589 ;; But when we actually clear out the mark value too, we must
4590 ;; clear mark-active in any mode.
4592 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
4593 ;; it should never be nil if the mark is nil.
4594 (setq mark-active nil
)
4595 (set-marker (mark-marker) nil
)))
4597 (defcustom use-empty-active-region nil
4598 "Whether \"region-aware\" commands should act on empty regions.
4599 If nil, region-aware commands treat empty regions as inactive.
4600 If non-nil, region-aware commands treat the region as active as
4601 long as the mark is active, even if the region is empty.
4603 Region-aware commands are those that act on the region if it is
4604 active and Transient Mark mode is enabled, and on the text near
4608 :group
'editing-basics
)
4610 (defun use-region-p ()
4611 "Return t if the region is active and it is appropriate to act on it.
4612 This is used by commands that act specially on the region under
4613 Transient Mark mode.
4615 The return value is t if Transient Mark mode is enabled and the
4616 mark is active; furthermore, if `use-empty-active-region' is nil,
4617 the region must not be empty. Otherwise, the return value is nil.
4619 For some commands, it may be appropriate to ignore the value of
4620 `use-empty-active-region'; in that case, use `region-active-p'."
4621 (and (region-active-p)
4622 (or use-empty-active-region
(> (region-end) (region-beginning)))))
4624 (defun region-active-p ()
4625 "Return t if Transient Mark mode is enabled and the mark is active.
4627 Some commands act specially on the region when Transient Mark
4628 mode is enabled. Usually, such commands should use
4629 `use-region-p' instead of this function, because `use-region-p'
4630 also checks the value of `use-empty-active-region'."
4631 (and transient-mark-mode mark-active
4632 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
4633 ;; without the mark being set (e.g. bug#17324). We really should fix
4634 ;; that problem, but in the mean time, let's make sure we don't say the
4635 ;; region is active when there's no mark.
4639 (defvar redisplay-unhighlight-region-function
4640 (lambda (rol) (when (overlayp rol
) (delete-overlay rol
))))
4642 (defvar redisplay-highlight-region-function
4643 (lambda (start end window rol
)
4644 (if (not (overlayp rol
))
4645 (let ((nrol (make-overlay start end
)))
4646 (funcall redisplay-unhighlight-region-function rol
)
4647 (overlay-put nrol
'window window
)
4648 (overlay-put nrol
'face
'region
)
4649 ;; Normal priority so that a large region doesn't hide all the
4650 ;; overlays within it, but high secondary priority so that if it
4651 ;; ends/starts in the middle of a small overlay, that small overlay
4652 ;; won't hide the region's boundaries.
4653 (overlay-put nrol
'priority
'(nil .
100))
4655 (unless (and (eq (overlay-buffer rol
) (current-buffer))
4656 (eq (overlay-start rol
) start
)
4657 (eq (overlay-end rol
) end
))
4658 (move-overlay rol start end
(current-buffer)))
4661 (defun redisplay--update-region-highlight (window)
4662 (with-current-buffer (window-buffer window
)
4663 (let ((rol (window-parameter window
'internal-region-overlay
)))
4664 (if (not (region-active-p))
4665 (funcall redisplay-unhighlight-region-function rol
)
4666 (let* ((pt (window-point window
))
4668 (start (min pt mark
))
4671 (funcall redisplay-highlight-region-function
4672 start end window rol
)))
4673 (unless (equal new rol
)
4674 (set-window-parameter window
'internal-region-overlay
4677 (defun redisplay--update-region-highlights (windows)
4678 (with-demoted-errors "redisplay--update-region-highlights: %S"
4680 (redisplay--update-region-highlight (selected-window))
4681 (unless (listp windows
) (setq windows
(window-list-1 nil nil t
)))
4682 (if highlight-nonselected-windows
4683 (mapc #'redisplay--update-region-highlight windows
)
4684 (let ((msw (and (window-minibuffer-p) (minibuffer-selected-window))))
4686 (if (or (eq w
(selected-window)) (eq w msw
))
4687 (redisplay--update-region-highlight w
)
4688 (funcall redisplay-unhighlight-region-function
4689 (window-parameter w
'internal-region-overlay
)))))))))
4691 (add-function :before pre-redisplay-function
4692 #'redisplay--update-region-highlights
)
4695 (defvar-local mark-ring nil
4696 "The list of former marks of the current buffer, most recent first.")
4697 (put 'mark-ring
'permanent-local t
)
4699 (defcustom mark-ring-max
16
4700 "Maximum size of mark ring. Start discarding off end if gets this big."
4702 :group
'editing-basics
)
4704 (defvar global-mark-ring nil
4705 "The list of saved global marks, most recent first.")
4707 (defcustom global-mark-ring-max
16
4708 "Maximum size of global mark ring. \
4709 Start discarding off end if gets this big."
4711 :group
'editing-basics
)
4713 (defun pop-to-mark-command ()
4714 "Jump to mark, and pop a new position for mark off the ring.
4715 \(Does not affect global mark ring)."
4718 (error "No mark set in this buffer")
4719 (if (= (point) (mark t
))
4720 (message "Mark popped"))
4721 (goto-char (mark t
))
4724 (defun push-mark-command (arg &optional nomsg
)
4725 "Set mark at where point is.
4726 If no prefix ARG and mark is already set there, just activate it.
4727 Display `Mark set' unless the optional second arg NOMSG is non-nil."
4729 (let ((mark (mark t
)))
4730 (if (or arg
(null mark
) (/= mark
(point)))
4731 (push-mark nil nomsg t
)
4732 (activate-mark 'no-tmm
)
4734 (message "Mark activated")))))
4736 (defcustom set-mark-command-repeat-pop nil
4737 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
4738 That means that C-u \\[set-mark-command] \\[set-mark-command]
4739 will pop the mark twice, and
4740 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
4741 will pop the mark three times.
4743 A value of nil means \\[set-mark-command]'s behavior does not change
4744 after C-u \\[set-mark-command]."
4746 :group
'editing-basics
)
4748 (defun set-mark-command (arg)
4749 "Set the mark where point is, or jump to the mark.
4750 Setting the mark also alters the region, which is the text
4751 between point and mark; this is the closest equivalent in
4752 Emacs to what some editors call the \"selection\".
4754 With no prefix argument, set the mark at point, and push the
4755 old mark position on local mark ring. Also push the old mark on
4756 global mark ring, if the previous mark was set in another buffer.
4758 When Transient Mark Mode is off, immediately repeating this
4759 command activates `transient-mark-mode' temporarily.
4761 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
4762 jump to the mark, and set the mark from
4763 position popped off the local mark ring (this does not affect the global
4764 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
4765 mark ring (see `pop-global-mark').
4767 If `set-mark-command-repeat-pop' is non-nil, repeating
4768 the \\[set-mark-command] command with no prefix argument pops the next position
4769 off the local (or global) mark ring and jumps there.
4771 With \\[universal-argument] \\[universal-argument] as prefix
4772 argument, unconditionally set mark where point is, even if
4773 `set-mark-command-repeat-pop' is non-nil.
4775 Novice Emacs Lisp programmers often try to use the mark for the wrong
4776 purposes. See the documentation of `set-mark' for more information."
4778 (cond ((eq transient-mark-mode
'lambda
)
4779 (kill-local-variable 'transient-mark-mode
))
4780 ((eq (car-safe transient-mark-mode
) 'only
)
4783 ((and (consp arg
) (> (prefix-numeric-value arg
) 4))
4784 (push-mark-command nil
))
4785 ((not (eq this-command
'set-mark-command
))
4787 (pop-to-mark-command)
4788 (push-mark-command t
)))
4789 ((and set-mark-command-repeat-pop
4790 (eq last-command
'pop-global-mark
)
4792 (setq this-command
'pop-global-mark
)
4794 ((or (and set-mark-command-repeat-pop
4795 (eq last-command
'pop-to-mark-command
))
4797 (setq this-command
'pop-to-mark-command
)
4798 (pop-to-mark-command))
4799 ((eq last-command
'set-mark-command
)
4800 (if (region-active-p)
4803 (message "Mark deactivated"))
4805 (message "Mark activated")))
4807 (push-mark-command nil
))))
4809 (defun push-mark (&optional location nomsg activate
)
4810 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
4811 If the last global mark pushed was not in the current buffer,
4812 also push LOCATION on the global mark ring.
4813 Display `Mark set' unless the optional second arg NOMSG is non-nil.
4815 Novice Emacs Lisp programmers often try to use the mark for the wrong
4816 purposes. See the documentation of `set-mark' for more information.
4818 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
4819 (unless (null (mark t
))
4820 (setq mark-ring
(cons (copy-marker (mark-marker)) mark-ring
))
4821 (when (> (length mark-ring
) mark-ring-max
)
4822 (move-marker (car (nthcdr mark-ring-max mark-ring
)) nil
)
4823 (setcdr (nthcdr (1- mark-ring-max
) mark-ring
) nil
)))
4824 (set-marker (mark-marker) (or location
(point)) (current-buffer))
4825 ;; Now push the mark on the global mark ring.
4826 (if (and global-mark-ring
4827 (eq (marker-buffer (car global-mark-ring
)) (current-buffer)))
4828 ;; The last global mark pushed was in this same buffer.
4829 ;; Don't push another one.
4831 (setq global-mark-ring
(cons (copy-marker (mark-marker)) global-mark-ring
))
4832 (when (> (length global-mark-ring
) global-mark-ring-max
)
4833 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring
)) nil
)
4834 (setcdr (nthcdr (1- global-mark-ring-max
) global-mark-ring
) nil
)))
4835 (or nomsg executing-kbd-macro
(> (minibuffer-depth) 0)
4836 (message "Mark set"))
4837 (if (or activate
(not transient-mark-mode
))
4838 (set-mark (mark t
)))
4842 "Pop off mark ring into the buffer's actual mark.
4843 Does not set point. Does nothing if mark ring is empty."
4845 (setq mark-ring
(nconc mark-ring
(list (copy-marker (mark-marker)))))
4846 (set-marker (mark-marker) (+ 0 (car mark-ring
)) (current-buffer))
4847 (move-marker (car mark-ring
) nil
)
4848 (if (null (mark t
)) (ding))
4849 (setq mark-ring
(cdr mark-ring
)))
4852 (define-obsolete-function-alias
4853 'exchange-dot-and-mark
'exchange-point-and-mark
"23.3")
4854 (defun exchange-point-and-mark (&optional arg
)
4855 "Put the mark where point is now, and point where the mark is now.
4856 This command works even when the mark is not active,
4857 and it reactivates the mark.
4859 If Transient Mark mode is on, a prefix ARG deactivates the mark
4860 if it is active, and otherwise avoids reactivating it. If
4861 Transient Mark mode is off, a prefix ARG enables Transient Mark
4864 (let ((omark (mark t
))
4865 (temp-highlight (eq (car-safe transient-mark-mode
) 'only
)))
4867 (error "No mark set in this buffer"))
4870 (cond (temp-highlight
4871 (setq-local transient-mark-mode
(cons 'only transient-mark-mode
)))
4872 ((or (and arg
(region-active-p)) ; (xor arg (not (region-active-p)))
4873 (not (or arg
(region-active-p))))
4875 (t (activate-mark)))
4878 (defcustom shift-select-mode t
4879 "When non-nil, shifted motion keys activate the mark momentarily.
4881 While the mark is activated in this way, any shift-translated point
4882 motion key extends the region, and if Transient Mark mode was off, it
4883 is temporarily turned on. Furthermore, the mark will be deactivated
4884 by any subsequent point motion key that was not shift-translated, or
4885 by any action that normally deactivates the mark in Transient Mark mode.
4887 See `this-command-keys-shift-translated' for the meaning of
4890 :group
'editing-basics
)
4892 (defun handle-shift-selection ()
4893 "Activate/deactivate mark depending on invocation thru shift translation.
4894 This function is called by `call-interactively' when a command
4895 with a `^' character in its `interactive' spec is invoked, before
4896 running the command itself.
4898 If `shift-select-mode' is enabled and the command was invoked
4899 through shift translation, set the mark and activate the region
4900 temporarily, unless it was already set in this way. See
4901 `this-command-keys-shift-translated' for the meaning of shift
4904 Otherwise, if the region has been activated temporarily,
4905 deactivate it, and restore the variable `transient-mark-mode' to
4907 (cond ((and shift-select-mode this-command-keys-shift-translated
)
4908 (unless (and mark-active
4909 (eq (car-safe transient-mark-mode
) 'only
))
4910 (setq-local transient-mark-mode
4912 (unless (eq transient-mark-mode
'lambda
)
4913 transient-mark-mode
)))
4914 (push-mark nil nil t
)))
4915 ((eq (car-safe transient-mark-mode
) 'only
)
4916 (setq transient-mark-mode
(cdr transient-mark-mode
))
4917 (if (eq transient-mark-mode
(default-value 'transient-mark-mode
))
4918 (kill-local-variable 'transient-mark-mode
))
4919 (deactivate-mark))))
4921 (define-minor-mode transient-mark-mode
4922 "Toggle Transient Mark mode.
4923 With a prefix argument ARG, enable Transient Mark mode if ARG is
4924 positive, and disable it otherwise. If called from Lisp, enable
4925 Transient Mark mode if ARG is omitted or nil.
4927 Transient Mark mode is a global minor mode. When enabled, the
4928 region is highlighted whenever the mark is active. The mark is
4929 \"deactivated\" by changing the buffer, and after certain other
4930 operations that set the mark but whose main purpose is something
4931 else--for example, incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
4933 You can also deactivate the mark by typing \\[keyboard-quit] or
4934 \\[keyboard-escape-quit].
4936 Many commands change their behavior when Transient Mark mode is
4937 in effect and the mark is active, by acting on the region instead
4938 of their usual default part of the buffer's text. Examples of
4939 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
4940 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
4941 To see the documentation of commands which are sensitive to the
4942 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
4943 or \"mark.*active\" at the prompt."
4945 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
4946 :variable
(default-value 'transient-mark-mode
))
4948 (defvar widen-automatically t
4949 "Non-nil means it is ok for commands to call `widen' when they want to.
4950 Some commands will do this in order to go to positions outside
4951 the current accessible part of the buffer.
4953 If `widen-automatically' is nil, these commands will do something else
4954 as a fallback, and won't change the buffer bounds.")
4956 (defvar non-essential nil
4957 "Whether the currently executing code is performing an essential task.
4958 This variable should be non-nil only when running code which should not
4959 disturb the user. E.g. it can be used to prevent Tramp from prompting the
4960 user for a password when we are simply scanning a set of files in the
4961 background or displaying possible completions before the user even asked
4964 (defun pop-global-mark ()
4965 "Pop off global mark ring and jump to the top location."
4967 ;; Pop entries which refer to non-existent buffers.
4968 (while (and global-mark-ring
(not (marker-buffer (car global-mark-ring
))))
4969 (setq global-mark-ring
(cdr global-mark-ring
)))
4970 (or global-mark-ring
4971 (error "No global mark set"))
4972 (let* ((marker (car global-mark-ring
))
4973 (buffer (marker-buffer marker
))
4974 (position (marker-position marker
)))
4975 (setq global-mark-ring
(nconc (cdr global-mark-ring
)
4976 (list (car global-mark-ring
))))
4978 (or (and (>= position
(point-min))
4979 (<= position
(point-max)))
4980 (if widen-automatically
4982 (error "Global mark position is outside accessible part of buffer")))
4983 (goto-char position
)
4984 (switch-to-buffer buffer
)))
4986 (defcustom next-line-add-newlines nil
4987 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
4990 :group
'editing-basics
)
4992 (defun next-line (&optional arg try-vscroll
)
4993 "Move cursor vertically down ARG lines.
4994 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4995 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
4996 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
4997 function will not vscroll.
5001 If there is no character in the target line exactly under the current column,
5002 the cursor is positioned after the character in that line which spans this
5003 column, or at the end of the line if it is not long enough.
5004 If there is no line in the buffer after this one, behavior depends on the
5005 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5006 to create a line, and moves the cursor to that line. Otherwise it moves the
5007 cursor to the end of the buffer.
5009 If the variable `line-move-visual' is non-nil, this command moves
5010 by display lines. Otherwise, it moves by buffer lines, without
5011 taking variable-width characters or continued lines into account.
5013 The command \\[set-goal-column] can be used to create
5014 a semipermanent goal column for this command.
5015 Then instead of trying to move exactly vertically (or as close as possible),
5016 this command moves to the specified goal column (or as close as possible).
5017 The goal column is stored in the variable `goal-column', which is nil
5018 when there is no goal column. Note that setting `goal-column'
5019 overrides `line-move-visual' and causes this command to move by buffer
5020 lines rather than by display lines."
5021 (declare (interactive-only forward-line
))
5022 (interactive "^p\np")
5023 (or arg
(setq arg
1))
5024 (if (and next-line-add-newlines
(= arg
1))
5025 (if (save-excursion (end-of-line) (eobp))
5026 ;; When adding a newline, don't expand an abbrev.
5027 (let ((abbrev-mode nil
))
5029 (insert (if use-hard-newlines hard-newline
"\n")))
5030 (line-move arg nil nil try-vscroll
))
5031 (if (called-interactively-p 'interactive
)
5033 (line-move arg nil nil try-vscroll
)
5034 ((beginning-of-buffer end-of-buffer
)
5035 (signal (car err
) (cdr err
))))
5036 (line-move arg nil nil try-vscroll
)))
5039 (defun previous-line (&optional arg try-vscroll
)
5040 "Move cursor vertically up ARG lines.
5041 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5042 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5043 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5044 function will not vscroll.
5048 If there is no character in the target line exactly over the current column,
5049 the cursor is positioned after the character in that line which spans this
5050 column, or at the end of the line if it is not long enough.
5052 If the variable `line-move-visual' is non-nil, this command moves
5053 by display lines. Otherwise, it moves by buffer lines, without
5054 taking variable-width characters or continued lines into account.
5056 The command \\[set-goal-column] can be used to create
5057 a semipermanent goal column for this command.
5058 Then instead of trying to move exactly vertically (or as close as possible),
5059 this command moves to the specified goal column (or as close as possible).
5060 The goal column is stored in the variable `goal-column', which is nil
5061 when there is no goal column. Note that setting `goal-column'
5062 overrides `line-move-visual' and causes this command to move by buffer
5063 lines rather than by display lines."
5064 (declare (interactive-only
5065 "use `forward-line' with negative argument instead."))
5066 (interactive "^p\np")
5067 (or arg
(setq arg
1))
5068 (if (called-interactively-p 'interactive
)
5070 (line-move (- arg
) nil nil try-vscroll
)
5071 ((beginning-of-buffer end-of-buffer
)
5072 (signal (car err
) (cdr err
))))
5073 (line-move (- arg
) nil nil try-vscroll
))
5076 (defcustom track-eol nil
5077 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5078 This means moving to the end of each line moved onto.
5079 The beginning of a blank line does not count as the end of a line.
5080 This has no effect when the variable `line-move-visual' is non-nil."
5082 :group
'editing-basics
)
5084 (defcustom goal-column nil
5085 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5086 A non-nil setting overrides the variable `line-move-visual', which see."
5087 :type
'(choice integer
5088 (const :tag
"None" nil
))
5089 :group
'editing-basics
)
5090 (make-variable-buffer-local 'goal-column
)
5092 (defvar temporary-goal-column
0
5093 "Current goal column for vertical motion.
5094 It is the column where point was at the start of the current run
5095 of vertical motion commands.
5097 When moving by visual lines via the function `line-move-visual', it is a cons
5098 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5099 divided by the default column width, and HSCROLL is the number of
5100 columns by which window is scrolled from left margin.
5102 When the `track-eol' feature is doing its job, the value is
5103 `most-positive-fixnum'.")
5105 (defcustom line-move-ignore-invisible t
5106 "Non-nil means commands that move by lines ignore invisible newlines.
5107 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5108 as if newlines that are invisible didn't exist, and count
5109 only visible newlines. Thus, moving across across 2 newlines
5110 one of which is invisible will be counted as a one-line move.
5111 Also, a non-nil value causes invisible text to be ignored when
5112 counting columns for the purposes of keeping point in the same
5113 column by \\[next-line] and \\[previous-line].
5115 Outline mode sets this."
5117 :group
'editing-basics
)
5119 (defcustom line-move-visual t
5120 "When non-nil, `line-move' moves point by visual lines.
5121 This movement is based on where the cursor is displayed on the
5122 screen, instead of relying on buffer contents alone. It takes
5123 into account variable-width characters and line continuation.
5124 If nil, `line-move' moves point by logical lines.
5125 A non-nil setting of `goal-column' overrides the value of this variable
5126 and forces movement by logical lines.
5127 A window that is horizontally scrolled also forces movement by logical
5130 :group
'editing-basics
5133 ;; Only used if display-graphic-p.
5134 (declare-function font-info
"font.c" (name &optional frame
))
5136 (defun default-font-height ()
5137 "Return the height in pixels of the current buffer's default face font."
5138 (let ((default-font (face-font 'default
)))
5140 ((and (display-multi-font-p)
5141 ;; Avoid calling font-info if the frame's default font was
5142 ;; not changed since the frame was created. That's because
5143 ;; font-info is expensive for some fonts, see bug #14838.
5144 (not (string= (frame-parameter nil
'font
) default-font
)))
5145 (aref (font-info default-font
) 3))
5146 (t (frame-char-height)))))
5148 (defun default-line-height ()
5149 "Return the pixel height of current buffer's default-face text line.
5151 The value includes `line-spacing', if any, defined for the buffer
5153 (let ((dfh (default-font-height))
5154 (lsp (if (display-graphic-p)
5156 (default-value 'line-spacing
)
5157 (frame-parameter nil
'line-spacing
)
5161 (setq lsp
(truncate (* (frame-char-height) lsp
))))
5164 (defun window-screen-lines ()
5165 "Return the number of screen lines in the text area of the selected window.
5167 This is different from `window-text-height' in that this function counts
5168 lines in units of the height of the font used by the default face displayed
5169 in the window, not in units of the frame's default font, and also accounts
5170 for `line-spacing', if any, defined for the window's buffer or frame.
5172 The value is a floating-point number."
5173 (let ((edges (window-inside-pixel-edges))
5174 (dlh (default-line-height)))
5175 (/ (float (- (nth 3 edges
) (nth 1 edges
))) dlh
)))
5177 ;; Returns non-nil if partial move was done.
5178 (defun line-move-partial (arg noerror to-end
)
5180 ;; Move backward (up).
5181 ;; If already vscrolled, reduce vscroll
5182 (let ((vs (window-vscroll nil t
))
5183 (dlh (default-line-height)))
5185 (set-window-vscroll nil
(- vs dlh
) t
)))
5187 ;; Move forward (down).
5188 (let* ((lh (window-line-height -
1))
5193 (this-lh (window-line-height))
5194 (this-height (car this-lh
))
5195 (this-ypos (nth 2 this-lh
))
5196 (dlh (default-line-height))
5197 (wslines (window-screen-lines))
5198 (edges (window-inside-pixel-edges))
5199 (winh (- (nth 3 edges
) (nth 1 edges
) 1))
5201 (if (> (mod wslines
1.0) 0.0)
5202 (setq wslines
(round (+ wslines
0.5))))
5207 (<= this-ypos
(- dlh
)))
5209 (let ((wend (pos-visible-in-window-p t nil t
)))
5210 (setq rbot
(nth 3 wend
)
5212 vpos
(nth 5 wend
))))
5214 (let ((wstart (pos-visible-in-window-p nil nil t
)))
5215 (setq this-ypos
(nth 2 wstart
)
5216 this-height
(nth 4 wstart
))))
5219 (let ((ppos (posn-at-point))
5221 (setq col-row
(posn-actual-col-row ppos
))
5223 (- (cdr col-row
) (window-vscroll))
5224 (cdr (posn-col-row ppos
))))))
5225 ;; VPOS > 0 means the last line is only partially visible.
5226 ;; But if the part that is visible is at least as tall as the
5227 ;; default font, that means the line is actually fully
5228 ;; readable, and something like line-spacing is hidden. So in
5229 ;; that case we accept the last line in the window as still
5230 ;; visible, and consider the margin as starting one line
5232 (if (and vpos
(> vpos
0))
5234 (>= rowh
(default-font-height))
5236 (setq last-line
(min (- wslines scroll-margin
) vpos
))
5237 (setq last-line
(min (- wslines scroll-margin
1) (1- vpos
)))))
5239 ;; If last line of window is fully visible, and vscrolling
5240 ;; more would make this line invisible, move forward.
5241 ((and (or (< (setq vs
(window-vscroll nil t
)) dlh
)
5243 (<= this-height dlh
))
5244 (or (null rbot
) (= rbot
0)))
5246 ;; If cursor is not in the bottom scroll margin, and the
5247 ;; current line is is not too tall, move forward.
5248 ((and (or (null this-height
) (<= this-height winh
))
5253 ;; When already vscrolled, we vscroll some more if we can,
5254 ;; or clear vscroll and move forward at end of tall image.
5256 (when (or (and rbot
(> rbot
0))
5257 (and this-height
(> this-height dlh
)))
5258 (set-window-vscroll nil
(+ vs dlh
) t
)))
5259 ;; If cursor just entered the bottom scroll margin, move forward,
5260 ;; but also optionally vscroll one line so redisplay won't recenter.
5264 ;; Don't vscroll if the partially-visible line at window
5265 ;; bottom is not too tall (a.k.a. "just one more text
5266 ;; line"): in that case, we do want redisplay to behave
5267 ;; normally, i.e. recenter or whatever.
5269 ;; Note: ROWH + RBOT from the value returned by
5270 ;; pos-visible-in-window-p give the total height of the
5271 ;; partially-visible glyph row at the end of the window. As
5272 ;; we are dealing with floats, we disregard sub-pixel
5273 ;; discrepancies between that and DLH.
5274 (if (and rowh rbot
(>= (- (+ rowh rbot
) winh
) 1))
5275 (set-window-vscroll nil dlh t
))
5276 (line-move-1 arg noerror to-end
)
5278 ;; If there are lines above the last line, scroll-up one line.
5279 ((and vpos
(> vpos
0))
5282 ;; Finally, start vscroll.
5284 (set-window-vscroll nil dlh t
)))))))
5287 ;; This is like line-move-1 except that it also performs
5288 ;; vertical scrolling of tall images if appropriate.
5289 ;; That is not really a clean thing to do, since it mixes
5290 ;; scrolling with cursor motion. But so far we don't have
5291 ;; a cleaner solution to the problem of making C-n do something
5292 ;; useful given a tall image.
5293 (defun line-move (arg &optional noerror to-end try-vscroll
)
5294 "Move forward ARG lines.
5295 If NOERROR, don't signal an error if we can't move ARG lines.
5297 TRY-VSCROLL controls whether to vscroll tall lines: if either
5298 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
5302 (unless (and auto-window-vscroll try-vscroll
5303 ;; Only vscroll for single line moves
5305 ;; Under scroll-conservatively, the display engine
5306 ;; does this better.
5307 (zerop scroll-conservatively
)
5308 ;; But don't vscroll in a keyboard macro.
5309 (not defining-kbd-macro
)
5310 (not executing-kbd-macro
)
5311 (line-move-partial arg noerror to-end
))
5312 (set-window-vscroll nil
0 t
)
5313 (if (and line-move-visual
5314 ;; Display-based column are incompatible with goal-column.
5316 ;; When the text in the window is scrolled to the left,
5317 ;; display-based motion doesn't make sense (because each
5318 ;; logical line occupies exactly one screen line).
5319 (not (> (window-hscroll) 0))
5320 ;; Likewise when the text _was_ scrolled to the left
5321 ;; when the current run of vertical motion commands
5323 (not (and (memq last-command
5324 `(next-line previous-line
,this-command
))
5326 (numberp temporary-goal-column
)
5327 (>= temporary-goal-column
5328 (- (window-width) hscroll-margin
)))))
5329 (prog1 (line-move-visual arg noerror
)
5330 ;; If we moved into a tall line, set vscroll to make
5331 ;; scrolling through tall images more smooth.
5332 (let ((lh (line-pixel-height))
5333 (edges (window-inside-pixel-edges))
5334 (dlh (default-line-height))
5336 (setq winh
(- (nth 3 edges
) (nth 1 edges
) 1))
5338 (< (point) (window-start))
5343 (line-move-1 arg noerror to-end
)))))
5345 ;; Display-based alternative to line-move-1.
5346 ;; Arg says how many lines to move. The value is t if we can move the
5347 ;; specified number of lines.
5348 (defun line-move-visual (arg &optional noerror
)
5349 "Move ARG lines forward.
5350 If NOERROR, don't signal an error if we can't move that many lines."
5351 (let ((opoint (point))
5352 (hscroll (window-hscroll))
5354 ;; Check if the previous command was a line-motion command, or if
5355 ;; we were called from some other command.
5356 (if (and (consp temporary-goal-column
)
5357 (memq last-command
`(next-line previous-line
,this-command
)))
5358 ;; If so, there's no need to reset `temporary-goal-column',
5359 ;; but we may need to hscroll.
5360 (if (or (/= (cdr temporary-goal-column
) hscroll
)
5361 (> (cdr temporary-goal-column
) 0))
5362 (setq target-hscroll
(cdr temporary-goal-column
)))
5363 ;; Otherwise, we should reset `temporary-goal-column'.
5364 (let ((posn (posn-at-point)))
5366 ;; Handle the `overflow-newline-into-fringe' case:
5367 ((eq (nth 1 posn
) 'right-fringe
)
5368 (setq temporary-goal-column
(cons (- (window-width) 1) hscroll
)))
5369 ((car (posn-x-y posn
))
5370 (setq temporary-goal-column
5371 (cons (/ (float (car (posn-x-y posn
)))
5375 (set-window-hscroll (selected-window) target-hscroll
))
5376 ;; vertical-motion can move more than it was asked to if it moves
5377 ;; across display strings with newlines. We don't want to ring
5378 ;; the bell and announce beginning/end of buffer in that case.
5379 (or (and (or (and (>= arg
0)
5380 (>= (vertical-motion
5381 (cons (or goal-column
5382 (if (consp temporary-goal-column
)
5383 (car temporary-goal-column
)
5384 temporary-goal-column
))
5388 (<= (vertical-motion
5389 (cons (or goal-column
5390 (if (consp temporary-goal-column
)
5391 (car temporary-goal-column
)
5392 temporary-goal-column
))
5397 ;; If the goal column lies on a display string,
5398 ;; `vertical-motion' advances the cursor to the end
5399 ;; of the string. For arg < 0, this can cause the
5400 ;; cursor to get stuck. (Bug#3020).
5401 (= (vertical-motion arg
) arg
)))
5403 (signal (if (< arg
0) 'beginning-of-buffer
'end-of-buffer
)
5406 ;; This is the guts of next-line and previous-line.
5407 ;; Arg says how many lines to move.
5408 ;; The value is t if we can move the specified number of lines.
5409 (defun line-move-1 (arg &optional noerror _to-end
)
5410 ;; Don't run any point-motion hooks, and disregard intangibility,
5411 ;; for intermediate positions.
5412 (let ((inhibit-point-motion-hooks t
)
5415 (if (consp temporary-goal-column
)
5416 (setq temporary-goal-column
(+ (car temporary-goal-column
)
5417 (cdr temporary-goal-column
))))
5420 (if (not (memq last-command
'(next-line previous-line
)))
5421 (setq temporary-goal-column
5422 (if (and track-eol
(eolp)
5423 ;; Don't count beg of empty line as end of line
5424 ;; unless we just did explicit end-of-line.
5425 (or (not (bolp)) (eq last-command
'move-end-of-line
)))
5426 most-positive-fixnum
5429 (if (not (or (integerp selective-display
)
5430 line-move-ignore-invisible
))
5431 ;; Use just newline characters.
5432 ;; Set ARG to 0 if we move as many lines as requested.
5434 (progn (if (> arg
1) (forward-line (1- arg
)))
5435 ;; This way of moving forward ARG lines
5436 ;; verifies that we have a newline after the last one.
5437 ;; It doesn't get confused by intangible text.
5439 (if (zerop (forward-line 1))
5441 (and (zerop (forward-line arg
))
5445 (signal (if (< arg
0)
5446 'beginning-of-buffer
5449 ;; Move by arg lines, but ignore invisible ones.
5451 (while (and (> arg
0) (not done
))
5452 ;; If the following character is currently invisible,
5453 ;; skip all characters with that same `invisible' property value.
5454 (while (and (not (eobp)) (invisible-p (point)))
5455 (goto-char (next-char-property-change (point))))
5457 ;; We don't use `end-of-line', since we want to escape
5458 ;; from field boundaries occurring exactly at point.
5459 (goto-char (constrain-to-field
5460 (let ((inhibit-field-text-motion t
))
5461 (line-end-position))
5463 'inhibit-line-move-field-capture
))
5464 ;; If there's no invisibility here, move over the newline.
5468 (signal 'end-of-buffer nil
)
5470 ((and (> arg
1) ;; Use vertical-motion for last move
5471 (not (integerp selective-display
))
5472 (not (invisible-p (point))))
5473 ;; We avoid vertical-motion when possible
5474 ;; because that has to fontify.
5476 ;; Otherwise move a more sophisticated way.
5477 ((zerop (vertical-motion 1))
5479 (signal 'end-of-buffer nil
)
5482 (setq arg
(1- arg
))))
5483 ;; The logic of this is the same as the loop above,
5484 ;; it just goes in the other direction.
5485 (while (and (< arg
0) (not done
))
5486 ;; For completely consistency with the forward-motion
5487 ;; case, we should call beginning-of-line here.
5488 ;; However, if point is inside a field and on a
5489 ;; continued line, the call to (vertical-motion -1)
5490 ;; below won't move us back far enough; then we return
5491 ;; to the same column in line-move-finish, and point
5492 ;; gets stuck -- cyd
5497 (signal 'beginning-of-buffer nil
)
5499 ((and (< arg -
1) ;; Use vertical-motion for last move
5500 (not (integerp selective-display
))
5501 (not (invisible-p (1- (point)))))
5503 ((zerop (vertical-motion -
1))
5505 (signal 'beginning-of-buffer nil
)
5509 (while (and ;; Don't move over previous invis lines
5510 ;; if our target is the middle of this line.
5511 (or (zerop (or goal-column temporary-goal-column
))
5513 (not (bobp)) (invisible-p (1- (point))))
5514 (goto-char (previous-char-property-change (point))))))))
5515 ;; This is the value the function returns.
5519 ;; If we did not move down as far as desired, at least go
5520 ;; to end of line. Be sure to call point-entered and
5521 ;; point-left-hooks.
5522 (let* ((npoint (prog1 (line-end-position)
5523 (goto-char opoint
)))
5524 (inhibit-point-motion-hooks nil
))
5525 (goto-char npoint
)))
5527 ;; If we did not move up as far as desired,
5528 ;; at least go to beginning of line.
5529 (let* ((npoint (prog1 (line-beginning-position)
5530 (goto-char opoint
)))
5531 (inhibit-point-motion-hooks nil
))
5532 (goto-char npoint
)))
5534 (line-move-finish (or goal-column temporary-goal-column
)
5535 opoint
(> orig-arg
0)))))))
5537 (defun line-move-finish (column opoint forward
)
5540 ;; Set REPEAT to t to repeat the whole thing.
5545 (line-beg (line-beginning-position))
5547 ;; Compute the end of the line
5548 ;; ignoring effectively invisible newlines.
5550 ;; Like end-of-line but ignores fields.
5551 (skip-chars-forward "^\n")
5552 (while (and (not (eobp)) (invisible-p (point)))
5553 (goto-char (next-char-property-change (point)))
5554 (skip-chars-forward "^\n"))
5557 ;; Move to the desired column.
5558 (line-move-to-column (truncate column
))
5560 ;; Corner case: suppose we start out in a field boundary in
5561 ;; the middle of a continued line. When we get to
5562 ;; line-move-finish, point is at the start of a new *screen*
5563 ;; line but the same text line; then line-move-to-column would
5564 ;; move us backwards. Test using C-n with point on the "x" in
5565 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
5572 ;; Process intangibility within a line.
5573 ;; With inhibit-point-motion-hooks bound to nil, a call to
5574 ;; goto-char moves point past intangible text.
5576 ;; However, inhibit-point-motion-hooks controls both the
5577 ;; intangibility and the point-entered/point-left hooks. The
5578 ;; following hack avoids calling the point-* hooks
5579 ;; unnecessarily. Note that we move *forward* past intangible
5580 ;; text when the initial and final points are the same.
5582 (let ((inhibit-point-motion-hooks nil
))
5585 ;; If intangibility moves us to a different (later) place
5586 ;; in the same line, use that as the destination.
5587 (if (<= (point) line-end
)
5589 ;; If that position is "too late",
5590 ;; try the previous allowable position.
5594 ;; If going forward, don't accept the previous
5595 ;; allowable position if it is before the target line.
5596 (< line-beg
(point))
5597 ;; If going backward, don't accept the previous
5598 ;; allowable position if it is still after the target line.
5599 (<= (point) line-end
))
5601 ;; As a last resort, use the end of the line.
5602 (setq new line-end
))))
5604 ;; Now move to the updated destination, processing fields
5605 ;; as well as intangibility.
5607 (let ((inhibit-point-motion-hooks nil
))
5609 ;; Ignore field boundaries if the initial and final
5610 ;; positions have the same `field' property, even if the
5611 ;; fields are non-contiguous. This seems to be "nicer"
5612 ;; behavior in many situations.
5613 (if (eq (get-char-property new
'field
)
5614 (get-char-property opoint
'field
))
5616 (constrain-to-field new opoint t t
5617 'inhibit-line-move-field-capture
))))
5619 ;; If all this moved us to a different line,
5620 ;; retry everything within that new line.
5621 (when (or (< (point) line-beg
) (> (point) line-end
))
5622 ;; Repeat the intangibility and field processing.
5623 (setq repeat t
))))))
5625 (defun line-move-to-column (col)
5626 "Try to find column COL, considering invisibility.
5627 This function works only in certain cases,
5628 because what we really need is for `move-to-column'
5629 and `current-column' to be able to ignore invisible text."
5632 (move-to-column col
))
5634 (when (and line-move-ignore-invisible
5635 (not (bolp)) (invisible-p (1- (point))))
5636 (let ((normal-location (point))
5637 (normal-column (current-column)))
5638 ;; If the following character is currently invisible,
5639 ;; skip all characters with that same `invisible' property value.
5640 (while (and (not (eobp))
5641 (invisible-p (point)))
5642 (goto-char (next-char-property-change (point))))
5643 ;; Have we advanced to a larger column position?
5644 (if (> (current-column) normal-column
)
5645 ;; We have made some progress towards the desired column.
5646 ;; See if we can make any further progress.
5647 (line-move-to-column (+ (current-column) (- col normal-column
)))
5648 ;; Otherwise, go to the place we originally found
5649 ;; and move back over invisible text.
5650 ;; that will get us to the same place on the screen
5651 ;; but with a more reasonable buffer position.
5652 (goto-char normal-location
)
5653 (let ((line-beg (line-beginning-position)))
5654 (while (and (not (bolp)) (invisible-p (1- (point))))
5655 (goto-char (previous-char-property-change (point) line-beg
))))))))
5657 (defun move-end-of-line (arg)
5658 "Move point to end of current line as displayed.
5659 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5660 If point reaches the beginning or end of buffer, it stops there.
5662 To ignore the effects of the `intangible' text or overlay
5663 property, bind `inhibit-point-motion-hooks' to t.
5664 If there is an image in the current line, this function
5665 disregards newlines that are part of the text on which the image
5668 (or arg
(setq arg
1))
5673 (let ((goal-column 0)
5674 (line-move-visual nil
))
5675 (and (line-move arg t
)
5676 ;; With bidi reordering, we may not be at bol,
5677 ;; so make sure we are.
5678 (skip-chars-backward "^\n")
5681 (while (and (not (bobp)) (invisible-p (1- (point))))
5682 (goto-char (previous-single-char-property-change
5683 (point) 'invisible
)))
5687 (if (and (> (point) newpos
)
5688 (eq (preceding-char) ?
\n))
5690 (if (and (> (point) newpos
) (not (eobp))
5691 (not (eq (following-char) ?
\n)))
5692 ;; If we skipped something intangible and now we're not
5693 ;; really at eol, keep going.
5697 (defun move-beginning-of-line (arg)
5698 "Move point to beginning of current line as displayed.
5699 \(If there's an image in the line, this disregards newlines
5700 which are part of the text that the image rests on.)
5702 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5703 If point reaches the beginning or end of buffer, it stops there.
5704 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5706 (or arg
(setq arg
1))
5708 (let ((orig (point))
5709 first-vis first-vis-field-value
)
5711 ;; Move by lines, if ARG is not 1 (the default).
5713 (let ((line-move-visual nil
))
5714 (line-move (1- arg
) t
)))
5716 ;; Move to beginning-of-line, ignoring fields and invisible text.
5717 (skip-chars-backward "^\n")
5718 (while (and (not (bobp)) (invisible-p (1- (point))))
5719 (goto-char (previous-char-property-change (point)))
5720 (skip-chars-backward "^\n"))
5722 ;; Now find first visible char in the line.
5723 (while (and (< (point) orig
) (invisible-p (point)))
5724 (goto-char (next-char-property-change (point) orig
)))
5725 (setq first-vis
(point))
5727 ;; See if fields would stop us from reaching FIRST-VIS.
5728 (setq first-vis-field-value
5729 (constrain-to-field first-vis orig
(/= arg
1) t nil
))
5731 (goto-char (if (/= first-vis-field-value first-vis
)
5732 ;; If yes, obey them.
5733 first-vis-field-value
5734 ;; Otherwise, move to START with attention to fields.
5735 ;; (It is possible that fields never matter in this case.)
5736 (constrain-to-field (point) orig
5737 (/= arg
1) t nil
)))))
5740 ;; Many people have said they rarely use this feature, and often type
5741 ;; it by accident. Maybe it shouldn't even be on a key.
5742 (put 'set-goal-column
'disabled t
)
5744 (defun set-goal-column (arg)
5745 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
5746 Those commands will move to this position in the line moved to
5747 rather than trying to keep the same horizontal position.
5748 With a non-nil argument ARG, clears out the goal column
5749 so that \\[next-line] and \\[previous-line] resume vertical motion.
5750 The goal column is stored in the variable `goal-column'."
5754 (setq goal-column nil
)
5755 (message "No goal column"))
5756 (setq goal-column
(current-column))
5757 ;; The older method below can be erroneous if `set-goal-column' is bound
5758 ;; to a sequence containing %
5759 ;;(message (substitute-command-keys
5760 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
5764 (format "Goal column %d " goal-column
)
5765 (substitute-command-keys
5766 "(use \\[set-goal-column] with an arg to unset it)")))
5771 ;;; Editing based on visual lines, as opposed to logical lines.
5773 (defun end-of-visual-line (&optional n
)
5774 "Move point to end of current visual line.
5775 With argument N not nil or 1, move forward N - 1 visual lines first.
5776 If point reaches the beginning or end of buffer, it stops there.
5777 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5781 (let ((line-move-visual t
))
5782 (line-move (1- n
) t
)))
5783 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
5784 ;; constrain to field boundaries, so we don't either.
5785 (vertical-motion (cons (window-width) 0)))
5787 (defun beginning-of-visual-line (&optional n
)
5788 "Move point to beginning of current visual line.
5789 With argument N not nil or 1, move forward N - 1 visual lines first.
5790 If point reaches the beginning or end of buffer, it stops there.
5791 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5794 (let ((opoint (point)))
5796 (let ((line-move-visual t
))
5797 (line-move (1- n
) t
)))
5799 ;; Constrain to field boundaries, like `move-beginning-of-line'.
5800 (goto-char (constrain-to-field (point) opoint
(/= n
1)))))
5802 (defun kill-visual-line (&optional arg
)
5803 "Kill the rest of the visual line.
5804 With prefix argument ARG, kill that many visual lines from point.
5805 If ARG is negative, kill visual lines backward.
5806 If ARG is zero, kill the text before point on the current visual
5809 If you want to append the killed line to the last killed text,
5810 use \\[append-next-kill] before \\[kill-line].
5812 If the buffer is read-only, Emacs will beep and refrain from deleting
5813 the line, but put the line in the kill ring anyway. This means that
5814 you can use this command to copy text from a read-only buffer.
5815 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5818 ;; Like in `kill-line', it's better to move point to the other end
5819 ;; of the kill before killing.
5820 (let ((opoint (point))
5821 (kill-whole-line (and kill-whole-line
(bolp))))
5823 (vertical-motion (prefix-numeric-value arg
))
5824 (end-of-visual-line 1)
5825 (if (= (point) opoint
)
5827 ;; Skip any trailing whitespace at the end of the visual line.
5828 ;; We used to do this only if `show-trailing-whitespace' is
5829 ;; nil, but that's wrong; the correct thing would be to check
5830 ;; whether the trailing whitespace is highlighted. But, it's
5831 ;; OK to just do this unconditionally.
5832 (skip-chars-forward " \t")))
5833 (kill-region opoint
(if (and kill-whole-line
(looking-at "\n"))
5837 (defun next-logical-line (&optional arg try-vscroll
)
5838 "Move cursor vertically down ARG lines.
5839 This is identical to `next-line', except that it always moves
5840 by logical lines instead of visual lines, ignoring the value of
5841 the variable `line-move-visual'."
5842 (interactive "^p\np")
5843 (let ((line-move-visual nil
))
5845 (next-line arg try-vscroll
))))
5847 (defun previous-logical-line (&optional arg try-vscroll
)
5848 "Move cursor vertically up ARG lines.
5849 This is identical to `previous-line', except that it always moves
5850 by logical lines instead of visual lines, ignoring the value of
5851 the variable `line-move-visual'."
5852 (interactive "^p\np")
5853 (let ((line-move-visual nil
))
5855 (previous-line arg try-vscroll
))))
5857 (defgroup visual-line nil
5858 "Editing based on visual lines."
5862 (defvar visual-line-mode-map
5863 (let ((map (make-sparse-keymap)))
5864 (define-key map
[remap kill-line
] 'kill-visual-line
)
5865 (define-key map
[remap move-beginning-of-line
] 'beginning-of-visual-line
)
5866 (define-key map
[remap move-end-of-line
] 'end-of-visual-line
)
5867 ;; These keybindings interfere with xterm function keys. Are
5868 ;; there any other suitable bindings?
5869 ;; (define-key map "\M-[" 'previous-logical-line)
5870 ;; (define-key map "\M-]" 'next-logical-line)
5873 (defcustom visual-line-fringe-indicators
'(nil nil
)
5874 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
5875 The value should be a list of the form (LEFT RIGHT), where LEFT
5876 and RIGHT are symbols representing the bitmaps to display, to
5877 indicate wrapped lines, in the left and right fringes respectively.
5878 See also `fringe-indicator-alist'.
5879 The default is not to display fringe indicators for wrapped lines.
5880 This variable does not affect fringe indicators displayed for
5882 :type
'(list (choice (const :tag
"Hide left indicator" nil
)
5883 (const :tag
"Left curly arrow" left-curly-arrow
)
5884 (symbol :tag
"Other bitmap"))
5885 (choice (const :tag
"Hide right indicator" nil
)
5886 (const :tag
"Right curly arrow" right-curly-arrow
)
5887 (symbol :tag
"Other bitmap")))
5888 :set
(lambda (symbol value
)
5889 (dolist (buf (buffer-list))
5890 (with-current-buffer buf
5891 (when (and (boundp 'visual-line-mode
)
5892 (symbol-value 'visual-line-mode
))
5893 (setq fringe-indicator-alist
5894 (cons (cons 'continuation value
)
5897 (copy-tree fringe-indicator-alist
)))))))
5898 (set-default symbol value
)))
5900 (defvar visual-line--saved-state nil
)
5902 (define-minor-mode visual-line-mode
5903 "Toggle visual line based editing (Visual Line mode).
5904 With a prefix argument ARG, enable Visual Line mode if ARG is
5905 positive, and disable it otherwise. If called from Lisp, enable
5906 the mode if ARG is omitted or nil.
5908 When Visual Line mode is enabled, `word-wrap' is turned on in
5909 this buffer, and simple editing commands are redefined to act on
5910 visual lines, not logical lines. See Info node `Visual Line
5912 :keymap visual-line-mode-map
5915 (if visual-line-mode
5917 (set (make-local-variable 'visual-line--saved-state
) nil
)
5918 ;; Save the local values of some variables, to be restored if
5919 ;; visual-line-mode is turned off.
5920 (dolist (var '(line-move-visual truncate-lines
5921 truncate-partial-width-windows
5922 word-wrap fringe-indicator-alist
))
5923 (if (local-variable-p var
)
5924 (push (cons var
(symbol-value var
))
5925 visual-line--saved-state
)))
5926 (set (make-local-variable 'line-move-visual
) t
)
5927 (set (make-local-variable 'truncate-partial-width-windows
) nil
)
5928 (setq truncate-lines nil
5930 fringe-indicator-alist
5931 (cons (cons 'continuation visual-line-fringe-indicators
)
5932 fringe-indicator-alist
)))
5933 (kill-local-variable 'line-move-visual
)
5934 (kill-local-variable 'word-wrap
)
5935 (kill-local-variable 'truncate-lines
)
5936 (kill-local-variable 'truncate-partial-width-windows
)
5937 (kill-local-variable 'fringe-indicator-alist
)
5938 (dolist (saved visual-line--saved-state
)
5939 (set (make-local-variable (car saved
)) (cdr saved
)))
5940 (kill-local-variable 'visual-line--saved-state
)))
5942 (defun turn-on-visual-line-mode ()
5943 (visual-line-mode 1))
5945 (define-globalized-minor-mode global-visual-line-mode
5946 visual-line-mode turn-on-visual-line-mode
)
5949 (defun transpose-chars (arg)
5950 "Interchange characters around point, moving forward one character.
5951 With prefix arg ARG, effect is to take character before point
5952 and drag it forward past ARG other characters (backward if ARG negative).
5953 If no argument and at end of line, the previous two chars are exchanged."
5955 (when (and (null arg
) (eolp) (not (bobp))
5956 (not (get-text-property (1- (point)) 'read-only
)))
5958 (transpose-subr 'forward-char
(prefix-numeric-value arg
)))
5960 (defun transpose-words (arg)
5961 "Interchange words around point, leaving point at end of them.
5962 With prefix arg ARG, effect is to take word before or around point
5963 and drag it forward past ARG other words (backward if ARG negative).
5964 If ARG is zero, the words around or after point and around or after mark
5966 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
5968 (transpose-subr 'forward-word arg
))
5970 (defun transpose-sexps (arg)
5971 "Like \\[transpose-words] but applies to sexps.
5972 Does not work on a sexp that point is in the middle of
5973 if it is a list or string."
5977 ;; Here we should try to simulate the behavior of
5978 ;; (cons (progn (forward-sexp x) (point))
5979 ;; (progn (forward-sexp (- x)) (point)))
5980 ;; Except that we don't want to rely on the second forward-sexp
5981 ;; putting us back to where we want to be, since forward-sexp-function
5982 ;; might do funny things like infix-precedence.
5984 (looking-at "\\sw\\|\\s_")
5986 (save-excursion (forward-char -
1) (looking-at "\\sw\\|\\s_"))))
5987 ;; Jumping over a symbol. We might be inside it, mind you.
5988 (progn (funcall (if (> arg
0)
5989 'skip-syntax-backward
'skip-syntax-forward
)
5991 (cons (save-excursion (forward-sexp arg
) (point)) (point)))
5992 ;; Otherwise, we're between sexps. Take a step back before jumping
5993 ;; to make sure we'll obey the same precedence no matter which direction
5995 (funcall (if (> arg
0) 'skip-syntax-backward
'skip-syntax-forward
) " .")
5996 (cons (save-excursion (forward-sexp arg
) (point))
5997 (progn (while (or (forward-comment (if (> arg
0) 1 -
1))
5998 (not (zerop (funcall (if (> arg
0)
5999 'skip-syntax-forward
6000 'skip-syntax-backward
)
6005 (defun transpose-lines (arg)
6006 "Exchange current line and previous line, leaving point after both.
6007 With argument ARG, takes previous line and moves it past ARG lines.
6008 With argument 0, interchanges line point is in with line mark is in."
6010 (transpose-subr (function
6014 ;; Move forward over ARG lines,
6015 ;; but create newlines if necessary.
6016 (setq arg
(forward-line arg
))
6017 (if (/= (preceding-char) ?
\n)
6018 (setq arg
(1+ arg
)))
6021 (forward-line arg
))))
6024 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6025 ;; which seems inconsistent with the ARG /= 0 case.
6026 ;; FIXME document SPECIAL.
6027 (defun transpose-subr (mover arg
&optional special
)
6028 "Subroutine to do the work of transposing objects.
6029 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6030 moves forward by units of the given object (e.g. forward-sentence,
6031 forward-paragraph). If ARG is zero, exchanges the current object
6032 with the one containing mark. If ARG is an integer, moves the
6033 current object past ARG following (if ARG is positive) or
6034 preceding (if ARG is negative) objects, leaving point after the
6036 (let ((aux (if special mover
6038 (cons (progn (funcall mover x
) (point))
6039 (progn (funcall mover
(- x
)) (point))))))
6044 (setq pos1
(funcall aux
1))
6045 (goto-char (or (mark) (error "No mark set in this buffer")))
6046 (setq pos2
(funcall aux
1))
6047 (transpose-subr-1 pos1 pos2
))
6048 (exchange-point-and-mark))
6050 (setq pos1
(funcall aux -
1))
6051 (setq pos2
(funcall aux arg
))
6052 (transpose-subr-1 pos1 pos2
)
6053 (goto-char (car pos2
)))
6055 (setq pos1
(funcall aux -
1))
6056 (goto-char (car pos1
))
6057 (setq pos2
(funcall aux arg
))
6058 (transpose-subr-1 pos1 pos2
)))))
6060 (defun transpose-subr-1 (pos1 pos2
)
6061 (when (> (car pos1
) (cdr pos1
)) (setq pos1
(cons (cdr pos1
) (car pos1
))))
6062 (when (> (car pos2
) (cdr pos2
)) (setq pos2
(cons (cdr pos2
) (car pos2
))))
6063 (when (> (car pos1
) (car pos2
))
6065 (setq pos1 pos2 pos2 swap
)))
6066 (if (> (cdr pos1
) (car pos2
)) (error "Don't have two things to transpose"))
6067 (atomic-change-group
6068 ;; This sequence of insertions attempts to preserve marker
6069 ;; positions at the start and end of the transposed objects.
6070 (let* ((word (buffer-substring (car pos2
) (cdr pos2
)))
6071 (len1 (- (cdr pos1
) (car pos1
)))
6072 (len2 (length word
))
6073 (boundary (make-marker)))
6074 (set-marker boundary
(car pos2
))
6075 (goto-char (cdr pos1
))
6076 (insert-before-markers word
)
6077 (setq word
(delete-and-extract-region (car pos1
) (+ (car pos1
) len1
)))
6078 (goto-char boundary
)
6080 (goto-char (+ boundary len1
))
6081 (delete-region (point) (+ (point) len2
))
6082 (set-marker boundary nil
))))
6084 (defun backward-word (&optional arg
)
6085 "Move backward until encountering the beginning of a word.
6086 With argument ARG, do this that many times.
6087 If ARG is omitted or nil, move point backward one word."
6089 (forward-word (- (or arg
1))))
6091 (defun mark-word (&optional arg allow-extend
)
6092 "Set mark ARG words away from point.
6093 The place mark goes is the same place \\[forward-word] would
6094 move to with the same argument.
6095 Interactively, if this command is repeated
6096 or (in Transient Mark mode) if the mark is active,
6097 it marks the next ARG words after the ones already marked."
6098 (interactive "P\np")
6099 (cond ((and allow-extend
6100 (or (and (eq last-command this-command
) (mark t
))
6102 (setq arg
(if arg
(prefix-numeric-value arg
)
6103 (if (< (mark) (point)) -
1 1)))
6112 (forward-word (prefix-numeric-value arg
))
6116 (defun kill-word (arg)
6117 "Kill characters forward until encountering the end of a word.
6118 With argument ARG, do this that many times."
6120 (kill-region (point) (progn (forward-word arg
) (point))))
6122 (defun backward-kill-word (arg)
6123 "Kill characters backward until encountering the beginning of a word.
6124 With argument ARG, do this that many times."
6126 (kill-word (- arg
)))
6128 (defun current-word (&optional strict really-word
)
6129 "Return the symbol or word that point is on (or a nearby one) as a string.
6130 The return value includes no text properties.
6131 If optional arg STRICT is non-nil, return nil unless point is within
6132 or adjacent to a symbol or word. In all cases the value can be nil
6133 if there is no word nearby.
6134 The function, belying its name, normally finds a symbol.
6135 If optional arg REALLY-WORD is non-nil, it finds just a word."
6137 (let* ((oldpoint (point)) (start (point)) (end (point))
6138 (syntaxes (if really-word
"w" "w_"))
6139 (not-syntaxes (concat "^" syntaxes
)))
6140 (skip-syntax-backward syntaxes
) (setq start
(point))
6141 (goto-char oldpoint
)
6142 (skip-syntax-forward syntaxes
) (setq end
(point))
6143 (when (and (eq start oldpoint
) (eq end oldpoint
)
6144 ;; Point is neither within nor adjacent to a word.
6146 ;; Look for preceding word in same line.
6147 (skip-syntax-backward not-syntaxes
(line-beginning-position))
6149 ;; No preceding word in same line.
6150 ;; Look for following word in same line.
6152 (skip-syntax-forward not-syntaxes
(line-end-position))
6153 (setq start
(point))
6154 (skip-syntax-forward syntaxes
)
6157 (skip-syntax-backward syntaxes
)
6158 (setq start
(point))))
6159 ;; If we found something nonempty, return it as a string.
6160 (unless (= start end
)
6161 (buffer-substring-no-properties start end
)))))
6163 (defcustom fill-prefix nil
6164 "String for filling to insert at front of new line, or nil for none."
6165 :type
'(choice (const :tag
"None" nil
)
6168 (make-variable-buffer-local 'fill-prefix
)
6169 (put 'fill-prefix
'safe-local-variable
'string-or-null-p
)
6171 (defcustom auto-fill-inhibit-regexp nil
6172 "Regexp to match lines which should not be auto-filled."
6173 :type
'(choice (const :tag
"None" nil
)
6177 (defun do-auto-fill ()
6178 "The default value for `normal-auto-fill-function'.
6179 This is the default auto-fill function, some major modes use a different one.
6180 Returns t if it really did any work."
6181 (let (fc justify give-up
6182 (fill-prefix fill-prefix
))
6183 (if (or (not (setq justify
(current-justification)))
6184 (null (setq fc
(current-fill-column)))
6185 (and (eq justify
'left
)
6186 (<= (current-column) fc
))
6187 (and auto-fill-inhibit-regexp
6188 (save-excursion (beginning-of-line)
6189 (looking-at auto-fill-inhibit-regexp
))))
6190 nil
;; Auto-filling not required
6191 (if (memq justify
'(full center right
))
6192 (save-excursion (unjustify-current-line)))
6194 ;; Choose a fill-prefix automatically.
6195 (when (and adaptive-fill-mode
6196 (or (null fill-prefix
) (string= fill-prefix
"")))
6198 (fill-context-prefix
6199 (save-excursion (fill-forward-paragraph -
1) (point))
6200 (save-excursion (fill-forward-paragraph 1) (point)))))
6201 (and prefix
(not (equal prefix
""))
6202 ;; Use auto-indentation rather than a guessed empty prefix.
6203 (not (and fill-indent-according-to-mode
6204 (string-match "\\`[ \t]*\\'" prefix
)))
6205 (setq fill-prefix prefix
))))
6207 (while (and (not give-up
) (> (current-column) fc
))
6208 ;; Determine where to split the line.
6213 (setq after-prefix
(point))
6215 (looking-at (regexp-quote fill-prefix
))
6216 (setq after-prefix
(match-end 0)))
6217 (move-to-column (1+ fc
))
6218 (fill-move-to-break-point after-prefix
)
6221 ;; See whether the place we found is any good.
6223 (goto-char fill-point
)
6225 ;; There is no use breaking at end of line.
6226 (save-excursion (skip-chars-forward " ") (eolp))
6227 ;; It is futile to split at the end of the prefix
6228 ;; since we would just insert the prefix again.
6229 (and after-prefix
(<= (point) after-prefix
))
6230 ;; Don't split right after a comment starter
6231 ;; since we would just make another comment starter.
6232 (and comment-start-skip
6233 (let ((limit (point)))
6235 (and (re-search-forward comment-start-skip
6237 (eq (point) limit
))))))
6238 ;; No good place to break => stop trying.
6240 ;; Ok, we have a useful place to break the line. Do it.
6241 (let ((prev-column (current-column)))
6242 ;; If point is at the fill-point, do not `save-excursion'.
6243 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6244 ;; point will end up before it rather than after it.
6246 (skip-chars-backward " \t")
6247 (= (point) fill-point
))
6248 (default-indent-new-line t
)
6250 (goto-char fill-point
)
6251 (default-indent-new-line t
)))
6252 ;; Now do justification, if required
6253 (if (not (eq justify
'left
))
6256 (justify-current-line justify nil t
)))
6257 ;; If making the new line didn't reduce the hpos of
6258 ;; the end of the line, then give up now;
6259 ;; trying again will not help.
6260 (if (>= (current-column) prev-column
)
6261 (setq give-up t
))))))
6262 ;; Justify last line.
6263 (justify-current-line justify t t
)
6266 (defvar comment-line-break-function
'comment-indent-new-line
6267 "Mode-specific function which line breaks and continues a comment.
6268 This function is called during auto-filling when a comment syntax
6270 The function should take a single optional argument, which is a flag
6271 indicating whether it should use soft newlines.")
6273 (defun default-indent-new-line (&optional soft
)
6274 "Break line at point and indent.
6275 If a comment syntax is defined, call `comment-indent-new-line'.
6277 The inserted newline is marked hard if variable `use-hard-newlines' is true,
6278 unless optional argument SOFT is non-nil."
6281 (funcall comment-line-break-function soft
)
6282 ;; Insert the newline before removing empty space so that markers
6283 ;; get preserved better.
6284 (if soft
(insert-and-inherit ?
\n) (newline 1))
6285 (save-excursion (forward-char -
1) (delete-horizontal-space))
6286 (delete-horizontal-space)
6288 (if (and fill-prefix
(not adaptive-fill-mode
))
6289 ;; Blindly trust a non-adaptive fill-prefix.
6291 (indent-to-left-margin)
6292 (insert-before-markers-and-inherit fill-prefix
))
6295 ;; If there's an adaptive prefix, use it unless we're inside
6296 ;; a comment and the prefix is not a comment starter.
6298 (indent-to-left-margin)
6299 (insert-and-inherit fill-prefix
))
6300 ;; If we're not inside a comment, just try to indent.
6301 (t (indent-according-to-mode))))))
6303 (defvar normal-auto-fill-function
'do-auto-fill
6304 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6305 Some major modes set this.")
6307 (put 'auto-fill-function
:minor-mode-function
'auto-fill-mode
)
6308 ;; `functions' and `hooks' are usually unsafe to set, but setting
6309 ;; auto-fill-function to nil in a file-local setting is safe and
6310 ;; can be useful to prevent auto-filling.
6311 (put 'auto-fill-function
'safe-local-variable
'null
)
6313 (define-minor-mode auto-fill-mode
6314 "Toggle automatic line breaking (Auto Fill mode).
6315 With a prefix argument ARG, enable Auto Fill mode if ARG is
6316 positive, and disable it otherwise. If called from Lisp, enable
6317 the mode if ARG is omitted or nil.
6319 When Auto Fill mode is enabled, inserting a space at a column
6320 beyond `current-fill-column' automatically breaks the line at a
6323 When `auto-fill-mode' is on, the `auto-fill-function' variable is
6326 The value of `normal-auto-fill-function' specifies the function to use
6327 for `auto-fill-function' when turning Auto Fill mode on."
6328 :variable
(auto-fill-function
6329 .
(lambda (v) (setq auto-fill-function
6330 (if v normal-auto-fill-function
)))))
6332 ;; This holds a document string used to document auto-fill-mode.
6333 (defun auto-fill-function ()
6334 "Automatically break line at a previous space, in insertion of text."
6337 (defun turn-on-auto-fill ()
6338 "Unconditionally turn on Auto Fill mode."
6341 (defun turn-off-auto-fill ()
6342 "Unconditionally turn off Auto Fill mode."
6343 (auto-fill-mode -
1))
6345 (custom-add-option 'text-mode-hook
'turn-on-auto-fill
)
6347 (defun set-fill-column (arg)
6348 "Set `fill-column' to specified argument.
6349 Use \\[universal-argument] followed by a number to specify a column.
6350 Just \\[universal-argument] as argument means to use the current column."
6352 (list (or current-prefix-arg
6353 ;; We used to use current-column silently, but C-x f is too easily
6354 ;; typed as a typo for C-x C-f, so we turned it into an error and
6355 ;; now an interactive prompt.
6356 (read-number "Set fill-column to: " (current-column)))))
6358 (setq arg
(current-column)))
6359 (if (not (integerp arg
))
6360 ;; Disallow missing argument; it's probably a typo for C-x C-f.
6361 (error "set-fill-column requires an explicit argument")
6362 (message "Fill column set to %d (was %d)" arg fill-column
)
6363 (setq fill-column arg
)))
6365 (defun set-selective-display (arg)
6366 "Set `selective-display' to ARG; clear it if no arg.
6367 When the value of `selective-display' is a number > 0,
6368 lines whose indentation is >= that value are not displayed.
6369 The variable `selective-display' has a separate value for each buffer."
6371 (if (eq selective-display t
)
6372 (error "selective-display already in use for marked lines"))
6375 (narrow-to-region (point-min) (point))
6376 (goto-char (window-start))
6377 (vertical-motion (window-height)))))
6378 (setq selective-display
6379 (and arg
(prefix-numeric-value arg
)))
6380 (recenter current-vpos
))
6381 (set-window-start (selected-window) (window-start))
6382 (princ "selective-display set to " t
)
6383 (prin1 selective-display t
)
6386 (defvaralias 'indicate-unused-lines
'indicate-empty-lines
)
6388 (defun toggle-truncate-lines (&optional arg
)
6389 "Toggle truncating of long lines for the current buffer.
6390 When truncating is off, long lines are folded.
6391 With prefix argument ARG, truncate long lines if ARG is positive,
6392 otherwise fold them. Note that in side-by-side windows, this
6393 command has no effect if `truncate-partial-width-windows' is
6396 (setq truncate-lines
6398 (not truncate-lines
)
6399 (> (prefix-numeric-value arg
) 0)))
6400 (force-mode-line-update)
6401 (unless truncate-lines
6402 (let ((buffer (current-buffer)))
6403 (walk-windows (lambda (window)
6404 (if (eq buffer
(window-buffer window
))
6405 (set-window-hscroll window
0)))
6407 (message "Truncate long lines %s"
6408 (if truncate-lines
"enabled" "disabled")))
6410 (defun toggle-word-wrap (&optional arg
)
6411 "Toggle whether to use word-wrapping for continuation lines.
6412 With prefix argument ARG, wrap continuation lines at word boundaries
6413 if ARG is positive, otherwise wrap them at the right screen edge.
6414 This command toggles the value of `word-wrap'. It has no effect
6415 if long lines are truncated."
6420 (> (prefix-numeric-value arg
) 0)))
6421 (force-mode-line-update)
6422 (message "Word wrapping %s"
6423 (if word-wrap
"enabled" "disabled")))
6425 (defvar overwrite-mode-textual
(purecopy " Ovwrt")
6426 "The string displayed in the mode line when in overwrite mode.")
6427 (defvar overwrite-mode-binary
(purecopy " Bin Ovwrt")
6428 "The string displayed in the mode line when in binary overwrite mode.")
6430 (define-minor-mode overwrite-mode
6431 "Toggle Overwrite mode.
6432 With a prefix argument ARG, enable Overwrite mode if ARG is
6433 positive, and disable it otherwise. If called from Lisp, enable
6434 the mode if ARG is omitted or nil.
6436 When Overwrite mode is enabled, printing characters typed in
6437 replace existing text on a one-for-one basis, rather than pushing
6438 it to the right. At the end of a line, such characters extend
6439 the line. Before a tab, such characters insert until the tab is
6440 filled in. \\[quoted-insert] still inserts characters in
6441 overwrite mode; this is supposed to make it easier to insert
6442 characters when necessary."
6443 :variable
(overwrite-mode
6444 .
(lambda (v) (setq overwrite-mode
(if v
'overwrite-mode-textual
)))))
6446 (define-minor-mode binary-overwrite-mode
6447 "Toggle Binary Overwrite mode.
6448 With a prefix argument ARG, enable Binary Overwrite mode if ARG
6449 is positive, and disable it otherwise. If called from Lisp,
6450 enable the mode if ARG is omitted or nil.
6452 When Binary Overwrite mode is enabled, printing characters typed
6453 in replace existing text. Newlines are not treated specially, so
6454 typing at the end of a line joins the line to the next, with the
6455 typed character between them. Typing before a tab character
6456 simply replaces the tab with the character typed.
6457 \\[quoted-insert] replaces the text at the cursor, just as
6458 ordinary typing characters do.
6460 Note that Binary Overwrite mode is not its own minor mode; it is
6461 a specialization of overwrite mode, entered by setting the
6462 `overwrite-mode' variable to `overwrite-mode-binary'."
6463 :variable
(overwrite-mode
6464 .
(lambda (v) (setq overwrite-mode
(if v
'overwrite-mode-binary
)))))
6466 (define-minor-mode line-number-mode
6467 "Toggle line number display in the mode line (Line Number mode).
6468 With a prefix argument ARG, enable Line Number mode if ARG is
6469 positive, and disable it otherwise. If called from Lisp, enable
6470 the mode if ARG is omitted or nil.
6472 Line numbers do not appear for very large buffers and buffers
6473 with very long lines; see variables `line-number-display-limit'
6474 and `line-number-display-limit-width'."
6475 :init-value t
:global t
:group
'mode-line
)
6477 (define-minor-mode column-number-mode
6478 "Toggle column number display in the mode line (Column Number mode).
6479 With a prefix argument ARG, enable Column Number mode if ARG is
6480 positive, and disable it otherwise.
6482 If called from Lisp, enable the mode if ARG is omitted or nil."
6483 :global t
:group
'mode-line
)
6485 (define-minor-mode size-indication-mode
6486 "Toggle buffer size display in the mode line (Size Indication mode).
6487 With a prefix argument ARG, enable Size Indication mode if ARG is
6488 positive, and disable it otherwise.
6490 If called from Lisp, enable the mode if ARG is omitted or nil."
6491 :global t
:group
'mode-line
)
6493 (define-minor-mode auto-save-mode
6494 "Toggle auto-saving in the current buffer (Auto Save mode).
6495 With a prefix argument ARG, enable Auto Save mode if ARG is
6496 positive, and disable it otherwise.
6498 If called from Lisp, enable the mode if ARG is omitted or nil."
6499 :variable
((and buffer-auto-save-file-name
6500 ;; If auto-save is off because buffer has shrunk,
6501 ;; then toggling should turn it on.
6502 (>= buffer-saved-size
0))
6504 (setq buffer-auto-save-file-name
6507 ((and buffer-file-name auto-save-visited-file-name
6508 (not buffer-read-only
))
6510 (t (make-auto-save-file-name))))))
6511 ;; If -1 was stored here, to temporarily turn off saving,
6513 (and (< buffer-saved-size
0)
6514 (setq buffer-saved-size
0)))
6516 (defgroup paren-blinking nil
6517 "Blinking matching of parens and expressions."
6518 :prefix
"blink-matching-"
6519 :group
'paren-matching
)
6521 (defcustom blink-matching-paren t
6522 "Non-nil means show matching open-paren when close-paren is inserted.
6523 If t, highlight the paren. If `jump', move cursor to its position."
6525 (const :tag
"Disable" nil
)
6526 (const :tag
"Highlight" t
)
6527 (const :tag
"Move cursor" jump
))
6528 :group
'paren-blinking
)
6530 (defcustom blink-matching-paren-on-screen t
6531 "Non-nil means show matching open-paren when it is on screen.
6532 If nil, don't show it (but the open-paren can still be shown
6533 when it is off screen).
6535 This variable has no effect if `blink-matching-paren' is nil.
6536 \(In that case, the open-paren is never shown.)
6537 It is also ignored if `show-paren-mode' is enabled."
6539 :group
'paren-blinking
)
6541 (defcustom blink-matching-paren-distance
(* 100 1024)
6542 "If non-nil, maximum distance to search backwards for matching open-paren.
6543 If nil, search stops at the beginning of the accessible portion of the buffer."
6544 :version
"23.2" ; 25->100k
6545 :type
'(choice (const nil
) integer
)
6546 :group
'paren-blinking
)
6548 (defcustom blink-matching-delay
1
6549 "Time in seconds to delay after showing a matching paren."
6551 :group
'paren-blinking
)
6553 (defcustom blink-matching-paren-dont-ignore-comments nil
6554 "If nil, `blink-matching-paren' ignores comments.
6555 More precisely, when looking for the matching parenthesis,
6556 it skips the contents of comments that end before point."
6558 :group
'paren-blinking
)
6560 (defun blink-matching-check-mismatch (start end
)
6561 "Return whether or not START...END are matching parens.
6562 END is the current point and START is the blink position.
6563 START might be nil if no matching starter was found.
6564 Returns non-nil if we find there is a mismatch."
6565 (let* ((end-syntax (syntax-after (1- end
)))
6566 (matching-paren (and (consp end-syntax
)
6567 (eq (syntax-class end-syntax
) 5)
6569 ;; For self-matched chars like " and $, we can't know when they're
6570 ;; mismatched or unmatched, so we can only do it for parens.
6571 (when matching-paren
6574 (eq (char-after start
) matching-paren
)
6575 ;; The cdr might hold a new paren-class info rather than
6576 ;; a matching-char info, in which case the two CDRs
6578 (eq matching-paren
(cdr-safe (syntax-after start
)))))))))
6580 (defvar blink-matching-check-function
#'blink-matching-check-mismatch
6581 "Function to check parentheses mismatches.
6582 The function takes two arguments (START and END) where START is the
6583 position just before the opening token and END is the position right after.
6584 START can be nil, if it was not found.
6585 The function should return non-nil if the two tokens do not match.")
6587 (defvar blink-matching--overlay
6588 (let ((ol (make-overlay (point) (point) nil t
)))
6589 (overlay-put ol
'face
'show-paren-match
)
6592 "Overlay used to highlight the matching paren.")
6594 (defun blink-matching-open ()
6595 "Momentarily highlight the beginning of the sexp before point."
6597 (when (and (not (bobp))
6598 blink-matching-paren
)
6599 (let* ((oldpos (point))
6600 (message-log-max nil
) ; Don't log messages about paren matching.
6604 (if blink-matching-paren-distance
6606 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
6607 (- (point) blink-matching-paren-distance
))
6609 (let ((parse-sexp-ignore-comments
6610 (and parse-sexp-ignore-comments
6611 (not blink-matching-paren-dont-ignore-comments
))))
6614 (syntax-propertize (point))
6616 ;; backward-sexp skips backward over prefix chars,
6617 ;; so move back to the matching paren.
6618 (while (and (< (point) (1- oldpos
))
6619 (let ((code (syntax-after (point))))
6620 (or (eq (syntax-class code
) 6)
6621 (eq (logand 1048576 (car code
))
6626 (mismatch (funcall blink-matching-check-function blinkpos oldpos
)))
6631 (minibuffer-message "Mismatched parentheses")
6632 (message "Mismatched parentheses"))
6634 (minibuffer-message "No matching parenthesis found")
6635 (message "No matching parenthesis found"))))
6636 ((not blinkpos
) nil
)
6637 ((pos-visible-in-window-p blinkpos
)
6638 ;; Matching open within window, temporarily move to or highlight
6639 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
6641 (and blink-matching-paren-on-screen
6642 (not show-paren-mode
)
6643 (if (eq blink-matching-paren
'jump
)
6645 (goto-char blinkpos
)
6646 (sit-for blink-matching-delay
))
6649 (move-overlay blink-matching--overlay blinkpos
(1+ blinkpos
)
6651 (sit-for blink-matching-delay
))
6652 (delete-overlay blink-matching--overlay
)))))
6655 (goto-char blinkpos
)
6656 (let ((open-paren-line-string
6657 ;; Show what precedes the open in its line, if anything.
6659 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
6660 (buffer-substring (line-beginning-position)
6662 ;; Show what follows the open in its line, if anything.
6665 (skip-chars-forward " \t")
6667 (buffer-substring blinkpos
6668 (line-end-position)))
6669 ;; Otherwise show the previous nonblank line,
6671 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
6673 (buffer-substring (progn
6674 (skip-chars-backward "\n \t")
6675 (line-beginning-position))
6676 (progn (end-of-line)
6677 (skip-chars-backward " \t")
6679 ;; Replace the newline and other whitespace with `...'.
6681 (buffer-substring blinkpos
(1+ blinkpos
))))
6682 ;; There is nothing to show except the char itself.
6683 (t (buffer-substring blinkpos
(1+ blinkpos
))))))
6684 (message "Matches %s"
6685 (substring-no-properties open-paren-line-string
)))))))))
6687 (defvar blink-paren-function
'blink-matching-open
6688 "Function called, if non-nil, whenever a close parenthesis is inserted.
6689 More precisely, a char with closeparen syntax is self-inserted.")
6691 (defun blink-paren-post-self-insert-function ()
6692 (when (and (eq (char-before) last-command-event
) ; Sanity check.
6693 (memq (char-syntax last-command-event
) '(?\
) ?\$
))
6694 blink-paren-function
6695 (not executing-kbd-macro
)
6696 (not noninteractive
)
6697 ;; Verify an even number of quoting characters precede the close.
6698 (= 1 (logand 1 (- (point)
6701 (skip-syntax-backward "/\\")
6703 (funcall blink-paren-function
)))
6705 (put 'blink-paren-post-self-insert-function
'priority
100)
6707 (add-hook 'post-self-insert-hook
#'blink-paren-post-self-insert-function
6708 ;; Most likely, this hook is nil, so this arg doesn't matter,
6709 ;; but I use it as a reminder that this function usually
6710 ;; likes to be run after others since it does
6711 ;; `sit-for'. That's also the reason it get a `priority' prop
6715 ;; This executes C-g typed while Emacs is waiting for a command.
6716 ;; Quitting out of a program does not go through here;
6717 ;; that happens in the QUIT macro at the C code level.
6718 (defun keyboard-quit ()
6719 "Signal a `quit' condition.
6720 During execution of Lisp code, this character causes a quit directly.
6721 At top-level, as an editor command, this simply beeps."
6723 ;; Avoid adding the region to the window selection.
6724 (setq saved-region-selection nil
)
6725 (let (select-active-regions)
6727 (if (fboundp 'kmacro-keyboard-quit
)
6728 (kmacro-keyboard-quit))
6729 (when completion-in-region-mode
6730 (completion-in-region-mode -
1))
6731 ;; Force the next redisplay cycle to remove the "Def" indicator from
6732 ;; all the mode lines.
6733 (if defining-kbd-macro
6734 (force-mode-line-update t
))
6735 (setq defining-kbd-macro nil
)
6736 (let ((debug-on-quit nil
))
6737 (signal 'quit nil
)))
6739 (defvar buffer-quit-function nil
6740 "Function to call to \"quit\" the current buffer, or nil if none.
6741 \\[keyboard-escape-quit] calls this function when its more local actions
6742 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
6744 (defun keyboard-escape-quit ()
6745 "Exit the current \"mode\" (in a generalized sense of the word).
6746 This command can exit an interactive command such as `query-replace',
6747 can clear out a prefix argument or a region,
6748 can get out of the minibuffer or other recursive edit,
6749 cancel the use of the current buffer (for special-purpose buffers),
6750 or go back to just one window (by deleting all but the selected window)."
6752 (cond ((eq last-command
'mode-exited
) nil
)
6755 ((> (minibuffer-depth) 0)
6756 (abort-recursive-edit))
6759 ((> (recursion-depth) 0)
6760 (exit-recursive-edit))
6761 (buffer-quit-function
6762 (funcall buffer-quit-function
))
6763 ((not (one-window-p t
))
6764 (delete-other-windows))
6765 ((string-match "^ \\*" (buffer-name (current-buffer)))
6768 (defun play-sound-file (file &optional volume device
)
6769 "Play sound stored in FILE.
6770 VOLUME and DEVICE correspond to the keywords of the sound
6771 specification for `play-sound'."
6772 (interactive "fPlay sound file: ")
6773 (let ((sound (list :file file
)))
6775 (plist-put sound
:volume volume
))
6777 (plist-put sound
:device device
))
6779 (play-sound sound
)))
6782 (defcustom read-mail-command
'rmail
6783 "Your preference for a mail reading package.
6784 This is used by some keybindings which support reading mail.
6785 See also `mail-user-agent' concerning sending mail."
6786 :type
'(radio (function-item :tag
"Rmail" :format
"%t\n" rmail
)
6787 (function-item :tag
"Gnus" :format
"%t\n" gnus
)
6788 (function-item :tag
"Emacs interface to MH"
6789 :format
"%t\n" mh-rmail
)
6790 (function :tag
"Other"))
6794 (defcustom mail-user-agent
'message-user-agent
6795 "Your preference for a mail composition package.
6796 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
6797 outgoing email message. This variable lets you specify which
6798 mail-sending package you prefer.
6800 Valid values include:
6802 `message-user-agent' -- use the Message package.
6803 See Info node `(message)'.
6804 `sendmail-user-agent' -- use the Mail package.
6805 See Info node `(emacs)Sending Mail'.
6806 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
6807 See Info node `(mh-e)'.
6808 `gnus-user-agent' -- like `message-user-agent', but with Gnus
6809 paraphernalia if Gnus is running, particularly
6810 the Gcc: header for archiving.
6812 Additional valid symbols may be available; check with the author of
6813 your package for details. The function should return non-nil if it
6816 See also `read-mail-command' concerning reading mail."
6817 :type
'(radio (function-item :tag
"Message package"
6820 (function-item :tag
"Mail package"
6822 sendmail-user-agent
)
6823 (function-item :tag
"Emacs interface to MH"
6826 (function-item :tag
"Message with full Gnus features"
6829 (function :tag
"Other"))
6830 :version
"23.2" ; sendmail->message
6833 (defcustom compose-mail-user-agent-warnings t
6834 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
6835 If the value of `mail-user-agent' is the default, and the user
6836 appears to have customizations applying to the old default,
6837 `compose-mail' issues a warning."
6842 (defun rfc822-goto-eoh ()
6843 "If the buffer starts with a mail header, move point to the header's end.
6844 Otherwise, moves to `point-min'.
6845 The end of the header is the start of the next line, if there is one,
6846 else the end of the last line. This function obeys RFC822."
6847 (goto-char (point-min))
6848 (when (re-search-forward
6849 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil
'move
)
6850 (goto-char (match-beginning 0))))
6852 ;; Used by Rmail (e.g., rmail-forward).
6853 (defvar mail-encode-mml nil
6854 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
6855 the outgoing message before sending it.")
6857 (defun compose-mail (&optional to subject other-headers continue
6858 switch-function yank-action send-actions
6860 "Start composing a mail message to send.
6861 This uses the user's chosen mail composition package
6862 as selected with the variable `mail-user-agent'.
6863 The optional arguments TO and SUBJECT specify recipients
6864 and the initial Subject field, respectively.
6866 OTHER-HEADERS is an alist specifying additional
6867 header fields. Elements look like (HEADER . VALUE) where both
6868 HEADER and VALUE are strings.
6870 CONTINUE, if non-nil, says to continue editing a message already
6871 being composed. Interactively, CONTINUE is the prefix argument.
6873 SWITCH-FUNCTION, if non-nil, is a function to use to
6874 switch to and display the buffer used for mail composition.
6876 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
6877 to insert the raw text of the message being replied to.
6878 It has the form (FUNCTION . ARGS). The user agent will apply
6879 FUNCTION to ARGS, to insert the raw text of the original message.
6880 \(The user agent will also run `mail-citation-hook', *after* the
6881 original text has been inserted in this way.)
6883 SEND-ACTIONS is a list of actions to call when the message is sent.
6884 Each action has the form (FUNCTION . ARGS).
6886 RETURN-ACTION, if non-nil, is an action for returning to the
6887 caller. It has the form (FUNCTION . ARGS). The function is
6888 called after the mail has been sent or put aside, and the mail
6891 (list nil nil nil current-prefix-arg
))
6893 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
6894 ;; from sendmail-user-agent to message-user-agent. Some users may
6895 ;; encounter incompatibilities. This hack tries to detect problems
6896 ;; and warn about them.
6897 (and compose-mail-user-agent-warnings
6898 (eq mail-user-agent
'message-user-agent
)
6900 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
6901 mail-yank-hooks mail-archive-file-name
6902 mail-default-reply-to mail-mailing-lists
6906 (push var warn-vars
)))
6908 (display-warning 'mail
6910 The default mail mode is now Message mode.
6911 You have the following Mail mode variable%s customized:
6912 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
6913 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
6914 (if (> (length warn-vars
) 1) "s" "")
6915 (mapconcat 'symbol-name
6918 (let ((function (get mail-user-agent
'composefunc
)))
6919 (funcall function to subject other-headers continue switch-function
6920 yank-action send-actions return-action
)))
6922 (defun compose-mail-other-window (&optional to subject other-headers continue
6923 yank-action send-actions
6925 "Like \\[compose-mail], but edit the outgoing message in another window."
6926 (interactive (list nil nil nil current-prefix-arg
))
6927 (compose-mail to subject other-headers continue
6928 'switch-to-buffer-other-window yank-action send-actions
6931 (defun compose-mail-other-frame (&optional to subject other-headers continue
6932 yank-action send-actions
6934 "Like \\[compose-mail], but edit the outgoing message in another frame."
6935 (interactive (list nil nil nil current-prefix-arg
))
6936 (compose-mail to subject other-headers continue
6937 'switch-to-buffer-other-frame yank-action send-actions
6941 (defvar set-variable-value-history nil
6942 "History of values entered with `set-variable'.
6944 Maximum length of the history list is determined by the value
6945 of `history-length', which see.")
6947 (defun set-variable (variable value
&optional make-local
)
6948 "Set VARIABLE to VALUE. VALUE is a Lisp object.
6949 VARIABLE should be a user option variable name, a Lisp variable
6950 meant to be customized by users. You should enter VALUE in Lisp syntax,
6951 so if you want VALUE to be a string, you must surround it with doublequotes.
6952 VALUE is used literally, not evaluated.
6954 If VARIABLE has a `variable-interactive' property, that is used as if
6955 it were the arg to `interactive' (which see) to interactively read VALUE.
6957 If VARIABLE has been defined with `defcustom', then the type information
6958 in the definition is used to check that VALUE is valid.
6960 With a prefix argument, set VARIABLE to VALUE buffer-locally."
6962 (let* ((default-var (variable-at-point))
6963 (var (if (custom-variable-p default-var
)
6964 (read-variable (format "Set variable (default %s): " default-var
)
6966 (read-variable "Set variable: ")))
6967 (minibuffer-help-form '(describe-variable var
))
6968 (prop (get var
'variable-interactive
))
6969 (obsolete (car (get var
'byte-obsolete-variable
)))
6970 (prompt (format "Set %s %s to value: " var
6971 (cond ((local-variable-p var
)
6973 ((or current-prefix-arg
6974 (local-variable-if-set-p var
))
6979 (message (concat "`%S' is obsolete; "
6980 (if (symbolp obsolete
) "use `%S' instead" "%s"))
6984 ;; Use VAR's `variable-interactive' property
6985 ;; as an interactive spec for prompting.
6986 (call-interactively `(lambda (arg)
6989 (read-from-minibuffer prompt nil
6990 read-expression-map t
6991 'set-variable-value-history
6992 (format "%S" (symbol-value var
)))))))
6993 (list var val current-prefix-arg
)))
6995 (and (custom-variable-p variable
)
6996 (not (get variable
'custom-type
))
6997 (custom-load-symbol variable
))
6998 (let ((type (get variable
'custom-type
)))
7000 ;; Match with custom type.
7002 (setq type
(widget-convert type
))
7003 (unless (widget-apply type
:match value
)
7004 (error "Value `%S' does not match type %S of %S"
7005 value
(car type
) variable
))))
7008 (make-local-variable variable
))
7010 (set variable value
)
7012 ;; Force a thorough redisplay for the case that the variable
7013 ;; has an effect on the display, like `tab-width' has.
7014 (force-mode-line-update))
7016 ;; Define the major mode for lists of completions.
7018 (defvar completion-list-mode-map
7019 (let ((map (make-sparse-keymap)))
7020 (define-key map
[mouse-2
] 'choose-completion
)
7021 (define-key map
[follow-link
] 'mouse-face
)
7022 (define-key map
[down-mouse-2
] nil
)
7023 (define-key map
"\C-m" 'choose-completion
)
7024 (define-key map
"\e\e\e" 'delete-completion-window
)
7025 (define-key map
[left] 'previous-completion)
7026 (define-key map [right] 'next-completion)
7027 (define-key map [?\t] 'next-completion)
7028 (define-key map [backtab] 'previous-completion)
7029 (define-key map "q" 'quit-window)
7030 (define-key map "z" 'kill-this-buffer)
7032 "Local map for completion list buffers.")
7034 ;; Completion mode is suitable only for specially formatted data.
7035 (put 'completion-list-mode 'mode-class 'special)
7037 (defvar completion-reference-buffer nil
7038 "Record the buffer that was current when the completion list was requested.
7039 This is a local variable in the completion list buffer.
7040 Initial value is nil to avoid some compiler warnings.")
7042 (defvar completion-no-auto-exit nil
7043 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7044 This also applies to other functions such as `choose-completion'.")
7046 (defvar completion-base-position nil
7047 "Position of the base of the text corresponding to the shown completions.
7048 This variable is used in the *Completions* buffers.
7049 Its value is a list of the form (START END) where START is the place
7050 where the completion should be inserted and END (if non-nil) is the end
7051 of the text to replace. If END is nil, point is used instead.")
7053 (defvar completion-list-insert-choice-function #'completion--replace
7054 "Function to use to insert the text chosen in *Completions*.
7055 Called with three arguments (BEG END TEXT), it should replace the text
7056 between BEG and END with TEXT. Expected to be set buffer-locally
7057 in the *Completions* buffer.")
7059 (defvar completion-base-size nil
7060 "Number of chars before point not involved in completion.
7061 This is a local variable in the completion list buffer.
7062 It refers to the chars in the minibuffer if completing in the
7063 minibuffer, or in `completion-reference-buffer' otherwise.
7064 Only characters in the field at point are included.
7066 If nil, Emacs determines which part of the tail end of the
7067 buffer's text is involved in completion by comparing the text
7069 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7071 (defun delete-completion-window ()
7072 "Delete the completion list window.
7073 Go to the window from which completion was requested."
7075 (let ((buf completion-reference-buffer))
7076 (if (one-window-p t)
7077 (if (window-dedicated-p) (delete-frame))
7078 (delete-window (selected-window))
7079 (if (get-buffer-window buf)
7080 (select-window (get-buffer-window buf))))))
7082 (defun previous-completion (n)
7083 "Move to the previous item in the completion list."
7085 (next-completion (- n)))
7087 (defun next-completion (n)
7088 "Move to the next item in the completion list.
7089 With prefix argument N, move N items (negative N means move backward)."
7091 (let ((beg (point-min)) (end (point-max)))
7092 (while (and (> n 0) (not (eobp)))
7093 ;; If in a completion, move to the end of it.
7094 (when (get-text-property (point) 'mouse-face)
7095 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7096 ;; Move to start of next one.
7097 (unless (get-text-property (point) 'mouse-face)
7098 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7100 (while (and (< n 0) (not (bobp)))
7101 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7102 ;; If in a completion, move to the start of it.
7103 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7104 (goto-char (previous-single-property-change
7105 (point) 'mouse-face nil beg)))
7106 ;; Move to end of the previous completion.
7107 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7108 (goto-char (previous-single-property-change
7109 (point) 'mouse-face nil beg)))
7110 ;; Move to the start of that one.
7111 (goto-char (previous-single-property-change
7112 (point) 'mouse-face nil beg))
7115 (defun choose-completion (&optional event)
7116 "Choose the completion at point.
7117 If EVENT, use EVENT's position to determine the starting position."
7118 (interactive (list last-nonmenu-event))
7119 ;; In case this is run via the mouse, give temporary modes such as
7120 ;; isearch a chance to turn off.
7121 (run-hooks 'mouse-leave-buffer-hook)
7122 (with-current-buffer (window-buffer (posn-window (event-start event)))
7123 (let ((buffer completion-reference-buffer)
7124 (base-size completion-base-size)
7125 (base-position completion-base-position)
7126 (insert-function completion-list-insert-choice-function)
7129 (goto-char (posn-point (event-start event)))
7132 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7133 (setq end (point) beg (1+ (point))))
7135 (get-text-property (1- (point)) 'mouse-face))
7136 (setq end (1- (point)) beg (point)))
7137 (t (error "No completion here")))
7138 (setq beg (previous-single-property-change beg 'mouse-face))
7139 (setq end (or (next-single-property-change end 'mouse-face)
7141 (buffer-substring-no-properties beg end)))))
7143 (unless (buffer-live-p buffer)
7144 (error "Destination buffer is dead"))
7145 (quit-window nil (posn-window (event-start event)))
7147 (with-current-buffer buffer
7148 (choose-completion-string
7152 ;; Someone's using old completion code that doesn't know
7153 ;; about base-position yet.
7154 (list (+ base-size (field-beginning))))
7155 ;; If all else fails, just guess.
7156 (list (choose-completion-guess-base-position choice)))
7157 insert-function)))))
7159 ;; Delete the longest partial match for STRING
7160 ;; that can be found before POINT.
7161 (defun choose-completion-guess-base-position (string)
7163 (let ((opoint (point))
7165 ;; Try moving back by the length of the string.
7166 (goto-char (max (- (point) (length string))
7167 (minibuffer-prompt-end)))
7168 ;; See how far back we were actually able to move. That is the
7169 ;; upper bound on how much we can match and delete.
7170 (setq len (- opoint (point)))
7171 (if completion-ignore-case
7172 (setq string (downcase string)))
7173 (while (and (> len 0)
7174 (let ((tail (buffer-substring (point) opoint)))
7175 (if completion-ignore-case
7176 (setq tail (downcase tail)))
7177 (not (string= tail (substring string 0 len)))))
7182 (defun choose-completion-delete-max-match (string)
7183 (declare (obsolete choose-completion-guess-base-position "23.2"))
7184 (delete-region (choose-completion-guess-base-position string) (point)))
7186 (defvar choose-completion-string-functions nil
7187 "Functions that may override the normal insertion of a completion choice.
7188 These functions are called in order with three arguments:
7189 CHOICE - the string to insert in the buffer,
7190 BUFFER - the buffer in which the choice should be inserted,
7191 BASE-POSITION - where to insert the completion.
7193 If a function in the list returns non-nil, that function is supposed
7194 to have inserted the CHOICE in the BUFFER, and possibly exited
7195 the minibuffer; no further functions will be called.
7197 If all functions in the list return nil, that means to use
7198 the default method of inserting the completion in BUFFER.")
7200 (defun choose-completion-string (choice &optional
7201 buffer base-position insert-function)
7202 "Switch to BUFFER and insert the completion choice CHOICE.
7203 BASE-POSITION says where to insert the completion.
7204 INSERT-FUNCTION says how to insert the completion and falls
7205 back on `completion-list-insert-choice-function' when nil."
7207 ;; If BUFFER is the minibuffer, exit the minibuffer
7208 ;; unless it is reading a file name and CHOICE is a directory,
7209 ;; or completion-no-auto-exit is non-nil.
7211 ;; Some older code may call us passing `base-size' instead of
7212 ;; `base-position'. It's difficult to make any use of `base-size',
7213 ;; so we just ignore it.
7214 (unless (consp base-position)
7215 (message "Obsolete `base-size' passed to choose-completion-string")
7216 (setq base-position nil))
7218 (let* ((buffer (or buffer completion-reference-buffer))
7219 (mini-p (minibufferp buffer)))
7220 ;; If BUFFER is a minibuffer, barf unless it's the currently
7221 ;; active minibuffer.
7223 (not (and (active-minibuffer-window)
7225 (window-buffer (active-minibuffer-window))))))
7226 (error "Minibuffer is not active for completion")
7227 ;; Set buffer so buffer-local choose-completion-string-functions works.
7229 (unless (run-hook-with-args-until-success
7230 'choose-completion-string-functions
7231 ;; The fourth arg used to be `mini-p' but was useless
7232 ;; (since minibufferp can be used on the `buffer' arg)
7233 ;; and indeed unused. The last used to be `base-size', so we
7234 ;; keep it to try and avoid breaking old code.
7235 choice buffer base-position nil)
7236 ;; This remove-text-properties should be unnecessary since `choice'
7237 ;; comes from buffer-substring-no-properties.
7238 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7239 ;; Insert the completion into the buffer where it was requested.
7240 (funcall (or insert-function completion-list-insert-choice-function)
7241 (or (car base-position) (point))
7242 (or (cadr base-position) (point))
7244 ;; Update point in the window that BUFFER is showing in.
7245 (let ((window (get-buffer-window buffer t)))
7246 (set-window-point window (point)))
7247 ;; If completing for the minibuffer, exit it with this choice.
7248 (and (not completion-no-auto-exit)
7249 (minibufferp buffer)
7250 minibuffer-completion-table
7251 ;; If this is reading a file name, and the file name chosen
7252 ;; is a directory, don't exit the minibuffer.
7253 (let* ((result (buffer-substring (field-beginning) (point)))
7255 (completion-boundaries result minibuffer-completion-table
7256 minibuffer-completion-predicate
7258 (if (eq (car bounds) (length result))
7259 ;; The completion chosen leads to a new set of completions
7260 ;; (e.g. it's a directory): don't exit the minibuffer yet.
7261 (let ((mini (active-minibuffer-window)))
7262 (select-window mini)
7263 (when minibuffer-auto-raise
7264 (raise-frame (window-frame mini))))
7265 (exit-minibuffer))))))))
7267 (define-derived-mode completion-list-mode nil "Completion List"
7268 "Major mode for buffers showing lists of possible completions.
7269 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
7270 to select the completion near point.
7271 Or click to select one with the mouse.
7273 \\{completion-list-mode-map}"
7274 (set (make-local-variable 'completion-base-size) nil))
7276 (defun completion-list-mode-finish ()
7277 "Finish setup of the completions buffer.
7278 Called from `temp-buffer-show-hook'."
7279 (when (eq major-mode 'completion-list-mode)
7280 (setq buffer-read-only t)))
7282 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
7285 ;; Variables and faces used in `completion-setup-function'.
7287 (defcustom completion-show-help t
7288 "Non-nil means show help message in *Completions* buffer."
7293 ;; This function goes in completion-setup-hook, so that it is called
7294 ;; after the text of the completion list buffer is written.
7295 (defun completion-setup-function ()
7296 (let* ((mainbuf (current-buffer))
7298 ;; FIXME: This is a bad hack. We try to set the default-directory
7299 ;; in the *Completions* buffer so that the relative file names
7300 ;; displayed there can be treated as valid file names, independently
7301 ;; from the completion context. But this suffers from many problems:
7302 ;; - It's not clear when the completions are file names. With some
7303 ;; completion tables (e.g. bzr revision specs), the listed
7304 ;; completions can mix file names and other things.
7305 ;; - It doesn't pay attention to possible quoting.
7306 ;; - With fancy completion styles, the code below will not always
7307 ;; find the right base directory.
7308 (if minibuffer-completing-file-name
7309 (file-name-as-directory
7311 (buffer-substring (minibuffer-prompt-end)
7312 (- (point) (or completion-base-size 0))))))))
7313 (with-current-buffer standard-output
7314 (let ((base-size completion-base-size) ;Read before killing localvars.
7315 (base-position completion-base-position)
7316 (insert-fun completion-list-insert-choice-function))
7317 (completion-list-mode)
7318 (set (make-local-variable 'completion-base-size) base-size)
7319 (set (make-local-variable 'completion-base-position) base-position)
7320 (set (make-local-variable 'completion-list-insert-choice-function)
7322 (set (make-local-variable 'completion-reference-buffer) mainbuf)
7323 (if base-dir (setq default-directory base-dir))
7324 ;; Maybe insert help string.
7325 (when completion-show-help
7326 (goto-char (point-min))
7327 (if (display-mouse-p)
7328 (insert (substitute-command-keys
7329 "Click on a completion to select it.\n")))
7330 (insert (substitute-command-keys
7331 "In this buffer, type \\[choose-completion] to \
7332 select the completion near point.\n\n"))))))
7334 (add-hook 'completion-setup-hook 'completion-setup-function)
7336 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
7337 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
7339 (defun switch-to-completions ()
7340 "Select the completion list window."
7342 (let ((window (or (get-buffer-window "*Completions*" 0)
7343 ;; Make sure we have a completions window.
7344 (progn (minibuffer-completion-help)
7345 (get-buffer-window "*Completions*" 0)))))
7347 (select-window window)
7348 ;; In the new buffer, go to the first completion.
7349 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
7351 (next-completion 1)))))
7353 ;;; Support keyboard commands to turn on various modifiers.
7355 ;; These functions -- which are not commands -- each add one modifier
7356 ;; to the following event.
7358 (defun event-apply-alt-modifier (_ignore-prompt)
7359 "\\<function-key-map>Add the Alt modifier to the following event.
7360 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
7361 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
7362 (defun event-apply-super-modifier (_ignore-prompt)
7363 "\\<function-key-map>Add the Super modifier to the following event.
7364 For example, type \\[event-apply-super-modifier] & to enter Super-&."
7365 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
7366 (defun event-apply-hyper-modifier (_ignore-prompt)
7367 "\\<function-key-map>Add the Hyper modifier to the following event.
7368 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
7369 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
7370 (defun event-apply-shift-modifier (_ignore-prompt)
7371 "\\<function-key-map>Add the Shift modifier to the following event.
7372 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
7373 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
7374 (defun event-apply-control-modifier (_ignore-prompt)
7375 "\\<function-key-map>Add the Ctrl modifier to the following event.
7376 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
7377 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
7378 (defun event-apply-meta-modifier (_ignore-prompt)
7379 "\\<function-key-map>Add the Meta modifier to the following event.
7380 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
7381 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
7383 (defun event-apply-modifier (event symbol lshiftby prefix)
7384 "Apply a modifier flag to event EVENT.
7385 SYMBOL is the name of this modifier, as a symbol.
7386 LSHIFTBY is the numeric value of this modifier, in keyboard events.
7387 PREFIX is the string that represents this modifier in an event type symbol."
7389 (cond ((eq symbol 'control)
7390 (if (and (<= (downcase event) ?z)
7391 (>= (downcase event) ?a))
7392 (- (downcase event) ?a -1)
7393 (if (and (<= (downcase event) ?Z)
7394 (>= (downcase event) ?A))
7395 (- (downcase event) ?A -1)
7396 (logior (lsh 1 lshiftby) event))))
7398 (if (and (<= (downcase event) ?z)
7399 (>= (downcase event) ?a))
7401 (logior (lsh 1 lshiftby) event)))
7403 (logior (lsh 1 lshiftby) event)))
7404 (if (memq symbol (event-modifiers event))
7406 (let ((event-type (if (symbolp event) event (car event))))
7407 (setq event-type (intern (concat prefix (symbol-name event-type))))
7410 (cons event-type (cdr event)))))))
7412 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
7413 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
7414 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
7415 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
7416 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
7417 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
7419 ;;;; Keypad support.
7421 ;; Make the keypad keys act like ordinary typing keys. If people add
7422 ;; bindings for the function key symbols, then those bindings will
7423 ;; override these, so this shouldn't interfere with any existing
7426 ;; Also tell read-char how to handle these keys.
7428 (lambda (keypad-normal)
7429 (let ((keypad (nth 0 keypad-normal))
7430 (normal (nth 1 keypad-normal)))
7431 (put keypad 'ascii-character normal)
7432 (define-key function-key-map (vector keypad) (vector normal))))
7433 ;; See also kp-keys bound in bindings.el.
7439 ;; Do the same for various keys that are represented as symbols under
7440 ;; GUIs but naturally correspond to characters.
7451 ;;;; forking a twin copy of a buffer.
7454 (defvar clone-buffer-hook nil
7455 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
7457 (defvar clone-indirect-buffer-hook nil
7458 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
7460 (defun clone-process (process &optional newname)
7461 "Create a twin copy of PROCESS.
7462 If NEWNAME is nil, it defaults to PROCESS' name;
7463 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
7464 If PROCESS is associated with a buffer, the new process will be associated
7465 with the current buffer instead.
7466 Returns nil if PROCESS has already terminated."
7467 (setq newname (or newname (process-name process)))
7468 (if (string-match "<[0-9]+>\\'" newname)
7469 (setq newname (substring newname 0 (match-beginning 0))))
7470 (when (memq (process-status process) '(run stop open))
7471 (let* ((process-connection-type (process-tty-name process))
7473 (if (memq (process-status process) '(open))
7474 (let ((args (process-contact process t)))
7475 (setq args (plist-put args :name newname))
7476 (setq args (plist-put args :buffer
7477 (if (process-buffer process)
7479 (apply 'make-network-process args))
7480 (apply 'start-process newname
7481 (if (process-buffer process) (current-buffer))
7482 (process-command process)))))
7483 (set-process-query-on-exit-flag
7484 new-process (process-query-on-exit-flag process))
7485 (set-process-inherit-coding-system-flag
7486 new-process (process-inherit-coding-system-flag process))
7487 (set-process-filter new-process (process-filter process))
7488 (set-process-sentinel new-process (process-sentinel process))
7489 (set-process-plist new-process (copy-sequence (process-plist process)))
7492 ;; things to maybe add (currently partly covered by `funcall mode'):
7495 (defun clone-buffer (&optional newname display-flag)
7496 "Create and return a twin copy of the current buffer.
7497 Unlike an indirect buffer, the new buffer can be edited
7498 independently of the old one (if it is not read-only).
7499 NEWNAME is the name of the new buffer. It may be modified by
7500 adding or incrementing <N> at the end as necessary to create a
7501 unique buffer name. If nil, it defaults to the name of the
7502 current buffer, with the proper suffix. If DISPLAY-FLAG is
7503 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
7504 clone a file-visiting buffer, or a buffer whose major mode symbol
7505 has a non-nil `no-clone' property, results in an error.
7507 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
7508 current buffer with appropriate suffix. However, if a prefix
7509 argument is given, then the command prompts for NEWNAME in the
7512 This runs the normal hook `clone-buffer-hook' in the new buffer
7513 after it has been set up properly in other respects."
7516 (if buffer-file-name
7517 (error "Cannot clone a file-visiting buffer"))
7518 (if (get major-mode 'no-clone)
7519 (error "Cannot clone a buffer in %s mode" mode-name))
7520 (list (if current-prefix-arg
7521 (read-buffer "Name of new cloned buffer: " (current-buffer)))
7523 (if buffer-file-name
7524 (error "Cannot clone a file-visiting buffer"))
7525 (if (get major-mode 'no-clone)
7526 (error "Cannot clone a buffer in %s mode" mode-name))
7527 (setq newname (or newname (buffer-name)))
7528 (if (string-match "<[0-9]+>\\'" newname)
7529 (setq newname (substring newname 0 (match-beginning 0))))
7530 (let ((buf (current-buffer))
7534 (mk (if mark-active (mark t)))
7535 (modified (buffer-modified-p))
7537 (lvars (buffer-local-variables))
7538 (process (get-buffer-process (current-buffer)))
7539 (new (generate-new-buffer (or newname (buffer-name)))))
7542 (with-current-buffer new
7543 (insert-buffer-substring buf)))
7544 (with-current-buffer new
7545 (narrow-to-region ptmin ptmax)
7547 (if mk (set-mark mk))
7548 (set-buffer-modified-p modified)
7550 ;; Clone the old buffer's process, if any.
7551 (when process (clone-process process))
7553 ;; Now set up the major mode.
7556 ;; Set up other local variables.
7558 (condition-case () ;in case var is read-only
7561 (set (make-local-variable (car v)) (cdr v)))
7565 ;; Run any hooks (typically set up by the major mode
7566 ;; for cloning to work properly).
7567 (run-hooks 'clone-buffer-hook))
7569 ;; Presumably the current buffer is shown in the selected frame, so
7570 ;; we want to display the clone elsewhere.
7571 (let ((same-window-regexps nil)
7572 (same-window-buffer-names))
7573 (pop-to-buffer new)))
7577 (defun clone-indirect-buffer (newname display-flag &optional norecord)
7578 "Create an indirect buffer that is a twin copy of the current buffer.
7580 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
7581 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
7582 or if not called with a prefix arg, NEWNAME defaults to the current
7583 buffer's name. The name is modified by adding a `<N>' suffix to it
7584 or by incrementing the N in an existing suffix. Trying to clone a
7585 buffer whose major mode symbol has a non-nil `no-clone-indirect'
7586 property results in an error.
7588 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7589 This is always done when called interactively.
7591 Optional third arg NORECORD non-nil means do not put this buffer at the
7592 front of the list of recently selected ones.
7594 Returns the newly created indirect buffer."
7597 (if (get major-mode 'no-clone-indirect)
7598 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7599 (list (if current-prefix-arg
7600 (read-buffer "Name of indirect buffer: " (current-buffer)))
7602 (if (get major-mode 'no-clone-indirect)
7603 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7604 (setq newname (or newname (buffer-name)))
7605 (if (string-match "<[0-9]+>\\'" newname)
7606 (setq newname (substring newname 0 (match-beginning 0))))
7607 (let* ((name (generate-new-buffer-name newname))
7608 (buffer (make-indirect-buffer (current-buffer) name t)))
7609 (with-current-buffer buffer
7610 (run-hooks 'clone-indirect-buffer-hook))
7612 (pop-to-buffer buffer norecord))
7616 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
7617 "Like `clone-indirect-buffer' but display in another window."
7620 (if (get major-mode 'no-clone-indirect)
7621 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7622 (list (if current-prefix-arg
7623 (read-buffer "Name of indirect buffer: " (current-buffer)))
7625 (let ((pop-up-windows t))
7626 (clone-indirect-buffer newname display-flag norecord)))
7629 ;;; Handling of Backspace and Delete keys.
7631 (defcustom normal-erase-is-backspace 'maybe
7632 "Set the default behavior of the Delete and Backspace keys.
7634 If set to t, Delete key deletes forward and Backspace key deletes
7637 If set to nil, both Delete and Backspace keys delete backward.
7639 If set to 'maybe (which is the default), Emacs automatically
7640 selects a behavior. On window systems, the behavior depends on
7641 the keyboard used. If the keyboard has both a Backspace key and
7642 a Delete key, and both are mapped to their usual meanings, the
7643 option's default value is set to t, so that Backspace can be used
7644 to delete backward, and Delete can be used to delete forward.
7646 If not running under a window system, customizing this option
7647 accomplishes a similar effect by mapping C-h, which is usually
7648 generated by the Backspace key, to DEL, and by mapping DEL to C-d
7649 via `keyboard-translate'. The former functionality of C-h is
7650 available on the F1 key. You should probably not use this
7651 setting if you don't have both Backspace, Delete and F1 keys.
7653 Setting this variable with setq doesn't take effect. Programmatically,
7654 call `normal-erase-is-backspace-mode' (which see) instead."
7655 :type '(choice (const :tag "Off" nil)
7656 (const :tag "Maybe" maybe)
7657 (other :tag "On" t))
7658 :group 'editing-basics
7660 :set (lambda (symbol value)
7661 ;; The fboundp is because of a problem with :set when
7662 ;; dumping Emacs. It doesn't really matter.
7663 (if (fboundp 'normal-erase-is-backspace-mode)
7664 (normal-erase-is-backspace-mode (or value 0))
7665 (set-default symbol value))))
7667 (defun normal-erase-is-backspace-setup-frame (&optional frame)
7668 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
7669 (unless frame (setq frame (selected-frame)))
7670 (with-selected-frame frame
7671 (unless (terminal-parameter nil 'normal-erase-is-backspace)
7672 (normal-erase-is-backspace-mode
7673 (if (if (eq normal-erase-is-backspace 'maybe)
7674 (and (not noninteractive)
7675 (or (memq system-type '(ms-dos windows-nt))
7676 (memq window-system '(w32 ns))
7677 (and (memq window-system '(x))
7678 (fboundp 'x-backspace-delete-keys-p)
7679 (x-backspace-delete-keys-p))
7680 ;; If the terminal Emacs is running on has erase char
7681 ;; set to ^H, use the Backspace key for deleting
7682 ;; backward, and the Delete key for deleting forward.
7683 (and (null window-system)
7684 (eq tty-erase-char ?\^H))))
7685 normal-erase-is-backspace)
7688 (define-minor-mode normal-erase-is-backspace-mode
7689 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
7690 With a prefix argument ARG, enable this feature if ARG is
7691 positive, and disable it otherwise. If called from Lisp, enable
7692 the mode if ARG is omitted or nil.
7694 On window systems, when this mode is on, Delete is mapped to C-d
7695 and Backspace is mapped to DEL; when this mode is off, both
7696 Delete and Backspace are mapped to DEL. (The remapping goes via
7697 `local-function-key-map', so binding Delete or Backspace in the
7698 global or local keymap will override that.)
7700 In addition, on window systems, the bindings of C-Delete, M-Delete,
7701 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
7702 the global keymap in accordance with the functionality of Delete and
7703 Backspace. For example, if Delete is remapped to C-d, which deletes
7704 forward, C-Delete is bound to `kill-word', but if Delete is remapped
7705 to DEL, which deletes backward, C-Delete is bound to
7706 `backward-kill-word'.
7708 If not running on a window system, a similar effect is accomplished by
7709 remapping C-h (normally produced by the Backspace key) and DEL via
7710 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
7711 to C-d; if it's off, the keys are not remapped.
7713 When not running on a window system, and this mode is turned on, the
7714 former functionality of C-h is available on the F1 key. You should
7715 probably not turn on this mode on a text-only terminal if you don't
7716 have both Backspace, Delete and F1 keys.
7718 See also `normal-erase-is-backspace'."
7719 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
7721 (setf (terminal-parameter nil 'normal-erase-is-backspace)
7723 (let ((enabled (eq 1 (terminal-parameter
7724 nil 'normal-erase-is-backspace))))
7726 (cond ((or (memq window-system '(x w32 ns pc))
7727 (memq system-type '(ms-dos windows-nt)))
7729 `(([M-delete] [M-backspace])
7730 ([C-M-delete] [C-M-backspace])
7731 ([?\e C-delete] [?\e C-backspace]))))
7735 (define-key local-function-key-map [delete] [deletechar])
7736 (define-key local-function-key-map [kp-delete] [deletechar])
7737 (define-key local-function-key-map [backspace] [?\C-?])
7738 (dolist (b bindings)
7739 ;; Not sure if input-decode-map is really right, but
7740 ;; keyboard-translate-table (used below) only works
7741 ;; for integer events, and key-translation-table is
7742 ;; global (like the global-map, used earlier).
7743 (define-key input-decode-map (car b) nil)
7744 (define-key input-decode-map (cadr b) nil)))
7745 (define-key local-function-key-map [delete] [?\C-?])
7746 (define-key local-function-key-map [kp-delete] [?\C-?])
7747 (define-key local-function-key-map [backspace] [?\C-?])
7748 (dolist (b bindings)
7749 (define-key input-decode-map (car b) (cadr b))
7750 (define-key input-decode-map (cadr b) (car b))))))
7754 (keyboard-translate ?\C-h ?\C-?)
7755 (keyboard-translate ?\C-? ?\C-d))
7756 (keyboard-translate ?\C-h ?\C-h)
7757 (keyboard-translate ?\C-? ?\C-?))))
7759 (if (called-interactively-p 'interactive)
7760 (message "Delete key deletes %s"
7761 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
7762 "forward" "backward")))))
7764 (defvar vis-mode-saved-buffer-invisibility-spec nil
7765 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
7767 (define-minor-mode read-only-mode
7768 "Change whether the current buffer is read-only.
7769 With prefix argument ARG, make the buffer read-only if ARG is
7770 positive, otherwise make it writable. If buffer is read-only
7771 and `view-read-only' is non-nil, enter view mode.
7773 Do not call this from a Lisp program unless you really intend to
7774 do the same thing as the \\[read-only-mode] command, including
7775 possibly enabling or disabling View mode. Also, note that this
7776 command works by setting the variable `buffer-read-only', which
7777 does not affect read-only regions caused by text properties. To
7778 ignore read-only status in a Lisp program (whether due to text
7779 properties or buffer state), bind `inhibit-read-only' temporarily
7780 to a non-nil value."
7781 :variable buffer-read-only
7783 ((and (not buffer-read-only) view-mode)
7784 (View-exit-and-edit)
7785 (make-local-variable 'view-read-only)
7786 (setq view-read-only t)) ; Must leave view mode.
7787 ((and buffer-read-only view-read-only
7788 ;; If view-mode is already active, `view-mode-enter' is a nop.
7790 (not (eq (get major-mode 'mode-class) 'special)))
7791 (view-mode-enter))))
7793 (define-minor-mode visible-mode
7794 "Toggle making all invisible text temporarily visible (Visible mode).
7795 With a prefix argument ARG, enable Visible mode if ARG is
7796 positive, and disable it otherwise. If called from Lisp, enable
7797 the mode if ARG is omitted or nil.
7799 This mode works by saving the value of `buffer-invisibility-spec'
7800 and setting it to nil."
7802 :group 'editing-basics
7803 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
7804 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
7805 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
7807 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
7808 buffer-invisibility-spec)
7809 (setq buffer-invisibility-spec nil)))
7811 (defvar messages-buffer-mode-map
7812 (let ((map (make-sparse-keymap)))
7813 (set-keymap-parent map special-mode-map)
7814 (define-key map "g" nil) ; nothing to revert
7817 (define-derived-mode messages-buffer-mode special-mode "Messages"
7818 "Major mode used in the \"*Messages*\" buffer.")
7820 (defun messages-buffer ()
7821 "Return the \"*Messages*\" buffer.
7822 If it does not exist, create and it switch it to `messages-buffer-mode'."
7823 (or (get-buffer "*Messages*")
7824 (with-current-buffer (get-buffer-create "*Messages*")
7825 (messages-buffer-mode)
7829 ;; Minibuffer prompt stuff.
7831 ;;(defun minibuffer-prompt-modification (start end)
7832 ;; (error "You cannot modify the prompt"))
7835 ;;(defun minibuffer-prompt-insertion (start end)
7836 ;; (let ((inhibit-modification-hooks t))
7837 ;; (delete-region start end)
7838 ;; ;; Discard undo information for the text insertion itself
7839 ;; ;; and for the text deletion.above.
7840 ;; (when (consp buffer-undo-list)
7841 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
7842 ;; (message "You cannot modify the prompt")))
7845 ;;(setq minibuffer-prompt-properties
7846 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
7847 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
7850 ;;;; Problematic external packages.
7852 ;; rms says this should be done by specifying symbols that define
7853 ;; versions together with bad values. This is therefore not as
7854 ;; flexible as it could be. See the thread:
7855 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
7856 (defconst bad-packages-alist
7857 ;; Not sure exactly which semantic versions have problems.
7858 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
7859 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
7860 "The version of `semantic' loaded does not work in Emacs 22.
7861 It can cause constant high CPU load.
7862 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
7863 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
7864 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
7865 ;; provided the `CUA-mode' feature. Since this is no longer true,
7866 ;; we can warn the user if the `CUA-mode' feature is ever provided.
7868 "CUA-mode is now part of the standard GNU Emacs distribution,
7869 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
7871 You have loaded an older version of CUA-mode which does not work
7872 correctly with this version of Emacs. You should remove the old
7873 version and use the one distributed with Emacs."))
7874 "Alist of packages known to cause problems in this version of Emacs.
7875 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
7876 PACKAGE is either a regular expression to match file names, or a
7877 symbol (a feature name), like for `with-eval-after-load'.
7878 SYMBOL is either the name of a string variable, or `t'. Upon
7879 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
7880 warning using STRING as the message.")
7882 (defun bad-package-check (package)
7883 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
7885 (let* ((list (assoc package bad-packages-alist))
7886 (symbol (nth 1 list)))
7890 (and (stringp (setq symbol (eval symbol)))
7891 (string-match-p (nth 2 list) symbol)))
7892 (display-warning package (nth 3 list) :warning)))
7895 (dolist (elem bad-packages-alist)
7896 (let ((pkg (car elem)))
7897 (with-eval-after-load pkg
7898 (bad-package-check pkg))))
7901 ;;; Generic dispatcher commands
7903 ;; Macro `define-alternatives' is used to create generic commands.
7904 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
7905 ;; that can have different alternative implementations where choosing
7906 ;; among them is exclusively a matter of user preference.
7908 ;; (define-alternatives COMMAND) creates a new interactive command
7909 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
7910 ;; Typically, the user will not need to customize this variable; packages
7911 ;; wanting to add alternative implementations should use
7913 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
7915 (defmacro define-alternatives (command &rest customizations)
7916 "Define the new command `COMMAND'.
7918 The argument `COMMAND' should be a symbol.
7920 Running `M-x COMMAND RET' for the first time prompts for which
7921 alternative to use and records the selected command as a custom
7924 Running `C-u M-x COMMAND RET' prompts again for an alternative
7925 and overwrites the previous choice.
7927 The variable `COMMAND-alternatives' contains an alist with
7928 alternative implementations of COMMAND. `define-alternatives'
7929 does not have any effect until this variable is set.
7931 CUSTOMIZATIONS, if non-nil, should be composed of alternating
7932 `defcustom' keywords and values to add to the declaration of
7933 `COMMAND-alternatives' (typically :group and :version)."
7934 (let* ((command-name (symbol-name command))
7935 (varalt-name (concat command-name "-alternatives"))
7936 (varalt-sym (intern varalt-name))
7937 (varimp-sym (intern (concat command-name "--implementation"))))
7940 (defcustom ,varalt-sym nil
7941 ,(format "Alist of alternative implementations for the `%s' command.
7943 Each entry must be a pair (ALTNAME . ALTFUN), where:
7944 ALTNAME - The name shown at user to describe the alternative implementation.
7945 ALTFUN - The function called to implement this alternative."
7947 :type '(alist :key-type string :value-type function)
7950 (put ',varalt-sym 'definition-name ',command)
7951 (defvar ,varimp-sym nil "Internal use only.")
7953 (defun ,command (&optional arg)
7954 ,(format "Run generic command `%s'.
7955 If used for the first time, or with interactive ARG, ask the user which
7956 implementation to use for `%s'. The variable `%s'
7957 contains the list of implementations currently supported for this command."
7958 command-name command-name varalt-name)
7960 (when (or arg (null ,varimp-sym))
7961 (let ((val (completing-read
7962 ,(format "Select implementation for command `%s': "
7964 ,varalt-sym nil t)))
7965 (unless (string-equal val "")
7966 (when (null ,varimp-sym)
7968 "Use `C-u M-x %s RET' to select another implementation"
7971 (customize-save-variable ',varimp-sym
7972 (cdr (assoc-string val ,varalt-sym))))))
7974 (call-interactively ,varimp-sym)
7975 (message ,(format "No implementation selected for command `%s'"
7982 ;;; simple.el ends here