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