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