Improve documentation of 'expand-abbrev' and wrapper hooks
[emacs.git] / lisp / simple.el
blobc7d3b2e6b0b6f6417f4d011278398bd575c35dd7
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 "Return non-nil if BUFFER is a `next-error' capable buffer.
149 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
150 return nil.
152 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
153 BUFFER would not normally qualify. If it returns non-nil, BUFFER
154 is considered `next-error' capable, anyway, and the function
155 returns non-nil.
157 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
158 buffer would normally qualify. If it returns nil, BUFFER is
159 rejected, and the function returns nil."
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 "If VALUE in an integer, return a specially formatted string.
1422 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1423 If VALUE is not an integer, nil is returned.
1424 This function is used by functions like `prin1' that display the
1425 result of expression evaluation."
1426 (if (and (integerp value)
1427 (or (eq standard-output t)
1428 (zerop (prefix-numeric-value current-prefix-arg))))
1429 (let ((char-string
1430 (if (and (characterp value)
1431 (char-displayable-p value))
1432 (prin1-char value))))
1433 (if char-string
1434 (format " (#o%o, #x%x, %s)" value value char-string)
1435 (format " (#o%o, #x%x)" value value)))))
1437 (defvar eval-expression-minibuffer-setup-hook nil
1438 "Hook run by `eval-expression' when entering the minibuffer.")
1440 (defun read--expression (prompt &optional initial-contents)
1441 (let ((minibuffer-completing-symbol t))
1442 (minibuffer-with-setup-hook
1443 (lambda ()
1444 ;; FIXME: call emacs-lisp-mode?
1445 (add-function :before-until (local 'eldoc-documentation-function)
1446 #'elisp-eldoc-documentation-function)
1447 (add-hook 'completion-at-point-functions
1448 #'elisp-completion-at-point nil t)
1449 (run-hooks 'eval-expression-minibuffer-setup-hook))
1450 (read-from-minibuffer prompt initial-contents
1451 read-expression-map t
1452 'read-expression-history))))
1454 ;; We define this, rather than making `eval' interactive,
1455 ;; for the sake of completion of names like eval-region, eval-buffer.
1456 (defun eval-expression (exp &optional insert-value)
1457 "Evaluate EXP and print value in the echo area.
1458 When called interactively, read an Emacs Lisp expression and evaluate it.
1459 Value is also consed on to front of the variable `values'.
1460 If the resulting value is an integer, it will be printed in
1461 several additional formats (octal, hexadecimal, and character).
1462 Optional argument INSERT-VALUE non-nil (interactively, with
1463 prefix argument) means insert the result into the current buffer
1464 instead of printing it in the echo area.
1466 Normally, this function truncates long output according to the value
1467 of the variables `eval-expression-print-length' and
1468 `eval-expression-print-level'. With a prefix argument of zero,
1469 however, there is no such truncation.
1471 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1472 minibuffer.
1474 If `eval-expression-debug-on-error' is non-nil, which is the default,
1475 this command arranges for all errors to enter the debugger."
1476 (interactive
1477 (list (read--expression "Eval: ")
1478 current-prefix-arg))
1480 (if (null eval-expression-debug-on-error)
1481 (push (eval exp lexical-binding) values)
1482 (let ((old-value (make-symbol "t")) new-value)
1483 ;; Bind debug-on-error to something unique so that we can
1484 ;; detect when evalled code changes it.
1485 (let ((debug-on-error old-value))
1486 (push (eval (macroexpand-all exp) lexical-binding) values)
1487 (setq new-value debug-on-error))
1488 ;; If evalled code has changed the value of debug-on-error,
1489 ;; propagate that change to the global binding.
1490 (unless (eq old-value new-value)
1491 (setq debug-on-error new-value))))
1493 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
1494 eval-expression-print-length))
1495 (print-level (and (not (zerop (prefix-numeric-value insert-value)))
1496 eval-expression-print-level))
1497 (deactivate-mark))
1498 (if insert-value
1499 (with-no-warnings
1500 (let ((standard-output (current-buffer)))
1501 (prog1
1502 (prin1 (car values))
1503 (when (zerop (prefix-numeric-value insert-value))
1504 (let ((str (eval-expression-print-format (car values))))
1505 (if str (princ str)))))))
1506 (prog1
1507 (prin1 (car values) t)
1508 (let ((str (eval-expression-print-format (car values))))
1509 (if str (princ str t)))))))
1511 (defun edit-and-eval-command (prompt command)
1512 "Prompting with PROMPT, let user edit COMMAND and eval result.
1513 COMMAND is a Lisp expression. Let user edit that expression in
1514 the minibuffer, then read and evaluate the result."
1515 (let ((command
1516 (let ((print-level nil)
1517 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1518 (unwind-protect
1519 (read-from-minibuffer prompt
1520 (prin1-to-string command)
1521 read-expression-map t
1522 'command-history)
1523 ;; If command was added to command-history as a string,
1524 ;; get rid of that. We want only evaluable expressions there.
1525 (if (stringp (car command-history))
1526 (setq command-history (cdr command-history)))))))
1528 ;; If command to be redone does not match front of history,
1529 ;; add it to the history.
1530 (or (equal command (car command-history))
1531 (setq command-history (cons command command-history)))
1532 (eval command)))
1534 (defun repeat-complex-command (arg)
1535 "Edit and re-evaluate last complex command, or ARGth from last.
1536 A complex command is one which used the minibuffer.
1537 The command is placed in the minibuffer as a Lisp form for editing.
1538 The result is executed, repeating the command as changed.
1539 If the command has been changed or is not the most recent previous
1540 command it is added to the front of the command history.
1541 You can use the minibuffer history commands \
1542 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1543 to get different commands to edit and resubmit."
1544 (interactive "p")
1545 (let ((elt (nth (1- arg) command-history))
1546 newcmd)
1547 (if elt
1548 (progn
1549 (setq newcmd
1550 (let ((print-level nil)
1551 (minibuffer-history-position arg)
1552 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1553 (unwind-protect
1554 (read-from-minibuffer
1555 "Redo: " (prin1-to-string elt) read-expression-map t
1556 (cons 'command-history arg))
1558 ;; If command was added to command-history as a
1559 ;; string, get rid of that. We want only
1560 ;; evaluable expressions there.
1561 (if (stringp (car command-history))
1562 (setq command-history (cdr command-history))))))
1564 ;; If command to be redone does not match front of history,
1565 ;; add it to the history.
1566 (or (equal newcmd (car command-history))
1567 (setq command-history (cons newcmd command-history)))
1568 (apply #'funcall-interactively
1569 (car newcmd)
1570 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1571 (if command-history
1572 (error "Argument %d is beyond length of command history" arg)
1573 (error "There are no previous complex commands to repeat")))))
1576 (defvar extended-command-history nil)
1577 (defvar execute-extended-command--last-typed nil)
1579 (defun read-extended-command ()
1580 "Read command name to invoke in `execute-extended-command'."
1581 (minibuffer-with-setup-hook
1582 (lambda ()
1583 (add-hook 'post-self-insert-hook
1584 (lambda ()
1585 (setq execute-extended-command--last-typed
1586 (minibuffer-contents)))
1587 nil 'local)
1588 (set (make-local-variable 'minibuffer-default-add-function)
1589 (lambda ()
1590 ;; Get a command name at point in the original buffer
1591 ;; to propose it after M-n.
1592 (with-current-buffer (window-buffer (minibuffer-selected-window))
1593 (and (commandp (function-called-at-point))
1594 (format "%S" (function-called-at-point)))))))
1595 ;; Read a string, completing from and restricting to the set of
1596 ;; all defined commands. Don't provide any initial input.
1597 ;; Save the command read on the extended-command history list.
1598 (completing-read
1599 (concat (cond
1600 ((eq current-prefix-arg '-) "- ")
1601 ((and (consp current-prefix-arg)
1602 (eq (car current-prefix-arg) 4)) "C-u ")
1603 ((and (consp current-prefix-arg)
1604 (integerp (car current-prefix-arg)))
1605 (format "%d " (car current-prefix-arg)))
1606 ((integerp current-prefix-arg)
1607 (format "%d " current-prefix-arg)))
1608 ;; This isn't strictly correct if `execute-extended-command'
1609 ;; is bound to anything else (e.g. [menu]).
1610 ;; It could use (key-description (this-single-command-keys)),
1611 ;; but actually a prompt other than "M-x" would be confusing,
1612 ;; because "M-x" is a well-known prompt to read a command
1613 ;; and it serves as a shorthand for "Extended command: ".
1614 "M-x ")
1615 (lambda (string pred action)
1616 (let ((pred
1617 (if (memq action '(nil t))
1618 ;; Exclude obsolete commands from completions.
1619 (lambda (sym)
1620 (and (funcall pred sym)
1621 (or (equal string (symbol-name sym))
1622 (not (get sym 'byte-obsolete-info)))))
1623 pred)))
1624 (complete-with-action action obarray string pred)))
1625 #'commandp t nil 'extended-command-history)))
1627 (defcustom suggest-key-bindings t
1628 "Non-nil means show the equivalent key-binding when M-x command has one.
1629 The value can be a length of time to show the message for.
1630 If the value is non-nil and not a number, we wait 2 seconds."
1631 :group 'keyboard
1632 :type '(choice (const :tag "off" nil)
1633 (integer :tag "time" 2)
1634 (other :tag "on")))
1636 (defun execute-extended-command--shorter-1 (name length)
1637 (cond
1638 ((zerop length) (list ""))
1639 ((equal name "") nil)
1641 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1642 (execute-extended-command--shorter-1
1643 (substring name 1) (1- length)))
1644 (when (string-match "\\`\\(-\\)?[^-]*" name)
1645 (execute-extended-command--shorter-1
1646 (substring name (match-end 0)) length))))))
1648 (defun execute-extended-command--shorter (name typed)
1649 (let ((candidates '())
1650 (max (length typed))
1651 (len 1)
1652 binding)
1653 (while (and (not binding)
1654 (progn
1655 (unless candidates
1656 (setq len (1+ len))
1657 (setq candidates (execute-extended-command--shorter-1
1658 name len)))
1659 ;; Don't show the help message if the binding isn't
1660 ;; significantly shorter than the M-x command the user typed.
1661 (< len (- max 5))))
1662 (let ((candidate (pop candidates)))
1663 (when (equal name
1664 (car-safe (completion-try-completion
1665 candidate obarray 'commandp len)))
1666 (setq binding candidate))))
1667 binding))
1669 (defun execute-extended-command (prefixarg &optional command-name typed)
1670 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1671 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1672 "Read a command name, then read the arguments and call the command.
1673 To pass a prefix argument to the command you are
1674 invoking, give a prefix argument to `execute-extended-command'."
1675 (declare (interactive-only command-execute))
1676 ;; FIXME: Remember the actual text typed by the user before completion,
1677 ;; so that we don't later on suggest the same shortening.
1678 (interactive
1679 (let ((execute-extended-command--last-typed nil))
1680 (list current-prefix-arg
1681 (read-extended-command)
1682 execute-extended-command--last-typed)))
1683 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1684 (unless command-name
1685 (let ((current-prefix-arg prefixarg) ; for prompt
1686 (execute-extended-command--last-typed nil))
1687 (setq command-name (read-extended-command))
1688 (setq typed execute-extended-command--last-typed)))
1689 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1690 (binding (and suggest-key-bindings
1691 (not executing-kbd-macro)
1692 (where-is-internal function overriding-local-map t))))
1693 (unless (commandp function)
1694 (error "`%s' is not a valid command name" command-name))
1695 (setq this-command function)
1696 ;; Normally `real-this-command' should never be changed, but here we really
1697 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1698 ;; binding" for <cmd>, so the command the user really wanted to run is
1699 ;; `function' and not `execute-extended-command'. The difference is
1700 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1701 (setq real-this-command function)
1702 (let ((prefix-arg prefixarg))
1703 (command-execute function 'record))
1704 ;; If enabled, show which key runs this command.
1705 ;; But first wait, and skip the message if there is input.
1706 (let* ((waited
1707 ;; If this command displayed something in the echo area;
1708 ;; wait a few seconds, then display our suggestion message.
1709 ;; FIXME: Wait *after* running post-command-hook!
1710 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1711 ;; find a better answer anyway!
1712 (when suggest-key-bindings
1713 (sit-for (cond
1714 ((zerop (length (current-message))) 0)
1715 ((numberp suggest-key-bindings) suggest-key-bindings)
1716 (t 2))))))
1717 (when (and waited (not (consp unread-command-events)))
1718 (unless (or binding executing-kbd-macro (not (symbolp function))
1719 (<= (length (symbol-name function)) 2))
1720 ;; There's no binding for CMD. Let's try and find the shortest
1721 ;; string to use in M-x.
1722 ;; FIXME: Can be slow. Cache it maybe?
1723 (while-no-input
1724 (setq binding (execute-extended-command--shorter
1725 (symbol-name function) typed))))
1726 (when binding
1727 (with-temp-message
1728 (format-message "You can run the command `%s' with %s"
1729 function
1730 (if (stringp binding)
1731 (concat "M-x " binding " RET")
1732 (key-description binding)))
1733 (sit-for (if (numberp suggest-key-bindings)
1734 suggest-key-bindings
1735 2))))))))
1737 (defun command-execute (cmd &optional record-flag keys special)
1738 ;; BEWARE: Called directly from the C code.
1739 "Execute CMD as an editor command.
1740 CMD must be a symbol that satisfies the `commandp' predicate.
1741 Optional second arg RECORD-FLAG non-nil
1742 means unconditionally put this command in the variable `command-history'.
1743 Otherwise, that is done only if an arg is read using the minibuffer.
1744 The argument KEYS specifies the value to use instead of (this-command-keys)
1745 when reading the arguments; if it is nil, (this-command-keys) is used.
1746 The argument SPECIAL, if non-nil, means that this command is executing
1747 a special event, so ignore the prefix argument and don't clear it."
1748 (setq debug-on-next-call nil)
1749 (let ((prefixarg (unless special
1750 ;; FIXME: This should probably be done around
1751 ;; pre-command-hook rather than here!
1752 (prog1 prefix-arg
1753 (setq current-prefix-arg prefix-arg)
1754 (setq prefix-arg nil)
1755 (when current-prefix-arg
1756 (prefix-command-update))))))
1757 (if (and (symbolp cmd)
1758 (get cmd 'disabled)
1759 disabled-command-function)
1760 ;; FIXME: Weird calling convention!
1761 (run-hooks 'disabled-command-function)
1762 (let ((final cmd))
1763 (while
1764 (progn
1765 (setq final (indirect-function final))
1766 (if (autoloadp final)
1767 (setq final (autoload-do-load final cmd)))))
1768 (cond
1769 ((arrayp final)
1770 ;; If requested, place the macro in the command history. For
1771 ;; other sorts of commands, call-interactively takes care of this.
1772 (when record-flag
1773 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1774 ;; Don't keep command history around forever.
1775 (when (and (numberp history-length) (> history-length 0))
1776 (let ((cell (nthcdr history-length command-history)))
1777 (if (consp cell) (setcdr cell nil)))))
1778 (execute-kbd-macro final prefixarg))
1780 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1781 (prog1 (call-interactively cmd record-flag keys)
1782 (when (and (symbolp cmd)
1783 (get cmd 'byte-obsolete-info)
1784 (not (get cmd 'command-execute-obsolete-warned)))
1785 (put cmd 'command-execute-obsolete-warned t)
1786 (message "%s" (macroexp--obsolete-warning
1787 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1789 (defvar minibuffer-history nil
1790 "Default minibuffer history list.
1791 This is used for all minibuffer input
1792 except when an alternate history list is specified.
1794 Maximum length of the history list is determined by the value
1795 of `history-length', which see.")
1796 (defvar minibuffer-history-sexp-flag nil
1797 "Control whether history list elements are expressions or strings.
1798 If the value of this variable equals current minibuffer depth,
1799 they are expressions; otherwise they are strings.
1800 \(That convention is designed to do the right thing for
1801 recursive uses of the minibuffer.)")
1802 (setq minibuffer-history-variable 'minibuffer-history)
1803 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1804 (defvar minibuffer-history-search-history nil)
1806 (defvar minibuffer-text-before-history nil
1807 "Text that was in this minibuffer before any history commands.
1808 This is nil if there have not yet been any history commands
1809 in this use of the minibuffer.")
1811 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1813 (defun minibuffer-history-initialize ()
1814 (setq minibuffer-text-before-history nil))
1816 (defun minibuffer-avoid-prompt (_new _old)
1817 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1818 (declare (obsolete cursor-intangible-mode "25.1"))
1819 (constrain-to-field nil (point-max)))
1821 (defcustom minibuffer-history-case-insensitive-variables nil
1822 "Minibuffer history variables for which matching should ignore case.
1823 If a history variable is a member of this list, then the
1824 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1825 commands ignore case when searching it, regardless of `case-fold-search'."
1826 :type '(repeat variable)
1827 :group 'minibuffer)
1829 (defun previous-matching-history-element (regexp n)
1830 "Find the previous history element that matches REGEXP.
1831 \(Previous history elements refer to earlier actions.)
1832 With prefix argument N, search for Nth previous match.
1833 If N is negative, find the next or Nth next match.
1834 Normally, history elements are matched case-insensitively if
1835 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1836 makes the search case-sensitive.
1837 See also `minibuffer-history-case-insensitive-variables'."
1838 (interactive
1839 (let* ((enable-recursive-minibuffers t)
1840 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1842 minibuffer-local-map
1844 'minibuffer-history-search-history
1845 (car minibuffer-history-search-history))))
1846 ;; Use the last regexp specified, by default, if input is empty.
1847 (list (if (string= regexp "")
1848 (if minibuffer-history-search-history
1849 (car minibuffer-history-search-history)
1850 (user-error "No previous history search regexp"))
1851 regexp)
1852 (prefix-numeric-value current-prefix-arg))))
1853 (unless (zerop n)
1854 (if (and (zerop minibuffer-history-position)
1855 (null minibuffer-text-before-history))
1856 (setq minibuffer-text-before-history
1857 (minibuffer-contents-no-properties)))
1858 (let ((history (symbol-value minibuffer-history-variable))
1859 (case-fold-search
1860 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1861 ;; On some systems, ignore case for file names.
1862 (if (memq minibuffer-history-variable
1863 minibuffer-history-case-insensitive-variables)
1865 ;; Respect the user's setting for case-fold-search:
1866 case-fold-search)
1867 nil))
1868 prevpos
1869 match-string
1870 match-offset
1871 (pos minibuffer-history-position))
1872 (while (/= n 0)
1873 (setq prevpos pos)
1874 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1875 (when (= pos prevpos)
1876 (user-error (if (= pos 1)
1877 "No later matching history item"
1878 "No earlier matching history item")))
1879 (setq match-string
1880 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1881 (let ((print-level nil))
1882 (prin1-to-string (nth (1- pos) history)))
1883 (nth (1- pos) history)))
1884 (setq match-offset
1885 (if (< n 0)
1886 (and (string-match regexp match-string)
1887 (match-end 0))
1888 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1889 (match-beginning 1))))
1890 (when match-offset
1891 (setq n (+ n (if (< n 0) 1 -1)))))
1892 (setq minibuffer-history-position pos)
1893 (goto-char (point-max))
1894 (delete-minibuffer-contents)
1895 (insert match-string)
1896 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1897 (if (memq (car (car command-history)) '(previous-matching-history-element
1898 next-matching-history-element))
1899 (setq command-history (cdr command-history))))
1901 (defun next-matching-history-element (regexp n)
1902 "Find the next history element that matches REGEXP.
1903 \(The next history element refers to a more recent action.)
1904 With prefix argument N, search for Nth next match.
1905 If N is negative, find the previous or Nth previous match.
1906 Normally, history elements are matched case-insensitively if
1907 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1908 makes the search case-sensitive."
1909 (interactive
1910 (let* ((enable-recursive-minibuffers t)
1911 (regexp (read-from-minibuffer "Next element matching (regexp): "
1913 minibuffer-local-map
1915 'minibuffer-history-search-history
1916 (car minibuffer-history-search-history))))
1917 ;; Use the last regexp specified, by default, if input is empty.
1918 (list (if (string= regexp "")
1919 (if minibuffer-history-search-history
1920 (car minibuffer-history-search-history)
1921 (user-error "No previous history search regexp"))
1922 regexp)
1923 (prefix-numeric-value current-prefix-arg))))
1924 (previous-matching-history-element regexp (- n)))
1926 (defvar minibuffer-temporary-goal-position nil)
1928 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1929 "Function run by `goto-history-element' before consuming default values.
1930 This is useful to dynamically add more elements to the list of default values
1931 when `goto-history-element' reaches the end of this list.
1932 Before calling this function `goto-history-element' sets the variable
1933 `minibuffer-default-add-done' to t, so it will call this function only
1934 once. In special cases, when this function needs to be called more
1935 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1936 overriding the setting of this variable to t in `goto-history-element'.")
1938 (defvar minibuffer-default-add-done nil
1939 "When nil, add more elements to the end of the list of default values.
1940 The value nil causes `goto-history-element' to add more elements to
1941 the list of defaults when it reaches the end of this list. It does
1942 this by calling a function defined by `minibuffer-default-add-function'.")
1944 (make-variable-buffer-local 'minibuffer-default-add-done)
1946 (defun minibuffer-default-add-completions ()
1947 "Return a list of all completions without the default value.
1948 This function is used to add all elements of the completion table to
1949 the end of the list of defaults just after the default value."
1950 (let ((def minibuffer-default)
1951 (all (all-completions ""
1952 minibuffer-completion-table
1953 minibuffer-completion-predicate)))
1954 (if (listp def)
1955 (append def all)
1956 (cons def (delete def all)))))
1958 (defun goto-history-element (nabs)
1959 "Puts element of the minibuffer history in the minibuffer.
1960 The argument NABS specifies the absolute history position."
1961 (interactive "p")
1962 (when (and (not minibuffer-default-add-done)
1963 (functionp minibuffer-default-add-function)
1964 (< nabs (- (if (listp minibuffer-default)
1965 (length minibuffer-default)
1966 1))))
1967 (setq minibuffer-default-add-done t
1968 minibuffer-default (funcall minibuffer-default-add-function)))
1969 (let ((minimum (if minibuffer-default
1970 (- (if (listp minibuffer-default)
1971 (length minibuffer-default)
1974 elt minibuffer-returned-to-present)
1975 (if (and (zerop minibuffer-history-position)
1976 (null minibuffer-text-before-history))
1977 (setq minibuffer-text-before-history
1978 (minibuffer-contents-no-properties)))
1979 (if (< nabs minimum)
1980 (user-error (if minibuffer-default
1981 "End of defaults; no next item"
1982 "End of history; no default available")))
1983 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
1984 (length (symbol-value minibuffer-history-variable))
1986 (user-error "Beginning of history; no preceding item"))
1987 (unless (memq last-command '(next-history-element
1988 previous-history-element))
1989 (let ((prompt-end (minibuffer-prompt-end)))
1990 (set (make-local-variable 'minibuffer-temporary-goal-position)
1991 (cond ((<= (point) prompt-end) prompt-end)
1992 ((eobp) nil)
1993 (t (point))))))
1994 (goto-char (point-max))
1995 (delete-minibuffer-contents)
1996 (setq minibuffer-history-position nabs)
1997 (cond ((< nabs 0)
1998 (setq elt (if (listp minibuffer-default)
1999 (nth (1- (abs nabs)) minibuffer-default)
2000 minibuffer-default)))
2001 ((= nabs 0)
2002 (setq elt (or minibuffer-text-before-history ""))
2003 (setq minibuffer-returned-to-present t)
2004 (setq minibuffer-text-before-history nil))
2005 (t (setq elt (nth (1- minibuffer-history-position)
2006 (symbol-value minibuffer-history-variable)))))
2007 (insert
2008 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2009 (not minibuffer-returned-to-present))
2010 (let ((print-level nil))
2011 (prin1-to-string elt))
2012 elt))
2013 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2015 (defun next-history-element (n)
2016 "Puts next element of the minibuffer history in the minibuffer.
2017 With argument N, it uses the Nth following element."
2018 (interactive "p")
2019 (or (zerop n)
2020 (goto-history-element (- minibuffer-history-position n))))
2022 (defun previous-history-element (n)
2023 "Puts previous element of the minibuffer history in the minibuffer.
2024 With argument N, it uses the Nth previous element."
2025 (interactive "p")
2026 (or (zerop n)
2027 (goto-history-element (+ minibuffer-history-position n))))
2029 (defun next-line-or-history-element (&optional arg)
2030 "Move cursor vertically down ARG lines, or to the next history element.
2031 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2032 next element of the minibuffer history in the minibuffer."
2033 (interactive "^p")
2034 (or arg (setq arg 1))
2035 (let* ((old-point (point))
2036 ;; Remember the original goal column of possibly multi-line input
2037 ;; excluding the length of the prompt on the first line.
2038 (prompt-end (minibuffer-prompt-end))
2039 (old-column (unless (and (eolp) (> (point) prompt-end))
2040 (if (= (line-number-at-pos) 1)
2041 (max (- (current-column) (1- prompt-end)) 0)
2042 (current-column)))))
2043 (condition-case nil
2044 (with-no-warnings
2045 (next-line arg))
2046 (end-of-buffer
2047 ;; Restore old position since `line-move-visual' moves point to
2048 ;; the end of the line when it fails to go to the next line.
2049 (goto-char old-point)
2050 (next-history-element arg)
2051 ;; Reset `temporary-goal-column' because a correct value is not
2052 ;; calculated when `next-line' above fails by bumping against
2053 ;; the bottom of the minibuffer (bug#22544).
2054 (setq temporary-goal-column 0)
2055 ;; Restore the original goal column on the last line
2056 ;; of possibly multi-line input.
2057 (goto-char (point-max))
2058 (when old-column
2059 (if (= (line-number-at-pos) 1)
2060 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2061 (move-to-column old-column)))))))
2063 (defun previous-line-or-history-element (&optional arg)
2064 "Move cursor vertically up ARG lines, or to the previous history element.
2065 When point moves over the top line of multi-line minibuffer, puts ARGth
2066 previous element of the minibuffer history in the minibuffer."
2067 (interactive "^p")
2068 (or arg (setq arg 1))
2069 (let* ((old-point (point))
2070 ;; Remember the original goal column of possibly multi-line input
2071 ;; excluding the length of the prompt on the first line.
2072 (prompt-end (minibuffer-prompt-end))
2073 (old-column (unless (and (eolp) (> (point) prompt-end))
2074 (if (= (line-number-at-pos) 1)
2075 (max (- (current-column) (1- prompt-end)) 0)
2076 (current-column)))))
2077 (condition-case nil
2078 (with-no-warnings
2079 (previous-line arg))
2080 (beginning-of-buffer
2081 ;; Restore old position since `line-move-visual' moves point to
2082 ;; the beginning of the line when it fails to go to the previous line.
2083 (goto-char old-point)
2084 (previous-history-element arg)
2085 ;; Reset `temporary-goal-column' because a correct value is not
2086 ;; calculated when `previous-line' above fails by bumping against
2087 ;; the top of the minibuffer (bug#22544).
2088 (setq temporary-goal-column 0)
2089 ;; Restore the original goal column on the first line
2090 ;; of possibly multi-line input.
2091 (goto-char (minibuffer-prompt-end))
2092 (if old-column
2093 (if (= (line-number-at-pos) 1)
2094 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2095 (move-to-column old-column))
2096 ;; Put the cursor at the end of the visual line instead of the
2097 ;; logical line, so the next `previous-line-or-history-element'
2098 ;; would move to the previous history element, not to a possible upper
2099 ;; visual line from the end of logical line in `line-move-visual' mode.
2100 (end-of-visual-line)
2101 ;; Since `end-of-visual-line' puts the cursor at the beginning
2102 ;; of the next visual line, move it one char back to the end
2103 ;; of the first visual line (bug#22544).
2104 (unless (eolp) (backward-char 1)))))))
2106 (defun next-complete-history-element (n)
2107 "Get next history element which completes the minibuffer before the point.
2108 The contents of the minibuffer after the point are deleted, and replaced
2109 by the new completion."
2110 (interactive "p")
2111 (let ((point-at-start (point)))
2112 (next-matching-history-element
2113 (concat
2114 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2116 ;; next-matching-history-element always puts us at (point-min).
2117 ;; Move to the position we were at before changing the buffer contents.
2118 ;; This is still sensible, because the text before point has not changed.
2119 (goto-char point-at-start)))
2121 (defun previous-complete-history-element (n)
2123 Get previous history element which completes the minibuffer before the point.
2124 The contents of the minibuffer after the point are deleted, and replaced
2125 by the new completion."
2126 (interactive "p")
2127 (next-complete-history-element (- n)))
2129 ;; For compatibility with the old subr of the same name.
2130 (defun minibuffer-prompt-width ()
2131 "Return the display width of the minibuffer prompt.
2132 Return 0 if current buffer is not a minibuffer."
2133 ;; Return the width of everything before the field at the end of
2134 ;; the buffer; this should be 0 for normal buffers.
2135 (1- (minibuffer-prompt-end)))
2137 ;; isearch minibuffer history
2138 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2140 (defvar minibuffer-history-isearch-message-overlay)
2141 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2143 (defun minibuffer-history-isearch-setup ()
2144 "Set up a minibuffer for using isearch to search the minibuffer history.
2145 Intended to be added to `minibuffer-setup-hook'."
2146 (set (make-local-variable 'isearch-search-fun-function)
2147 'minibuffer-history-isearch-search)
2148 (set (make-local-variable 'isearch-message-function)
2149 'minibuffer-history-isearch-message)
2150 (set (make-local-variable 'isearch-wrap-function)
2151 'minibuffer-history-isearch-wrap)
2152 (set (make-local-variable 'isearch-push-state-function)
2153 'minibuffer-history-isearch-push-state)
2154 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2156 (defun minibuffer-history-isearch-end ()
2157 "Clean up the minibuffer after terminating isearch in the minibuffer."
2158 (if minibuffer-history-isearch-message-overlay
2159 (delete-overlay minibuffer-history-isearch-message-overlay)))
2161 (defun minibuffer-history-isearch-search ()
2162 "Return the proper search function, for isearch in minibuffer history."
2163 (lambda (string bound noerror)
2164 (let ((search-fun
2165 ;; Use standard functions to search within minibuffer text
2166 (isearch-search-fun-default))
2167 found)
2168 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2169 ;; searching forward. Lazy-highlight calls this lambda with the
2170 ;; bound arg, so skip the minibuffer prompt.
2171 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2172 (goto-char (minibuffer-prompt-end)))
2174 ;; 1. First try searching in the initial minibuffer text
2175 (funcall search-fun string
2176 (if isearch-forward bound (minibuffer-prompt-end))
2177 noerror)
2178 ;; 2. If the above search fails, start putting next/prev history
2179 ;; elements in the minibuffer successively, and search the string
2180 ;; in them. Do this only when bound is nil (i.e. not while
2181 ;; lazy-highlighting search strings in the current minibuffer text).
2182 (unless bound
2183 (condition-case nil
2184 (progn
2185 (while (not found)
2186 (cond (isearch-forward
2187 (next-history-element 1)
2188 (goto-char (minibuffer-prompt-end)))
2190 (previous-history-element 1)
2191 (goto-char (point-max))))
2192 (setq isearch-barrier (point) isearch-opoint (point))
2193 ;; After putting the next/prev history element, search
2194 ;; the string in them again, until next-history-element
2195 ;; or previous-history-element raises an error at the
2196 ;; beginning/end of history.
2197 (setq found (funcall search-fun string
2198 (unless isearch-forward
2199 ;; For backward search, don't search
2200 ;; in the minibuffer prompt
2201 (minibuffer-prompt-end))
2202 noerror)))
2203 ;; Return point of the new search result
2204 (point))
2205 ;; Return nil when next(prev)-history-element fails
2206 (error nil)))))))
2208 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2209 "Display the minibuffer history search prompt.
2210 If there are no search errors, this function displays an overlay with
2211 the isearch prompt which replaces the original minibuffer prompt.
2212 Otherwise, it displays the standard isearch message returned from
2213 the function `isearch-message'."
2214 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2215 ;; Use standard function `isearch-message' when not in the minibuffer,
2216 ;; or search fails, or has an error (like incomplete regexp).
2217 ;; This function overwrites minibuffer text with isearch message,
2218 ;; so it's possible to see what is wrong in the search string.
2219 (isearch-message c-q-hack ellipsis)
2220 ;; Otherwise, put the overlay with the standard isearch prompt over
2221 ;; the initial minibuffer prompt.
2222 (if (overlayp minibuffer-history-isearch-message-overlay)
2223 (move-overlay minibuffer-history-isearch-message-overlay
2224 (point-min) (minibuffer-prompt-end))
2225 (setq minibuffer-history-isearch-message-overlay
2226 (make-overlay (point-min) (minibuffer-prompt-end)))
2227 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2228 (overlay-put minibuffer-history-isearch-message-overlay
2229 'display (isearch-message-prefix c-q-hack ellipsis))
2230 ;; And clear any previous isearch message.
2231 (message "")))
2233 (defun minibuffer-history-isearch-wrap ()
2234 "Wrap the minibuffer history search when search fails.
2235 Move point to the first history element for a forward search,
2236 or to the last history element for a backward search."
2237 ;; When `minibuffer-history-isearch-search' fails on reaching the
2238 ;; beginning/end of the history, wrap the search to the first/last
2239 ;; minibuffer history element.
2240 (if isearch-forward
2241 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2242 (goto-history-element 0))
2243 (setq isearch-success t)
2244 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2246 (defun minibuffer-history-isearch-push-state ()
2247 "Save a function restoring the state of minibuffer history search.
2248 Save `minibuffer-history-position' to the additional state parameter
2249 in the search status stack."
2250 (let ((pos minibuffer-history-position))
2251 (lambda (cmd)
2252 (minibuffer-history-isearch-pop-state cmd pos))))
2254 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2255 "Restore the minibuffer history search state.
2256 Go to the history element by the absolute history position HIST-POS."
2257 (goto-history-element hist-pos))
2260 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2261 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2263 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2264 "Table mapping redo records to the corresponding undo one.
2265 A redo record for undo-in-region maps to t.
2266 A redo record for ordinary undo maps to the following (earlier) undo.")
2268 (defvar undo-in-region nil
2269 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2271 (defvar undo-no-redo nil
2272 "If t, `undo' doesn't go through redo entries.")
2274 (defvar pending-undo-list nil
2275 "Within a run of consecutive undo commands, list remaining to be undone.
2276 If t, we undid all the way to the end of it.")
2278 (defun undo (&optional arg)
2279 "Undo some previous changes.
2280 Repeat this command to undo more changes.
2281 A numeric ARG serves as a repeat count.
2283 In Transient Mark mode when the mark is active, only undo changes within
2284 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2285 as an argument limits undo to changes within the current region."
2286 (interactive "*P")
2287 ;; Make last-command indicate for the next command that this was an undo.
2288 ;; That way, another undo will undo more.
2289 ;; If we get to the end of the undo history and get an error,
2290 ;; another undo command will find the undo history empty
2291 ;; and will get another error. To begin undoing the undos,
2292 ;; you must type some other command.
2293 (let* ((modified (buffer-modified-p))
2294 ;; For an indirect buffer, look in the base buffer for the
2295 ;; auto-save data.
2296 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2297 (recent-save (with-current-buffer base-buffer
2298 (recent-auto-save-p)))
2299 message)
2300 ;; If we get an error in undo-start,
2301 ;; the next command should not be a "consecutive undo".
2302 ;; So set `this-command' to something other than `undo'.
2303 (setq this-command 'undo-start)
2305 (unless (and (eq last-command 'undo)
2306 (or (eq pending-undo-list t)
2307 ;; If something (a timer or filter?) changed the buffer
2308 ;; since the previous command, don't continue the undo seq.
2309 (let ((list buffer-undo-list))
2310 (while (eq (car list) nil)
2311 (setq list (cdr list)))
2312 ;; If the last undo record made was made by undo
2313 ;; it shows nothing else happened in between.
2314 (gethash list undo-equiv-table))))
2315 (setq undo-in-region
2316 (or (region-active-p) (and arg (not (numberp arg)))))
2317 (if undo-in-region
2318 (undo-start (region-beginning) (region-end))
2319 (undo-start))
2320 ;; get rid of initial undo boundary
2321 (undo-more 1))
2322 ;; If we got this far, the next command should be a consecutive undo.
2323 (setq this-command 'undo)
2324 ;; Check to see whether we're hitting a redo record, and if
2325 ;; so, ask the user whether she wants to skip the redo/undo pair.
2326 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2327 (or (eq (selected-window) (minibuffer-window))
2328 (setq message (format "%s%s!"
2329 (if (or undo-no-redo (not equiv))
2330 "Undo" "Redo")
2331 (if undo-in-region " in region" ""))))
2332 (when (and (consp equiv) undo-no-redo)
2333 ;; The equiv entry might point to another redo record if we have done
2334 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2335 (while (let ((next (gethash equiv undo-equiv-table)))
2336 (if next (setq equiv next))))
2337 (setq pending-undo-list equiv)))
2338 (undo-more
2339 (if (numberp arg)
2340 (prefix-numeric-value arg)
2342 ;; Record the fact that the just-generated undo records come from an
2343 ;; undo operation--that is, they are redo records.
2344 ;; In the ordinary case (not within a region), map the redo
2345 ;; record to the following undos.
2346 ;; I don't know how to do that in the undo-in-region case.
2347 (let ((list buffer-undo-list))
2348 ;; Strip any leading undo boundaries there might be, like we do
2349 ;; above when checking.
2350 (while (eq (car list) nil)
2351 (setq list (cdr list)))
2352 (puthash list
2353 ;; Prevent identity mapping. This can happen if
2354 ;; consecutive nils are erroneously in undo list.
2355 (if (or undo-in-region (eq list pending-undo-list))
2357 pending-undo-list)
2358 undo-equiv-table))
2359 ;; Don't specify a position in the undo record for the undo command.
2360 ;; Instead, undoing this should move point to where the change is.
2361 (let ((tail buffer-undo-list)
2362 (prev nil))
2363 (while (car tail)
2364 (when (integerp (car tail))
2365 (let ((pos (car tail)))
2366 (if prev
2367 (setcdr prev (cdr tail))
2368 (setq buffer-undo-list (cdr tail)))
2369 (setq tail (cdr tail))
2370 (while (car tail)
2371 (if (eq pos (car tail))
2372 (if prev
2373 (setcdr prev (cdr tail))
2374 (setq buffer-undo-list (cdr tail)))
2375 (setq prev tail))
2376 (setq tail (cdr tail)))
2377 (setq tail nil)))
2378 (setq prev tail tail (cdr tail))))
2379 ;; Record what the current undo list says,
2380 ;; so the next command can tell if the buffer was modified in between.
2381 (and modified (not (buffer-modified-p))
2382 (with-current-buffer base-buffer
2383 (delete-auto-save-file-if-necessary recent-save)))
2384 ;; Display a message announcing success.
2385 (if message
2386 (message "%s" message))))
2388 (defun buffer-disable-undo (&optional buffer)
2389 "Make BUFFER stop keeping undo information.
2390 No argument or nil as argument means do this for the current buffer."
2391 (interactive)
2392 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2393 (setq buffer-undo-list t)))
2395 (defun undo-only (&optional arg)
2396 "Undo some previous changes.
2397 Repeat this command to undo more changes.
2398 A numeric ARG serves as a repeat count.
2399 Contrary to `undo', this will not redo a previous undo."
2400 (interactive "*p")
2401 (let ((undo-no-redo t)) (undo arg)))
2403 (defvar undo-in-progress nil
2404 "Non-nil while performing an undo.
2405 Some change-hooks test this variable to do something different.")
2407 (defun undo-more (n)
2408 "Undo back N undo-boundaries beyond what was already undone recently.
2409 Call `undo-start' to get ready to undo recent changes,
2410 then call `undo-more' one or more times to undo them."
2411 (or (listp pending-undo-list)
2412 (user-error (concat "No further undo information"
2413 (and undo-in-region " for region"))))
2414 (let ((undo-in-progress t))
2415 ;; Note: The following, while pulling elements off
2416 ;; `pending-undo-list' will call primitive change functions which
2417 ;; will push more elements onto `buffer-undo-list'.
2418 (setq pending-undo-list (primitive-undo n pending-undo-list))
2419 (if (null pending-undo-list)
2420 (setq pending-undo-list t))))
2422 (defun primitive-undo (n list)
2423 "Undo N records from the front of the list LIST.
2424 Return what remains of the list."
2426 ;; This is a good feature, but would make undo-start
2427 ;; unable to do what is expected.
2428 ;;(when (null (car (list)))
2429 ;; ;; If the head of the list is a boundary, it is the boundary
2430 ;; ;; preceding this command. Get rid of it and don't count it.
2431 ;; (setq list (cdr list))))
2433 (let ((arg n)
2434 ;; In a writable buffer, enable undoing read-only text that is
2435 ;; so because of text properties.
2436 (inhibit-read-only t)
2437 ;; Don't let `intangible' properties interfere with undo.
2438 (inhibit-point-motion-hooks t)
2439 ;; We use oldlist only to check for EQ. ++kfs
2440 (oldlist buffer-undo-list)
2441 (did-apply nil)
2442 (next nil))
2443 (while (> arg 0)
2444 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2445 ;; Handle an integer by setting point to that value.
2446 (pcase next
2447 ((pred integerp) (goto-char next))
2448 ;; Element (t . TIME) records previous modtime.
2449 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2450 ;; UNKNOWN_MODTIME_NSECS.
2451 (`(t . ,time)
2452 ;; If this records an obsolete save
2453 ;; (not matching the actual disk file)
2454 ;; then don't mark unmodified.
2455 (when (or (equal time (visited-file-modtime))
2456 (and (consp time)
2457 (equal (list (car time) (cdr time))
2458 (visited-file-modtime))))
2459 (when (fboundp 'unlock-buffer)
2460 (unlock-buffer))
2461 (set-buffer-modified-p nil)))
2462 ;; Element (nil PROP VAL BEG . END) is property change.
2463 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2464 (when (or (> (point-min) beg) (< (point-max) end))
2465 (error "Changes to be undone are outside visible portion of buffer"))
2466 (put-text-property beg end prop val))
2467 ;; Element (BEG . END) means range was inserted.
2468 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2469 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2470 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2471 (when (or (> (point-min) beg) (< (point-max) end))
2472 (error "Changes to be undone are outside visible portion of buffer"))
2473 ;; Set point first thing, so that undoing this undo
2474 ;; does not send point back to where it is now.
2475 (goto-char beg)
2476 (delete-region beg end))
2477 ;; Element (apply FUN . ARGS) means call FUN to undo.
2478 (`(apply . ,fun-args)
2479 (let ((currbuff (current-buffer)))
2480 (if (integerp (car fun-args))
2481 ;; Long format: (apply DELTA START END FUN . ARGS).
2482 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2483 (start-mark (copy-marker start nil))
2484 (end-mark (copy-marker end t)))
2485 (when (or (> (point-min) start) (< (point-max) end))
2486 (error "Changes to be undone are outside visible portion of buffer"))
2487 (apply fun args) ;; Use `save-current-buffer'?
2488 ;; Check that the function did what the entry
2489 ;; said it would do.
2490 (unless (and (= start start-mark)
2491 (= (+ delta end) end-mark))
2492 (error "Changes to be undone by function different than announced"))
2493 (set-marker start-mark nil)
2494 (set-marker end-mark nil))
2495 (apply fun-args))
2496 (unless (eq currbuff (current-buffer))
2497 (error "Undo function switched buffer"))
2498 (setq did-apply t)))
2499 ;; Element (STRING . POS) means STRING was deleted.
2500 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2501 (when (let ((apos (abs pos)))
2502 (or (< apos (point-min)) (> apos (point-max))))
2503 (error "Changes to be undone are outside visible portion of buffer"))
2504 (let (valid-marker-adjustments)
2505 ;; Check that marker adjustments which were recorded
2506 ;; with the (STRING . POS) record are still valid, ie
2507 ;; the markers haven't moved. We check their validity
2508 ;; before reinserting the string so as we don't need to
2509 ;; mind marker insertion-type.
2510 (while (and (markerp (car-safe (car list)))
2511 (integerp (cdr-safe (car list))))
2512 (let* ((marker-adj (pop list))
2513 (m (car marker-adj)))
2514 (and (eq (marker-buffer m) (current-buffer))
2515 (= pos m)
2516 (push marker-adj valid-marker-adjustments))))
2517 ;; Insert string and adjust point
2518 (if (< pos 0)
2519 (progn
2520 (goto-char (- pos))
2521 (insert string))
2522 (goto-char pos)
2523 (insert string)
2524 (goto-char pos))
2525 ;; Adjust the valid marker adjustments
2526 (dolist (adj valid-marker-adjustments)
2527 (set-marker (car adj)
2528 (- (car adj) (cdr adj))))))
2529 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2530 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2531 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2532 next)
2533 ;; Even though these elements are not expected in the undo
2534 ;; list, adjust them to be conservative for the 24.4
2535 ;; release. (Bug#16818)
2536 (when (marker-buffer marker)
2537 (set-marker marker
2538 (- marker offset)
2539 (marker-buffer marker))))
2540 (_ (error "Unrecognized entry in undo list %S" next))))
2541 (setq arg (1- arg)))
2542 ;; Make sure an apply entry produces at least one undo entry,
2543 ;; so the test in `undo' for continuing an undo series
2544 ;; will work right.
2545 (if (and did-apply
2546 (eq oldlist buffer-undo-list))
2547 (setq buffer-undo-list
2548 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2549 list)
2551 ;; Deep copy of a list
2552 (defun undo-copy-list (list)
2553 "Make a copy of undo list LIST."
2554 (mapcar 'undo-copy-list-1 list))
2556 (defun undo-copy-list-1 (elt)
2557 (if (consp elt)
2558 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2559 elt))
2561 (defun undo-start (&optional beg end)
2562 "Set `pending-undo-list' to the front of the undo list.
2563 The next call to `undo-more' will undo the most recently made change.
2564 If BEG and END are specified, then only undo elements
2565 that apply to text between BEG and END are used; other undo elements
2566 are ignored. If BEG and END are nil, all undo elements are used."
2567 (if (eq buffer-undo-list t)
2568 (user-error "No undo information in this buffer"))
2569 (setq pending-undo-list
2570 (if (and beg end (not (= beg end)))
2571 (undo-make-selective-list (min beg end) (max beg end))
2572 buffer-undo-list)))
2574 ;; The positions given in elements of the undo list are the positions
2575 ;; as of the time that element was recorded to undo history. In
2576 ;; general, subsequent buffer edits render those positions invalid in
2577 ;; the current buffer, unless adjusted according to the intervening
2578 ;; undo elements.
2580 ;; Undo in region is a use case that requires adjustments to undo
2581 ;; elements. It must adjust positions of elements in the region based
2582 ;; on newer elements not in the region so as they may be correctly
2583 ;; applied in the current buffer. undo-make-selective-list
2584 ;; accomplishes this with its undo-deltas list of adjustments. An
2585 ;; example undo history from oldest to newest:
2587 ;; buf pos:
2588 ;; 123456789 buffer-undo-list undo-deltas
2589 ;; --------- ---------------- -----------
2590 ;; aaa (1 . 4) (1 . -3)
2591 ;; aaba (3 . 4) N/A (in region)
2592 ;; ccaaba (1 . 3) (1 . -2)
2593 ;; ccaabaddd (7 . 10) (7 . -3)
2594 ;; ccaabdd ("ad" . 6) (6 . 2)
2595 ;; ccaabaddd (6 . 8) (6 . -2)
2596 ;; | |<-- region: "caab", from 2 to 6
2598 ;; When the user starts a run of undos in region,
2599 ;; undo-make-selective-list is called to create the full list of in
2600 ;; region elements. Each element is adjusted forward chronologically
2601 ;; through undo-deltas to determine if it is in the region.
2603 ;; In the above example, the insertion of "b" is (3 . 4) in the
2604 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2605 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2606 ;; . 6) is assessed as in the region and placed in the selective list.
2607 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2608 ;; due to the selected element. The "b" insertion is the only element
2609 ;; fully in the region, so in this example undo-make-selective-list
2610 ;; returns (nil (5 . 6)).
2612 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2613 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2614 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2615 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2616 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2618 ;; More interesting is how to adjust the "ddd" insertion due to the
2619 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2620 ;; If the reinsertion was a manual retyping of "ad", then the total
2621 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2622 ;; the reinsertion was due to undo, one might expect the first "d"
2623 ;; character would again be a part of the "ddd" text, meaning its
2624 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2626 ;; undo-make-selective-list assumes in this situation that "ad" was a
2627 ;; new edit, even if it was inserted because of an undo.
2628 ;; Consequently, if the user undos in region "8 to 10" of the
2629 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2630 ;; "ccaabad", as though the first "d" became detached from the
2631 ;; original "ddd" insertion. This quirk is a FIXME.
2633 (defun undo-make-selective-list (start end)
2634 "Return a list of undo elements for the region START to END.
2635 The elements come from `buffer-undo-list', but we keep only the
2636 elements inside this region, and discard those outside this
2637 region. The elements' positions are adjusted so as the returned
2638 list can be applied to the current buffer."
2639 (let ((ulist buffer-undo-list)
2640 ;; A list of position adjusted undo elements in the region.
2641 (selective-list (list nil))
2642 ;; A list of undo-deltas for out of region undo elements.
2643 undo-deltas
2644 undo-elt)
2645 (while ulist
2646 (when undo-no-redo
2647 (while (gethash ulist undo-equiv-table)
2648 (setq ulist (gethash ulist undo-equiv-table))))
2649 (setq undo-elt (car ulist))
2650 (cond
2651 ((null undo-elt)
2652 ;; Don't put two nils together in the list
2653 (when (car selective-list)
2654 (push nil selective-list)))
2655 ((and (consp undo-elt) (eq (car undo-elt) t))
2656 ;; This is a "was unmodified" element. Keep it
2657 ;; if we have kept everything thus far.
2658 (when (not undo-deltas)
2659 (push undo-elt selective-list)))
2660 ;; Skip over marker adjustments, instead relying
2661 ;; on finding them after (TEXT . POS) elements
2662 ((markerp (car-safe undo-elt))
2663 nil)
2665 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2666 undo-deltas)))
2667 (if (undo-elt-in-region adjusted-undo-elt start end)
2668 (progn
2669 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2670 (push adjusted-undo-elt selective-list)
2671 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2672 ;; kept. primitive-undo may discard them later.
2673 (when (and (stringp (car-safe adjusted-undo-elt))
2674 (integerp (cdr-safe adjusted-undo-elt)))
2675 (let ((list-i (cdr ulist)))
2676 (while (markerp (car-safe (car list-i)))
2677 (push (pop list-i) selective-list)))))
2678 (let ((delta (undo-delta undo-elt)))
2679 (when (/= 0 (cdr delta))
2680 (push delta undo-deltas)))))))
2681 (pop ulist))
2682 (nreverse selective-list)))
2684 (defun undo-elt-in-region (undo-elt start end)
2685 "Determine whether UNDO-ELT falls inside the region START ... END.
2686 If it crosses the edge, we return nil.
2688 Generally this function is not useful for determining
2689 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2690 because markers can be arbitrarily relocated. Instead, pass the
2691 marker adjustment's corresponding (TEXT . POS) element."
2692 (cond ((integerp undo-elt)
2693 (and (>= undo-elt start)
2694 (<= undo-elt end)))
2695 ((eq undo-elt nil)
2697 ((atom undo-elt)
2698 nil)
2699 ((stringp (car undo-elt))
2700 ;; (TEXT . POSITION)
2701 (and (>= (abs (cdr undo-elt)) start)
2702 (<= (abs (cdr undo-elt)) end)))
2703 ((and (consp undo-elt) (markerp (car undo-elt)))
2704 ;; (MARKER . ADJUSTMENT)
2705 (<= start (car undo-elt) end))
2706 ((null (car undo-elt))
2707 ;; (nil PROPERTY VALUE BEG . END)
2708 (let ((tail (nthcdr 3 undo-elt)))
2709 (and (>= (car tail) start)
2710 (<= (cdr tail) end))))
2711 ((integerp (car undo-elt))
2712 ;; (BEGIN . END)
2713 (and (>= (car undo-elt) start)
2714 (<= (cdr undo-elt) end)))))
2716 (defun undo-elt-crosses-region (undo-elt start end)
2717 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2718 This assumes we have already decided that UNDO-ELT
2719 is not *inside* the region START...END."
2720 (declare (obsolete nil "25.1"))
2721 (cond ((atom undo-elt) nil)
2722 ((null (car undo-elt))
2723 ;; (nil PROPERTY VALUE BEG . END)
2724 (let ((tail (nthcdr 3 undo-elt)))
2725 (and (< (car tail) end)
2726 (> (cdr tail) start))))
2727 ((integerp (car undo-elt))
2728 ;; (BEGIN . END)
2729 (and (< (car undo-elt) end)
2730 (> (cdr undo-elt) start)))))
2732 (defun undo-adjust-elt (elt deltas)
2733 "Return adjustment of undo element ELT by the undo DELTAS
2734 list."
2735 (pcase elt
2736 ;; POSITION
2737 ((pred integerp)
2738 (undo-adjust-pos elt deltas))
2739 ;; (BEG . END)
2740 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2741 (undo-adjust-beg-end beg end deltas))
2742 ;; (TEXT . POSITION)
2743 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2744 (cons text (* (if (< pos 0) -1 1)
2745 (undo-adjust-pos (abs pos) deltas))))
2746 ;; (nil PROPERTY VALUE BEG . END)
2747 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2748 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2749 ;; (apply DELTA START END FUN . ARGS)
2750 ;; FIXME
2751 ;; All others return same elt
2752 (_ elt)))
2754 ;; (BEG . END) can adjust to the same positions, commonly when an
2755 ;; insertion was undone and they are out of region, for example:
2757 ;; buf pos:
2758 ;; 123456789 buffer-undo-list undo-deltas
2759 ;; --------- ---------------- -----------
2760 ;; [...]
2761 ;; abbaa (2 . 4) (2 . -2)
2762 ;; aaa ("bb" . 2) (2 . 2)
2763 ;; [...]
2765 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2766 ;; undo. Further adjustments to such an element should be the same as
2767 ;; for (TEXT . POSITION) elements. The options are:
2769 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2770 ;; analogous to marker insertion-type t.
2772 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2773 ;; marker insertion-type nil.
2775 ;; There was no strong reason to prefer one or the other, except that
2776 ;; the first is more consistent with prior undo in region behavior.
2777 (defun undo-adjust-beg-end (beg end deltas)
2778 "Return cons of adjustments to BEG and END by the undo DELTAS
2779 list."
2780 (let ((adj-beg (undo-adjust-pos beg deltas)))
2781 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2782 (cons adj-beg
2783 (max adj-beg (undo-adjust-pos end deltas t)))))
2785 (defun undo-adjust-pos (pos deltas &optional use-<)
2786 "Return adjustment of POS by the undo DELTAS list, comparing
2787 with < or <= based on USE-<."
2788 (dolist (d deltas pos)
2789 (when (if use-<
2790 (< (car d) pos)
2791 (<= (car d) pos))
2792 (setq pos
2793 ;; Don't allow pos to become less than the undo-delta
2794 ;; position. This edge case is described in the overview
2795 ;; comments.
2796 (max (car d) (- pos (cdr d)))))))
2798 ;; Return the first affected buffer position and the delta for an undo element
2799 ;; delta is defined as the change in subsequent buffer positions if we *did*
2800 ;; the undo.
2801 (defun undo-delta (undo-elt)
2802 (if (consp undo-elt)
2803 (cond ((stringp (car undo-elt))
2804 ;; (TEXT . POSITION)
2805 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2806 ((integerp (car undo-elt))
2807 ;; (BEGIN . END)
2808 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2810 '(0 . 0)))
2811 '(0 . 0)))
2813 ;;; Default undo-boundary addition
2815 ;; This section adds a new undo-boundary at either after a command is
2816 ;; called or in some cases on a timer called after a change is made in
2817 ;; any buffer.
2818 (defvar-local undo-auto--last-boundary-cause nil
2819 "Describe the cause of the last undo-boundary.
2821 If `explicit', the last boundary was caused by an explicit call to
2822 `undo-boundary', that is one not called by the code in this
2823 section.
2825 If it is equal to `timer', then the last boundary was inserted
2826 by `undo-auto--boundary-timer'.
2828 If it is equal to `command', then the last boundary was inserted
2829 automatically after a command, that is by the code defined in
2830 this section.
2832 If it is equal to a list, then the last boundary was inserted by
2833 an amalgamating command. The car of the list is the number of
2834 times an amalgamating command has been called, and the cdr are the
2835 buffers that were changed during the last command.")
2837 (defvar undo-auto-current-boundary-timer nil
2838 "Current timer which will run `undo-auto--boundary-timer' or nil.
2840 If set to non-nil, this will effectively disable the timer.")
2842 (defvar undo-auto--this-command-amalgamating nil
2843 "Non-nil if `this-command' should be amalgamated.
2844 This variable is set to nil by `undo-auto--boundaries' and is set
2845 by `undo-auto-amalgamate'." )
2847 (defun undo-auto--needs-boundary-p ()
2848 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2849 (car-safe buffer-undo-list))
2851 (defun undo-auto--last-boundary-amalgamating-number ()
2852 "Return the number of amalgamating last commands or nil.
2853 Amalgamating commands are, by default, either
2854 `self-insert-command' and `delete-char', but can be any command
2855 that calls `undo-auto-amalgamate'."
2856 (car-safe undo-auto--last-boundary-cause))
2858 (defun undo-auto--ensure-boundary (cause)
2859 "Add an `undo-boundary' to the current buffer if needed.
2860 REASON describes the reason that the boundary is being added; see
2861 `undo-auto--last-boundary' for more information."
2862 (when (and
2863 (undo-auto--needs-boundary-p))
2864 (let ((last-amalgamating
2865 (undo-auto--last-boundary-amalgamating-number)))
2866 (undo-boundary)
2867 (setq undo-auto--last-boundary-cause
2868 (if (eq 'amalgamate cause)
2869 (cons
2870 (if last-amalgamating (1+ last-amalgamating) 0)
2871 undo-auto--undoably-changed-buffers)
2872 cause)))))
2874 (defun undo-auto--boundaries (cause)
2875 "Check recently changed buffers and add a boundary if necessary.
2876 REASON describes the reason that the boundary is being added; see
2877 `undo-last-boundary' for more information."
2878 (dolist (b undo-auto--undoably-changed-buffers)
2879 (when (buffer-live-p b)
2880 (with-current-buffer b
2881 (undo-auto--ensure-boundary cause))))
2882 (setq undo-auto--undoably-changed-buffers nil))
2884 (defun undo-auto--boundary-timer ()
2885 "Timer which will run `undo--auto-boundary-timer'."
2886 (setq undo-auto-current-boundary-timer nil)
2887 (undo-auto--boundaries 'timer))
2889 (defun undo-auto--boundary-ensure-timer ()
2890 "Ensure that the `undo-auto-boundary-timer' is set."
2891 (unless undo-auto-current-boundary-timer
2892 (setq undo-auto-current-boundary-timer
2893 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2895 (defvar undo-auto--undoably-changed-buffers nil
2896 "List of buffers that have changed recently.
2898 This list is maintained by `undo-auto--undoable-change' and
2899 `undo-auto--boundaries' and can be affected by changes to their
2900 default values.")
2902 (defun undo-auto--add-boundary ()
2903 "Add an `undo-boundary' in appropriate buffers."
2904 (undo-auto--boundaries
2905 (let ((amal undo-auto--this-command-amalgamating))
2906 (setq undo-auto--this-command-amalgamating nil)
2907 (if amal
2908 'amalgamate
2909 'command))))
2911 (defun undo-auto-amalgamate ()
2912 "Amalgamate undo if necessary.
2913 This function can be called before an amalgamating command. It
2914 removes the previous `undo-boundary' if a series of such calls
2915 have been made. By default `self-insert-command' and
2916 `delete-char' are the only amalgamating commands, although this
2917 function could be called by any command wishing to have this
2918 behavior."
2919 (let ((last-amalgamating-count
2920 (undo-auto--last-boundary-amalgamating-number)))
2921 (setq undo-auto--this-command-amalgamating t)
2922 (when
2923 last-amalgamating-count
2925 (and
2926 (< last-amalgamating-count 20)
2927 (eq this-command last-command))
2928 ;; Amalgamate all buffers that have changed.
2929 (dolist (b (cdr undo-auto--last-boundary-cause))
2930 (when (buffer-live-p b)
2931 (with-current-buffer
2933 (when
2934 ;; The head of `buffer-undo-list' is nil.
2935 ;; `car-safe' doesn't work because
2936 ;; `buffer-undo-list' need not be a list!
2937 (and (listp buffer-undo-list)
2938 (not (car buffer-undo-list)))
2939 (setq buffer-undo-list
2940 (cdr buffer-undo-list))))))
2941 (setq undo-auto--last-boundary-cause 0)))))
2943 ;; This function is called also from one place in fileio.c. We call
2944 ;; this function, rather than undoable-change because it reduces the
2945 ;; number of lisp functions we have to use fboundp for to avoid
2946 ;; bootstrap issues.
2947 (defun undo-auto--undoable-change-no-timer ()
2948 "Record `current-buffer' as changed."
2949 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2951 (defun undo-auto--undoable-change ()
2952 "Called after every undoable buffer change."
2953 (undo-auto--undoable-change-no-timer)
2954 (undo-auto--boundary-ensure-timer))
2955 ;; End auto-boundary section
2957 (defcustom undo-ask-before-discard nil
2958 "If non-nil ask about discarding undo info for the current command.
2959 Normally, Emacs discards the undo info for the current command if
2960 it exceeds `undo-outer-limit'. But if you set this option
2961 non-nil, it asks in the echo area whether to discard the info.
2962 If you answer no, there is a slight risk that Emacs might crash, so
2963 only do it if you really want to undo the command.
2965 This option is mainly intended for debugging. You have to be
2966 careful if you use it for other purposes. Garbage collection is
2967 inhibited while the question is asked, meaning that Emacs might
2968 leak memory. So you should make sure that you do not wait
2969 excessively long before answering the question."
2970 :type 'boolean
2971 :group 'undo
2972 :version "22.1")
2974 (defvar undo-extra-outer-limit nil
2975 "If non-nil, an extra level of size that's ok in an undo item.
2976 We don't ask the user about truncating the undo list until the
2977 current item gets bigger than this amount.
2979 This variable only matters if `undo-ask-before-discard' is non-nil.")
2980 (make-variable-buffer-local 'undo-extra-outer-limit)
2982 ;; When the first undo batch in an undo list is longer than
2983 ;; undo-outer-limit, this function gets called to warn the user that
2984 ;; the undo info for the current command was discarded. Garbage
2985 ;; collection is inhibited around the call, so it had better not do a
2986 ;; lot of consing.
2987 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
2988 (defun undo-outer-limit-truncate (size)
2989 (if undo-ask-before-discard
2990 (when (or (null undo-extra-outer-limit)
2991 (> size undo-extra-outer-limit))
2992 ;; Don't ask the question again unless it gets even bigger.
2993 ;; This applies, in particular, if the user quits from the question.
2994 ;; Such a quit quits out of GC, but something else will call GC
2995 ;; again momentarily. It will call this function again,
2996 ;; but we don't want to ask the question again.
2997 (setq undo-extra-outer-limit (+ size 50000))
2998 (if (let (use-dialog-box track-mouse executing-kbd-macro )
2999 (yes-or-no-p (format-message
3000 "Buffer `%s' undo info is %d bytes long; discard it? "
3001 (buffer-name) size)))
3002 (progn (setq buffer-undo-list nil)
3003 (setq undo-extra-outer-limit nil)
3005 nil))
3006 (display-warning '(undo discard-info)
3007 (concat
3008 (format-message
3009 "Buffer `%s' undo info was %d bytes long.\n"
3010 (buffer-name) size)
3011 "The undo info was discarded because it exceeded \
3012 `undo-outer-limit'.
3014 This is normal if you executed a command that made a huge change
3015 to the buffer. In that case, to prevent similar problems in the
3016 future, set `undo-outer-limit' to a value that is large enough to
3017 cover the maximum size of normal changes you expect a single
3018 command to make, but not so large that it might exceed the
3019 maximum memory allotted to Emacs.
3021 If you did not execute any such command, the situation is
3022 probably due to a bug and you should report it.
3024 You can disable the popping up of this buffer by adding the entry
3025 \(undo discard-info) to the user option `warning-suppress-types',
3026 which is defined in the `warnings' library.\n")
3027 :warning)
3028 (setq buffer-undo-list nil)
3031 (defcustom password-word-equivalents
3032 '("password" "passcode" "passphrase" "pass phrase"
3033 ; These are sorted according to the GNU en_US locale.
3034 "암호" ; ko
3035 "パスワード" ; ja
3036 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3037 "ពាក្យសម្ងាត់" ; km
3038 "adgangskode" ; da
3039 "contraseña" ; es
3040 "contrasenya" ; ca
3041 "geslo" ; sl
3042 "hasło" ; pl
3043 "heslo" ; cs, sk
3044 "iphasiwedi" ; zu
3045 "jelszó" ; hu
3046 "lösenord" ; sv
3047 "lozinka" ; hr, sr
3048 "mật khẩu" ; vi
3049 "mot de passe" ; fr
3050 "parola" ; tr
3051 "pasahitza" ; eu
3052 "passord" ; nb
3053 "passwort" ; de
3054 "pasvorto" ; eo
3055 "salasana" ; fi
3056 "senha" ; pt
3057 "slaptažodis" ; lt
3058 "wachtwoord" ; nl
3059 "كلمة السر" ; ar
3060 "ססמה" ; he
3061 "лозинка" ; sr
3062 "пароль" ; kk, ru, uk
3063 "गुप्तशब्द" ; mr
3064 "शब्दकूट" ; hi
3065 "પાસવર્ડ" ; gu
3066 "సంకేతపదము" ; te
3067 "ਪਾਸਵਰਡ" ; pa
3068 "ಗುಪ್ತಪದ" ; kn
3069 "கடவுச்சொல்" ; ta
3070 "അടയാളവാക്ക്" ; ml
3071 "গুপ্তশব্দ" ; as
3072 "পাসওয়ার্ড" ; bn_IN
3073 "රහස්පදය" ; si
3074 "密码" ; zh_CN
3075 "密碼" ; zh_TW
3077 "List of words equivalent to \"password\".
3078 This is used by Shell mode and other parts of Emacs to recognize
3079 password prompts, including prompts in languages other than
3080 English. Different case choices should not be assumed to be
3081 included; callers should bind `case-fold-search' to t."
3082 :type '(repeat string)
3083 :version "24.4"
3084 :group 'processes)
3086 (defvar shell-command-history nil
3087 "History list for some commands that read shell commands.
3089 Maximum length of the history list is determined by the value
3090 of `history-length', which see.")
3092 (defvar shell-command-switch (purecopy "-c")
3093 "Switch used to have the shell execute its command line argument.")
3095 (defvar shell-command-default-error-buffer nil
3096 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3097 This buffer is used when `shell-command' or `shell-command-on-region'
3098 is run interactively. A value of nil means that output to stderr and
3099 stdout will be intermixed in the output stream.")
3101 (declare-function mailcap-file-default-commands "mailcap" (files))
3102 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3104 (defun minibuffer-default-add-shell-commands ()
3105 "Return a list of all commands associated with the current file.
3106 This function is used to add all related commands retrieved by `mailcap'
3107 to the end of the list of defaults just after the default value."
3108 (interactive)
3109 (let* ((filename (if (listp minibuffer-default)
3110 (car minibuffer-default)
3111 minibuffer-default))
3112 (commands (and filename (require 'mailcap nil t)
3113 (mailcap-file-default-commands (list filename)))))
3114 (setq commands (mapcar (lambda (command)
3115 (concat command " " filename))
3116 commands))
3117 (if (listp minibuffer-default)
3118 (append minibuffer-default commands)
3119 (cons minibuffer-default commands))))
3121 (declare-function shell-completion-vars "shell" ())
3123 (defvar minibuffer-local-shell-command-map
3124 (let ((map (make-sparse-keymap)))
3125 (set-keymap-parent map minibuffer-local-map)
3126 (define-key map "\t" 'completion-at-point)
3127 map)
3128 "Keymap used for completing shell commands in minibuffer.")
3130 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3131 "Read a shell command from the minibuffer.
3132 The arguments are the same as the ones of `read-from-minibuffer',
3133 except READ and KEYMAP are missing and HIST defaults
3134 to `shell-command-history'."
3135 (require 'shell)
3136 (minibuffer-with-setup-hook
3137 (lambda ()
3138 (shell-completion-vars)
3139 (set (make-local-variable 'minibuffer-default-add-function)
3140 'minibuffer-default-add-shell-commands))
3141 (apply 'read-from-minibuffer prompt initial-contents
3142 minibuffer-local-shell-command-map
3144 (or hist 'shell-command-history)
3145 args)))
3147 (defcustom async-shell-command-buffer 'confirm-new-buffer
3148 "What to do when the output buffer is used by another shell command.
3149 This option specifies how to resolve the conflict where a new command
3150 wants to direct its output to the buffer `*Async Shell Command*',
3151 but this buffer is already taken by another running shell command.
3153 The value `confirm-kill-process' is used to ask for confirmation before
3154 killing the already running process and running a new process
3155 in the same buffer, `confirm-new-buffer' for confirmation before running
3156 the command in a new buffer with a name other than the default buffer name,
3157 `new-buffer' for doing the same without confirmation,
3158 `confirm-rename-buffer' for confirmation before renaming the existing
3159 output buffer and running a new command in the default buffer,
3160 `rename-buffer' for doing the same without confirmation."
3161 :type '(choice (const :tag "Confirm killing of running command"
3162 confirm-kill-process)
3163 (const :tag "Confirm creation of a new buffer"
3164 confirm-new-buffer)
3165 (const :tag "Create a new buffer"
3166 new-buffer)
3167 (const :tag "Confirm renaming of existing buffer"
3168 confirm-rename-buffer)
3169 (const :tag "Rename the existing buffer"
3170 rename-buffer))
3171 :group 'shell
3172 :version "24.3")
3174 (defun async-shell-command (command &optional output-buffer error-buffer)
3175 "Execute string COMMAND asynchronously in background.
3177 Like `shell-command', but adds `&' at the end of COMMAND
3178 to execute it asynchronously.
3180 The output appears in the buffer `*Async Shell Command*'.
3181 That buffer is in shell mode.
3183 You can configure `async-shell-command-buffer' to specify what to do in
3184 case when `*Async Shell Command*' buffer is already taken by another
3185 running shell command. To run COMMAND without displaying the output
3186 in a window you can configure `display-buffer-alist' to use the action
3187 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3189 In Elisp, you will often be better served by calling `start-process'
3190 directly, since it offers more control and does not impose the use of a
3191 shell (with its need to quote arguments)."
3192 (interactive
3193 (list
3194 (read-shell-command "Async shell command: " nil nil
3195 (let ((filename
3196 (cond
3197 (buffer-file-name)
3198 ((eq major-mode 'dired-mode)
3199 (dired-get-filename nil t)))))
3200 (and filename (file-relative-name filename))))
3201 current-prefix-arg
3202 shell-command-default-error-buffer))
3203 (unless (string-match "&[ \t]*\\'" command)
3204 (setq command (concat command " &")))
3205 (shell-command command output-buffer error-buffer))
3207 (defun shell-command (command &optional output-buffer error-buffer)
3208 "Execute string COMMAND in inferior shell; display output, if any.
3209 With prefix argument, insert the COMMAND's output at point.
3211 Interactively, prompt for COMMAND in the minibuffer.
3213 If COMMAND ends in `&', execute it asynchronously.
3214 The output appears in the buffer `*Async Shell Command*'.
3215 That buffer is in shell mode. You can also use
3216 `async-shell-command' that automatically adds `&'.
3218 Otherwise, COMMAND is executed synchronously. The output appears in
3219 the buffer `*Shell Command Output*'. If the output is short enough to
3220 display in the echo area (which is determined by the variables
3221 `resize-mini-windows' and `max-mini-window-height'), it is shown
3222 there, but it is nonetheless available in buffer `*Shell Command
3223 Output*' even though that buffer is not automatically displayed.
3225 To specify a coding system for converting non-ASCII characters
3226 in the shell command output, use \\[universal-coding-system-argument] \
3227 before this command.
3229 Noninteractive callers can specify coding systems by binding
3230 `coding-system-for-read' and `coding-system-for-write'.
3232 The optional second argument OUTPUT-BUFFER, if non-nil,
3233 says to put the output in some other buffer.
3234 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
3235 If OUTPUT-BUFFER is not a buffer and not nil,
3236 insert output in current buffer. (This cannot be done asynchronously.)
3237 In either case, the buffer is first erased, and the output is
3238 inserted after point (leaving mark after it).
3240 If the command terminates without error, but generates output,
3241 and you did not specify \"insert it in the current buffer\",
3242 the output can be displayed in the echo area or in its buffer.
3243 If the output is short enough to display in the echo area
3244 \(determined by the variable `max-mini-window-height' if
3245 `resize-mini-windows' is non-nil), it is shown there.
3246 Otherwise,the buffer containing the output is displayed.
3248 If there is output and an error, and you did not specify \"insert it
3249 in the current buffer\", a message about the error goes at the end
3250 of the output.
3252 If there is no output, or if output is inserted in the current buffer,
3253 then `*Shell Command Output*' is deleted.
3255 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3256 or buffer name to which to direct the command's standard error output.
3257 If it is nil, error output is mingled with regular output.
3258 In an interactive call, the variable `shell-command-default-error-buffer'
3259 specifies the value of ERROR-BUFFER.
3261 In Elisp, you will often be better served by calling `call-process' or
3262 `start-process' directly, since it offers more control and does not impose
3263 the use of a shell (with its need to quote arguments)."
3265 (interactive
3266 (list
3267 (read-shell-command "Shell command: " nil nil
3268 (let ((filename
3269 (cond
3270 (buffer-file-name)
3271 ((eq major-mode 'dired-mode)
3272 (dired-get-filename nil t)))))
3273 (and filename (file-relative-name filename))))
3274 current-prefix-arg
3275 shell-command-default-error-buffer))
3276 ;; Look for a handler in case default-directory is a remote file name.
3277 (let ((handler
3278 (find-file-name-handler (directory-file-name default-directory)
3279 'shell-command)))
3280 (if handler
3281 (funcall handler 'shell-command command output-buffer error-buffer)
3282 (if (and output-buffer
3283 (not (or (bufferp output-buffer) (stringp output-buffer))))
3284 ;; Output goes in current buffer.
3285 (let ((error-file
3286 (if error-buffer
3287 (make-temp-file
3288 (expand-file-name "scor"
3289 (or small-temporary-file-directory
3290 temporary-file-directory)))
3291 nil)))
3292 (barf-if-buffer-read-only)
3293 (push-mark nil t)
3294 ;; We do not use -f for csh; we will not support broken use of
3295 ;; .cshrcs. Even the BSD csh manual says to use
3296 ;; "if ($?prompt) exit" before things which are not useful
3297 ;; non-interactively. Besides, if someone wants their other
3298 ;; aliases for shell commands then they can still have them.
3299 (call-process shell-file-name nil
3300 (if error-file
3301 (list t error-file)
3303 nil shell-command-switch command)
3304 (when (and error-file (file-exists-p error-file))
3305 (if (< 0 (nth 7 (file-attributes error-file)))
3306 (with-current-buffer (get-buffer-create error-buffer)
3307 (let ((pos-from-end (- (point-max) (point))))
3308 (or (bobp)
3309 (insert "\f\n"))
3310 ;; Do no formatting while reading error file,
3311 ;; because that can run a shell command, and we
3312 ;; don't want that to cause an infinite recursion.
3313 (format-insert-file error-file nil)
3314 ;; Put point after the inserted errors.
3315 (goto-char (- (point-max) pos-from-end)))
3316 (display-buffer (current-buffer))))
3317 (delete-file error-file))
3318 ;; This is like exchange-point-and-mark, but doesn't
3319 ;; activate the mark. It is cleaner to avoid activation,
3320 ;; even though the command loop would deactivate the mark
3321 ;; because we inserted text.
3322 (goto-char (prog1 (mark t)
3323 (set-marker (mark-marker) (point)
3324 (current-buffer)))))
3325 ;; Output goes in a separate buffer.
3326 ;; Preserve the match data in case called from a program.
3327 (save-match-data
3328 (if (string-match "[ \t]*&[ \t]*\\'" command)
3329 ;; Command ending with ampersand means asynchronous.
3330 (let ((buffer (get-buffer-create
3331 (or output-buffer "*Async Shell Command*")))
3332 (directory default-directory)
3333 proc)
3334 ;; Remove the ampersand.
3335 (setq command (substring command 0 (match-beginning 0)))
3336 ;; Ask the user what to do with already running process.
3337 (setq proc (get-buffer-process buffer))
3338 (when proc
3339 (cond
3340 ((eq async-shell-command-buffer 'confirm-kill-process)
3341 ;; If will kill a process, query first.
3342 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3343 (kill-process proc)
3344 (error "Shell command in progress")))
3345 ((eq async-shell-command-buffer 'confirm-new-buffer)
3346 ;; If will create a new buffer, query first.
3347 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3348 (setq buffer (generate-new-buffer
3349 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3350 output-buffer "*Async Shell Command*")))
3351 (error "Shell command in progress")))
3352 ((eq async-shell-command-buffer 'new-buffer)
3353 ;; It will create a new buffer.
3354 (setq buffer (generate-new-buffer
3355 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3356 output-buffer "*Async Shell Command*"))))
3357 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3358 ;; If will rename the buffer, query first.
3359 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3360 (progn
3361 (with-current-buffer buffer
3362 (rename-uniquely))
3363 (setq buffer (get-buffer-create
3364 (or output-buffer "*Async Shell Command*"))))
3365 (error "Shell command in progress")))
3366 ((eq async-shell-command-buffer 'rename-buffer)
3367 ;; It will rename the buffer.
3368 (with-current-buffer buffer
3369 (rename-uniquely))
3370 (setq buffer (get-buffer-create
3371 (or output-buffer "*Async Shell Command*"))))))
3372 (with-current-buffer buffer
3373 (setq buffer-read-only nil)
3374 ;; Setting buffer-read-only to nil doesn't suffice
3375 ;; if some text has a non-nil read-only property,
3376 ;; which comint sometimes adds for prompts.
3377 (let ((inhibit-read-only t))
3378 (erase-buffer))
3379 (display-buffer buffer '(nil (allow-no-window . t)))
3380 (setq default-directory directory)
3381 (setq proc (start-process "Shell" buffer shell-file-name
3382 shell-command-switch command))
3383 (setq mode-line-process '(":%s"))
3384 (require 'shell) (shell-mode)
3385 (set-process-sentinel proc 'shell-command-sentinel)
3386 ;; Use the comint filter for proper handling of carriage motion
3387 ;; (see `comint-inhibit-carriage-motion'),.
3388 (set-process-filter proc 'comint-output-filter)
3390 ;; Otherwise, command is executed synchronously.
3391 (shell-command-on-region (point) (point) command
3392 output-buffer nil error-buffer)))))))
3394 (defun display-message-or-buffer (message &optional buffer-name action frame)
3395 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3396 MESSAGE may be either a string or a buffer.
3398 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3399 for maximum height of the echo area, as defined by `max-mini-window-height'
3400 if `resize-mini-windows' is non-nil.
3402 Returns either the string shown in the echo area, or when a pop-up
3403 buffer is used, the window used to display it.
3405 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3406 name of the buffer used to display it in the case where a pop-up buffer
3407 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3408 string and it is displayed in the echo area, it is not specified whether
3409 the contents are inserted into the buffer anyway.
3411 Optional arguments ACTION and FRAME are as for `display-buffer',
3412 and are only used if a pop-up buffer is displayed."
3413 (cond ((and (stringp message) (not (string-match "\n" message)))
3414 ;; Trivial case where we can use the echo area
3415 (message "%s" message))
3416 ((and (stringp message)
3417 (= (string-match "\n" message) (1- (length message))))
3418 ;; Trivial case where we can just remove single trailing newline
3419 (message "%s" (substring message 0 (1- (length message)))))
3421 ;; General case
3422 (with-current-buffer
3423 (if (bufferp message)
3424 message
3425 (get-buffer-create (or buffer-name "*Message*")))
3427 (unless (bufferp message)
3428 (erase-buffer)
3429 (insert message))
3431 (let ((lines
3432 (if (= (buffer-size) 0)
3434 (count-screen-lines nil nil nil (minibuffer-window)))))
3435 (cond ((= lines 0))
3436 ((and (or (<= lines 1)
3437 (<= lines
3438 (if resize-mini-windows
3439 (cond ((floatp max-mini-window-height)
3440 (* (frame-height)
3441 max-mini-window-height))
3442 ((integerp max-mini-window-height)
3443 max-mini-window-height)
3446 1)))
3447 ;; Don't use the echo area if the output buffer is
3448 ;; already displayed in the selected frame.
3449 (not (get-buffer-window (current-buffer))))
3450 ;; Echo area
3451 (goto-char (point-max))
3452 (when (bolp)
3453 (backward-char 1))
3454 (message "%s" (buffer-substring (point-min) (point))))
3456 ;; Buffer
3457 (goto-char (point-min))
3458 (display-buffer (current-buffer) action frame))))))))
3461 ;; We have a sentinel to prevent insertion of a termination message
3462 ;; in the buffer itself.
3463 (defun shell-command-sentinel (process signal)
3464 (if (memq (process-status process) '(exit signal))
3465 (message "%s: %s."
3466 (car (cdr (cdr (process-command process))))
3467 (substring signal 0 -1))))
3469 (defun shell-command-on-region (start end command
3470 &optional output-buffer replace
3471 error-buffer display-error-buffer
3472 region-noncontiguous-p)
3473 "Execute string COMMAND in inferior shell with region as input.
3474 Normally display output (if any) in temp buffer `*Shell Command Output*';
3475 Prefix arg means replace the region with it. Return the exit code of
3476 COMMAND.
3478 To specify a coding system for converting non-ASCII characters
3479 in the input and output to the shell command, use \\[universal-coding-system-argument]
3480 before this command. By default, the input (from the current buffer)
3481 is encoded using coding-system specified by `process-coding-system-alist',
3482 falling back to `default-process-coding-system' if no match for COMMAND
3483 is found in `process-coding-system-alist'.
3485 Noninteractive callers can specify coding systems by binding
3486 `coding-system-for-read' and `coding-system-for-write'.
3488 If the command generates output, the output may be displayed
3489 in the echo area or in a buffer.
3490 If the output is short enough to display in the echo area
3491 \(determined by the variable `max-mini-window-height' if
3492 `resize-mini-windows' is non-nil), it is shown there.
3493 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3494 The output is available in that buffer in both cases.
3496 If there is output and an error, a message about the error
3497 appears at the end of the output. If there is no output, or if
3498 output is inserted in the current buffer, the buffer `*Shell
3499 Command Output*' is deleted.
3501 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3502 command's output. If the value is a buffer or buffer name,
3503 put the output there. If the value is nil, use the buffer
3504 `*Shell Command Output*'. Any other value, excluding nil,
3505 means to insert the output in the current buffer. In either case,
3506 the output is inserted after point (leaving mark after it).
3508 Optional fifth arg REPLACE, if non-nil, means to insert the
3509 output in place of text from START to END, putting point and mark
3510 around it.
3512 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3513 or buffer name to which to direct the command's standard error
3514 output. If nil, error output is mingled with regular output.
3515 When called interactively, `shell-command-default-error-buffer'
3516 is used for ERROR-BUFFER.
3518 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3519 display the error buffer if there were any errors. When called
3520 interactively, this is t."
3521 (interactive (let (string)
3522 (unless (mark)
3523 (user-error "The mark is not set now, so there is no region"))
3524 ;; Do this before calling region-beginning
3525 ;; and region-end, in case subprocess output
3526 ;; relocates them while we are in the minibuffer.
3527 (setq string (read-shell-command "Shell command on region: "))
3528 ;; call-interactively recognizes region-beginning and
3529 ;; region-end specially, leaving them in the history.
3530 (list (region-beginning) (region-end)
3531 string
3532 current-prefix-arg
3533 current-prefix-arg
3534 shell-command-default-error-buffer
3536 (region-noncontiguous-p))))
3537 (let ((error-file
3538 (if error-buffer
3539 (make-temp-file
3540 (expand-file-name "scor"
3541 (or small-temporary-file-directory
3542 temporary-file-directory)))
3543 nil))
3544 exit-status)
3545 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3546 (if region-noncontiguous-p
3547 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3548 output)
3549 (with-temp-buffer
3550 (insert input)
3551 (call-process-region (point-min) (point-max)
3552 shell-file-name t t
3553 nil shell-command-switch
3554 command)
3555 (setq output (split-string (buffer-string) "\n")))
3556 (goto-char start)
3557 (funcall region-insert-function output))
3558 (if (or replace
3559 (and output-buffer
3560 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3561 ;; Replace specified region with output from command.
3562 (let ((swap (and replace (< start end))))
3563 ;; Don't muck with mark unless REPLACE says we should.
3564 (goto-char start)
3565 (and replace (push-mark (point) 'nomsg))
3566 (setq exit-status
3567 (call-process-region start end shell-file-name replace
3568 (if error-file
3569 (list t error-file)
3571 nil shell-command-switch command))
3572 ;; It is rude to delete a buffer which the command is not using.
3573 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3574 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3575 ;; (kill-buffer shell-buffer)))
3576 ;; Don't muck with mark unless REPLACE says we should.
3577 (and replace swap (exchange-point-and-mark)))
3578 ;; No prefix argument: put the output in a temp buffer,
3579 ;; replacing its entire contents.
3580 (let ((buffer (get-buffer-create
3581 (or output-buffer "*Shell Command Output*"))))
3582 (unwind-protect
3583 (if (eq buffer (current-buffer))
3584 ;; If the input is the same buffer as the output,
3585 ;; delete everything but the specified region,
3586 ;; then replace that region with the output.
3587 (progn (setq buffer-read-only nil)
3588 (delete-region (max start end) (point-max))
3589 (delete-region (point-min) (min start end))
3590 (setq exit-status
3591 (call-process-region (point-min) (point-max)
3592 shell-file-name t
3593 (if error-file
3594 (list t error-file)
3596 nil shell-command-switch
3597 command)))
3598 ;; Clear the output buffer, then run the command with
3599 ;; output there.
3600 (let ((directory default-directory))
3601 (with-current-buffer buffer
3602 (setq buffer-read-only nil)
3603 (if (not output-buffer)
3604 (setq default-directory directory))
3605 (erase-buffer)))
3606 (setq exit-status
3607 (call-process-region start end shell-file-name nil
3608 (if error-file
3609 (list buffer error-file)
3610 buffer)
3611 nil shell-command-switch command)))
3612 ;; Report the output.
3613 (with-current-buffer buffer
3614 (setq mode-line-process
3615 (cond ((null exit-status)
3616 " - Error")
3617 ((stringp exit-status)
3618 (format " - Signal [%s]" exit-status))
3619 ((not (equal 0 exit-status))
3620 (format " - Exit [%d]" exit-status)))))
3621 (if (with-current-buffer buffer (> (point-max) (point-min)))
3622 ;; There's some output, display it
3623 (display-message-or-buffer buffer)
3624 ;; No output; error?
3625 (let ((output
3626 (if (and error-file
3627 (< 0 (nth 7 (file-attributes error-file))))
3628 (format "some error output%s"
3629 (if shell-command-default-error-buffer
3630 (format " to the \"%s\" buffer"
3631 shell-command-default-error-buffer)
3632 ""))
3633 "no output")))
3634 (cond ((null exit-status)
3635 (message "(Shell command failed with error)"))
3636 ((equal 0 exit-status)
3637 (message "(Shell command succeeded with %s)"
3638 output))
3639 ((stringp exit-status)
3640 (message "(Shell command killed by signal %s)"
3641 exit-status))
3643 (message "(Shell command failed with code %d and %s)"
3644 exit-status output))))
3645 ;; Don't kill: there might be useful info in the undo-log.
3646 ;; (kill-buffer buffer)
3647 )))))
3649 (when (and error-file (file-exists-p error-file))
3650 (if (< 0 (nth 7 (file-attributes error-file)))
3651 (with-current-buffer (get-buffer-create error-buffer)
3652 (let ((pos-from-end (- (point-max) (point))))
3653 (or (bobp)
3654 (insert "\f\n"))
3655 ;; Do no formatting while reading error file,
3656 ;; because that can run a shell command, and we
3657 ;; don't want that to cause an infinite recursion.
3658 (format-insert-file error-file nil)
3659 ;; Put point after the inserted errors.
3660 (goto-char (- (point-max) pos-from-end)))
3661 (and display-error-buffer
3662 (display-buffer (current-buffer)))))
3663 (delete-file error-file))
3664 exit-status))
3666 (defun shell-command-to-string (command)
3667 "Execute shell command COMMAND and return its output as a string."
3668 (with-output-to-string
3669 (with-current-buffer
3670 standard-output
3671 (process-file shell-file-name nil t nil shell-command-switch command))))
3673 (defun process-file (program &optional infile buffer display &rest args)
3674 "Process files synchronously in a separate process.
3675 Similar to `call-process', but may invoke a file handler based on
3676 `default-directory'. The current working directory of the
3677 subprocess is `default-directory'.
3679 File names in INFILE and BUFFER are handled normally, but file
3680 names in ARGS should be relative to `default-directory', as they
3681 are passed to the process verbatim. (This is a difference to
3682 `call-process' which does not support file handlers for INFILE
3683 and BUFFER.)
3685 Some file handlers might not support all variants, for example
3686 they might behave as if DISPLAY was nil, regardless of the actual
3687 value passed."
3688 (let ((fh (find-file-name-handler default-directory 'process-file))
3689 lc stderr-file)
3690 (unwind-protect
3691 (if fh (apply fh 'process-file program infile buffer display args)
3692 (when infile (setq lc (file-local-copy infile)))
3693 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3694 (make-temp-file "emacs")))
3695 (prog1
3696 (apply 'call-process program
3697 (or lc infile)
3698 (if stderr-file (list (car buffer) stderr-file) buffer)
3699 display args)
3700 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3701 (when stderr-file (delete-file stderr-file))
3702 (when lc (delete-file lc)))))
3704 (defvar process-file-side-effects t
3705 "Whether a call of `process-file' changes remote files.
3707 By default, this variable is always set to t, meaning that a
3708 call of `process-file' could potentially change any file on a
3709 remote host. When set to nil, a file handler could optimize
3710 its behavior with respect to remote file attribute caching.
3712 You should only ever change this variable with a let-binding;
3713 never with `setq'.")
3715 (defun start-file-process (name buffer program &rest program-args)
3716 "Start a program in a subprocess. Return the process object for it.
3718 Similar to `start-process', but may invoke a file handler based on
3719 `default-directory'. See Info node `(elisp)Magic File Names'.
3721 This handler ought to run PROGRAM, perhaps on the local host,
3722 perhaps on a remote host that corresponds to `default-directory'.
3723 In the latter case, the local part of `default-directory' becomes
3724 the working directory of the process.
3726 PROGRAM and PROGRAM-ARGS might be file names. They are not
3727 objects of file handler invocation. File handlers might not
3728 support pty association, if PROGRAM is nil."
3729 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3730 (if fh (apply fh 'start-file-process name buffer program program-args)
3731 (apply 'start-process name buffer program program-args))))
3733 ;;;; Process menu
3735 (defvar tabulated-list-format)
3736 (defvar tabulated-list-entries)
3737 (defvar tabulated-list-sort-key)
3738 (declare-function tabulated-list-init-header "tabulated-list" ())
3739 (declare-function tabulated-list-print "tabulated-list"
3740 (&optional remember-pos update))
3742 (defvar process-menu-query-only nil)
3744 (defvar process-menu-mode-map
3745 (let ((map (make-sparse-keymap)))
3746 (define-key map [?d] 'process-menu-delete-process)
3747 map))
3749 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3750 "Major mode for listing the processes called by Emacs."
3751 (setq tabulated-list-format [("Process" 15 t)
3752 ("Status" 7 t)
3753 ("Buffer" 15 t)
3754 ("TTY" 12 t)
3755 ("Command" 0 t)])
3756 (make-local-variable 'process-menu-query-only)
3757 (setq tabulated-list-sort-key (cons "Process" nil))
3758 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3759 (tabulated-list-init-header))
3761 (defun process-menu-delete-process ()
3762 "Kill process at point in a `list-processes' buffer."
3763 (interactive)
3764 (delete-process (tabulated-list-get-id))
3765 (revert-buffer))
3767 (defun list-processes--refresh ()
3768 "Recompute the list of processes for the Process List buffer.
3769 Also, delete any process that is exited or signaled."
3770 (setq tabulated-list-entries nil)
3771 (dolist (p (process-list))
3772 (cond ((memq (process-status p) '(exit signal closed))
3773 (delete-process p))
3774 ((or (not process-menu-query-only)
3775 (process-query-on-exit-flag p))
3776 (let* ((buf (process-buffer p))
3777 (type (process-type p))
3778 (name (process-name p))
3779 (status (symbol-name (process-status p)))
3780 (buf-label (if (buffer-live-p buf)
3781 `(,(buffer-name buf)
3782 face link
3783 help-echo ,(format-message
3784 "Visit buffer `%s'"
3785 (buffer-name buf))
3786 follow-link t
3787 process-buffer ,buf
3788 action process-menu-visit-buffer)
3789 "--"))
3790 (tty (or (process-tty-name p) "--"))
3791 (cmd
3792 (if (memq type '(network serial))
3793 (let ((contact (process-contact p t)))
3794 (if (eq type 'network)
3795 (format "(%s %s)"
3796 (if (plist-get contact :type)
3797 "datagram"
3798 "network")
3799 (if (plist-get contact :server)
3800 (format "server on %s"
3802 (plist-get contact :host)
3803 (plist-get contact :local)))
3804 (format "connection to %s"
3805 (plist-get contact :host))))
3806 (format "(serial port %s%s)"
3807 (or (plist-get contact :port) "?")
3808 (let ((speed (plist-get contact :speed)))
3809 (if speed
3810 (format " at %s b/s" speed)
3811 "")))))
3812 (mapconcat 'identity (process-command p) " "))))
3813 (push (list p (vector name status buf-label tty cmd))
3814 tabulated-list-entries))))))
3816 (defun process-menu-visit-buffer (button)
3817 (display-buffer (button-get button 'process-buffer)))
3819 (defun list-processes (&optional query-only buffer)
3820 "Display a list of all processes that are Emacs sub-processes.
3821 If optional argument QUERY-ONLY is non-nil, only processes with
3822 the query-on-exit flag set are listed.
3823 Any process listed as exited or signaled is actually eliminated
3824 after the listing is made.
3825 Optional argument BUFFER specifies a buffer to use, instead of
3826 \"*Process List*\".
3827 The return value is always nil.
3829 This function lists only processes that were launched by Emacs. To
3830 see other processes running on the system, use `list-system-processes'."
3831 (interactive)
3832 (or (fboundp 'process-list)
3833 (error "Asynchronous subprocesses are not supported on this system"))
3834 (unless (bufferp buffer)
3835 (setq buffer (get-buffer-create "*Process List*")))
3836 (with-current-buffer buffer
3837 (process-menu-mode)
3838 (setq process-menu-query-only query-only)
3839 (list-processes--refresh)
3840 (tabulated-list-print))
3841 (display-buffer buffer)
3842 nil)
3844 ;;;; Prefix commands
3846 (setq prefix-command--needs-update nil)
3847 (setq prefix-command--last-echo nil)
3849 (defun internal-echo-keystrokes-prefix ()
3850 ;; BEWARE: Called directly from C code.
3851 ;; If the return value is non-nil, it means we are in the middle of
3852 ;; a command with prefix, such as a command invoked with prefix-arg.
3853 (if (not prefix-command--needs-update)
3854 prefix-command--last-echo
3855 (setq prefix-command--last-echo
3856 (let ((strs nil))
3857 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
3858 (lambda (fun) (push (funcall fun) strs)))
3859 (setq strs (delq nil strs))
3860 (when strs (mapconcat #'identity strs " "))))))
3862 (defvar prefix-command-echo-keystrokes-functions nil
3863 "Abnormal hook which constructs the description of the current prefix state.
3864 Each function is called with no argument, should return a string or nil.")
3866 (defun prefix-command-update ()
3867 "Update state of prefix commands.
3868 Call it whenever you change the \"prefix command state\"."
3869 (setq prefix-command--needs-update t))
3871 (defvar prefix-command-preserve-state-hook nil
3872 "Normal hook run when a command needs to preserve the prefix.")
3874 (defun prefix-command-preserve-state ()
3875 "Pass the current prefix command state to the next command.
3876 Should be called by all prefix commands.
3877 Runs `prefix-command-preserve-state-hook'."
3878 (run-hooks 'prefix-command-preserve-state-hook)
3879 ;; If the current command is a prefix command, we don't want the next (real)
3880 ;; command to have `last-command' set to, say, `universal-argument'.
3881 (setq this-command last-command)
3882 (setq real-this-command real-last-command)
3883 (prefix-command-update))
3885 (defun reset-this-command-lengths ()
3886 (declare (obsolete prefix-command-preserve-state "25.1"))
3887 nil)
3889 ;;;;; The main prefix command.
3891 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
3893 (add-hook 'prefix-command-echo-keystrokes-functions
3894 #'universal-argument--description)
3895 (defun universal-argument--description ()
3896 (when prefix-arg
3897 (concat "C-u"
3898 (pcase prefix-arg
3899 (`(-) " -")
3900 (`(,(and (pred integerp) n))
3901 (let ((str ""))
3902 (while (and (> n 4) (= (mod n 4) 0))
3903 (setq str (concat str " C-u"))
3904 (setq n (/ n 4)))
3905 (if (= n 4) str (format " %s" prefix-arg))))
3906 (_ (format " %s" prefix-arg))))))
3908 (add-hook 'prefix-command-preserve-state-hook
3909 #'universal-argument--preserve)
3910 (defun universal-argument--preserve ()
3911 (setq prefix-arg current-prefix-arg))
3913 (defvar universal-argument-map
3914 (let ((map (make-sparse-keymap))
3915 (universal-argument-minus
3916 ;; For backward compatibility, minus with no modifiers is an ordinary
3917 ;; command if digits have already been entered.
3918 `(menu-item "" negative-argument
3919 :filter ,(lambda (cmd)
3920 (if (integerp prefix-arg) nil cmd)))))
3921 (define-key map [switch-frame]
3922 (lambda (e) (interactive "e")
3923 (handle-switch-frame e) (universal-argument--mode)))
3924 (define-key map [?\C-u] 'universal-argument-more)
3925 (define-key map [?-] universal-argument-minus)
3926 (define-key map [?0] 'digit-argument)
3927 (define-key map [?1] 'digit-argument)
3928 (define-key map [?2] 'digit-argument)
3929 (define-key map [?3] 'digit-argument)
3930 (define-key map [?4] 'digit-argument)
3931 (define-key map [?5] 'digit-argument)
3932 (define-key map [?6] 'digit-argument)
3933 (define-key map [?7] 'digit-argument)
3934 (define-key map [?8] 'digit-argument)
3935 (define-key map [?9] 'digit-argument)
3936 (define-key map [kp-0] 'digit-argument)
3937 (define-key map [kp-1] 'digit-argument)
3938 (define-key map [kp-2] 'digit-argument)
3939 (define-key map [kp-3] 'digit-argument)
3940 (define-key map [kp-4] 'digit-argument)
3941 (define-key map [kp-5] 'digit-argument)
3942 (define-key map [kp-6] 'digit-argument)
3943 (define-key map [kp-7] 'digit-argument)
3944 (define-key map [kp-8] 'digit-argument)
3945 (define-key map [kp-9] 'digit-argument)
3946 (define-key map [kp-subtract] universal-argument-minus)
3947 map)
3948 "Keymap used while processing \\[universal-argument].")
3950 (defun universal-argument--mode ()
3951 (prefix-command-update)
3952 (set-transient-map universal-argument-map nil))
3954 (defun universal-argument ()
3955 "Begin a numeric argument for the following command.
3956 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3957 \\[universal-argument] following the digits or minus sign ends the argument.
3958 \\[universal-argument] without digits or minus sign provides 4 as argument.
3959 Repeating \\[universal-argument] without digits or minus sign
3960 multiplies the argument by 4 each time.
3961 For some commands, just \\[universal-argument] by itself serves as a flag
3962 which is different in effect from any particular numeric argument.
3963 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3964 (interactive)
3965 (prefix-command-preserve-state)
3966 (setq prefix-arg (list 4))
3967 (universal-argument--mode))
3969 (defun universal-argument-more (arg)
3970 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3971 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3972 (interactive "P")
3973 (prefix-command-preserve-state)
3974 (setq prefix-arg (if (consp arg)
3975 (list (* 4 (car arg)))
3976 (if (eq arg '-)
3977 (list -4)
3978 arg)))
3979 (when (consp prefix-arg) (universal-argument--mode)))
3981 (defun negative-argument (arg)
3982 "Begin a negative numeric argument for the next command.
3983 \\[universal-argument] following digits or minus sign ends the argument."
3984 (interactive "P")
3985 (prefix-command-preserve-state)
3986 (setq prefix-arg (cond ((integerp arg) (- arg))
3987 ((eq arg '-) nil)
3988 (t '-)))
3989 (universal-argument--mode))
3991 (defun digit-argument (arg)
3992 "Part of the numeric argument for the next command.
3993 \\[universal-argument] following digits or minus sign ends the argument."
3994 (interactive "P")
3995 (prefix-command-preserve-state)
3996 (let* ((char (if (integerp last-command-event)
3997 last-command-event
3998 (get last-command-event 'ascii-character)))
3999 (digit (- (logand char ?\177) ?0)))
4000 (setq prefix-arg (cond ((integerp arg)
4001 (+ (* arg 10)
4002 (if (< arg 0) (- digit) digit)))
4003 ((eq arg '-)
4004 ;; Treat -0 as just -, so that -01 will work.
4005 (if (zerop digit) '- (- digit)))
4007 digit))))
4008 (universal-argument--mode))
4011 (defvar filter-buffer-substring-functions nil
4012 "This variable is a wrapper hook around `buffer-substring--filter'.
4013 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4014 (make-obsolete-variable 'filter-buffer-substring-functions
4015 'filter-buffer-substring-function "24.4")
4017 (defvar filter-buffer-substring-function #'buffer-substring--filter
4018 "Function to perform the filtering in `filter-buffer-substring'.
4019 The function is called with the same 3 arguments (BEG END DELETE)
4020 that `filter-buffer-substring' received. It should return the
4021 buffer substring between BEG and END, after filtering. If DELETE is
4022 non-nil, it should delete the text between BEG and END from the buffer.")
4024 (defvar buffer-substring-filters nil
4025 "List of filter functions for `buffer-substring--filter'.
4026 Each function must accept a single argument, a string, and return a string.
4027 The buffer substring is passed to the first function in the list,
4028 and the return value of each function is passed to the next.
4029 As a special convention, point is set to the start of the buffer text
4030 being operated on (i.e., the first argument of `buffer-substring--filter')
4031 before these functions are called.")
4032 (make-obsolete-variable 'buffer-substring-filters
4033 'filter-buffer-substring-function "24.1")
4035 (defun filter-buffer-substring (beg end &optional delete)
4036 "Return the buffer substring between BEG and END, after filtering.
4037 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4039 This calls the function that `filter-buffer-substring-function' specifies
4040 \(passing the same three arguments that it received) to do the work,
4041 and returns whatever it does. The default function does no filtering,
4042 unless a hook has been set.
4044 Use `filter-buffer-substring' instead of `buffer-substring',
4045 `buffer-substring-no-properties', or `delete-and-extract-region' when
4046 you want to allow filtering to take place. For example, major or minor
4047 modes can use `filter-buffer-substring-function' to extract characters
4048 that are special to a buffer, and should not be copied into other buffers."
4049 (funcall filter-buffer-substring-function beg end delete))
4051 (defun buffer-substring--filter (beg end &optional delete)
4052 "Default function to use for `filter-buffer-substring-function'.
4053 Its arguments and return value are as specified for `filter-buffer-substring'.
4054 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4055 \(see `with-wrapper-hook' for details about wrapper hooks),
4056 and the abnormal hook `buffer-substring-filters'.
4057 No filtering is done unless a hook says to."
4058 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
4059 (cond
4060 ((or delete buffer-substring-filters)
4061 (save-excursion
4062 (goto-char beg)
4063 (let ((string (if delete (delete-and-extract-region beg end)
4064 (buffer-substring beg end))))
4065 (dolist (filter buffer-substring-filters)
4066 (setq string (funcall filter string)))
4067 string)))
4069 (buffer-substring beg end)))))
4072 ;;;; Window system cut and paste hooks.
4074 (defvar interprogram-cut-function #'gui-select-text
4075 "Function to call to make a killed region available to other programs.
4076 Most window systems provide a facility for cutting and pasting
4077 text between different programs, such as the clipboard on X and
4078 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4080 This variable holds a function that Emacs calls whenever text is
4081 put in the kill ring, to make the new kill available to other
4082 programs. The function takes one argument, TEXT, which is a
4083 string containing the text which should be made available.")
4085 (defvar interprogram-paste-function #'gui-selection-value
4086 "Function to call to get text cut from other programs.
4087 Most window systems provide a facility for cutting and pasting
4088 text between different programs, such as the clipboard on X and
4089 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4091 This variable holds a function that Emacs calls to obtain text
4092 that other programs have provided for pasting. The function is
4093 called with no arguments. If no other program has provided text
4094 to paste, the function should return nil (in which case the
4095 caller, usually `current-kill', should use the top of the Emacs
4096 kill ring). If another program has provided text to paste, the
4097 function should return that text as a string (in which case the
4098 caller should put this string in the kill ring as the latest
4099 kill).
4101 The function may also return a list of strings if the window
4102 system supports multiple selections. The first string will be
4103 used as the pasted text, but the other will be placed in the kill
4104 ring for easy access via `yank-pop'.
4106 Note that the function should return a string only if a program
4107 other than Emacs has provided a string for pasting; if Emacs
4108 provided the most recent string, the function should return nil.
4109 If it is difficult to tell whether Emacs or some other program
4110 provided the current string, it is probably good enough to return
4111 nil if the string is equal (according to `string=') to the last
4112 text Emacs provided.")
4116 ;;;; The kill ring data structure.
4118 (defvar kill-ring nil
4119 "List of killed text sequences.
4120 Since the kill ring is supposed to interact nicely with cut-and-paste
4121 facilities offered by window systems, use of this variable should
4122 interact nicely with `interprogram-cut-function' and
4123 `interprogram-paste-function'. The functions `kill-new',
4124 `kill-append', and `current-kill' are supposed to implement this
4125 interaction; you may want to use them instead of manipulating the kill
4126 ring directly.")
4128 (defcustom kill-ring-max 60
4129 "Maximum length of kill ring before oldest elements are thrown away."
4130 :type 'integer
4131 :group 'killing)
4133 (defvar kill-ring-yank-pointer nil
4134 "The tail of the kill ring whose car is the last thing yanked.")
4136 (defcustom save-interprogram-paste-before-kill nil
4137 "Save clipboard strings into kill ring before replacing them.
4138 When one selects something in another program to paste it into Emacs,
4139 but kills something in Emacs before actually pasting it,
4140 this selection is gone unless this variable is non-nil,
4141 in which case the other program's selection is saved in the `kill-ring'
4142 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4143 :type 'boolean
4144 :group 'killing
4145 :version "23.2")
4147 (defcustom kill-do-not-save-duplicates nil
4148 "Do not add a new string to `kill-ring' if it duplicates the last one.
4149 The comparison is done using `equal-including-properties'."
4150 :type 'boolean
4151 :group 'killing
4152 :version "23.2")
4154 (defun kill-new (string &optional replace)
4155 "Make STRING the latest kill in the kill ring.
4156 Set `kill-ring-yank-pointer' to point to it.
4157 If `interprogram-cut-function' is non-nil, apply it to STRING.
4158 Optional second argument REPLACE non-nil means that STRING will replace
4159 the front of the kill ring, rather than being added to the list.
4161 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4162 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4163 STRING.
4165 When the yank handler has a non-nil PARAM element, the original STRING
4166 argument is not used by `insert-for-yank'. However, since Lisp code
4167 may access and use elements from the kill ring directly, the STRING
4168 argument should still be a \"useful\" string for such uses."
4169 (unless (and kill-do-not-save-duplicates
4170 ;; Due to text properties such as 'yank-handler that
4171 ;; can alter the contents to yank, comparison using
4172 ;; `equal' is unsafe.
4173 (equal-including-properties string (car kill-ring)))
4174 (if (fboundp 'menu-bar-update-yank-menu)
4175 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4176 (when save-interprogram-paste-before-kill
4177 (let ((interprogram-paste (and interprogram-paste-function
4178 (funcall interprogram-paste-function))))
4179 (when interprogram-paste
4180 (dolist (s (if (listp interprogram-paste)
4181 (nreverse interprogram-paste)
4182 (list interprogram-paste)))
4183 (unless (and kill-do-not-save-duplicates
4184 (equal-including-properties s (car kill-ring)))
4185 (push s kill-ring))))))
4186 (unless (and kill-do-not-save-duplicates
4187 (equal-including-properties string (car kill-ring)))
4188 (if (and replace kill-ring)
4189 (setcar kill-ring string)
4190 (push string kill-ring)
4191 (if (> (length kill-ring) kill-ring-max)
4192 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4193 (setq kill-ring-yank-pointer kill-ring)
4194 (if interprogram-cut-function
4195 (funcall interprogram-cut-function string)))
4197 ;; It has been argued that this should work similar to `self-insert-command'
4198 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4199 (defcustom kill-append-merge-undo nil
4200 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4201 :type 'boolean
4202 :group 'killing
4203 :version "25.1")
4205 (defun kill-append (string before-p)
4206 "Append STRING to the end of the latest kill in the kill ring.
4207 If BEFORE-P is non-nil, prepend STRING to the kill.
4208 Also removes the last undo boundary in the current buffer,
4209 depending on `kill-append-merge-undo'.
4210 If `interprogram-cut-function' is set, pass the resulting kill to it."
4211 (let* ((cur (car kill-ring)))
4212 (kill-new (if before-p (concat string cur) (concat cur string))
4213 (or (= (length cur) 0)
4214 (equal nil (get-text-property 0 'yank-handler cur))))
4215 (when (and kill-append-merge-undo (not buffer-read-only))
4216 (let ((prev buffer-undo-list)
4217 (next (cdr buffer-undo-list)))
4218 ;; find the next undo boundary
4219 (while (car next)
4220 (pop next)
4221 (pop prev))
4222 ;; remove this undo boundary
4223 (when prev
4224 (setcdr prev (cdr next)))))))
4226 (defcustom yank-pop-change-selection nil
4227 "Whether rotating the kill ring changes the window system selection.
4228 If non-nil, whenever the kill ring is rotated (usually via the
4229 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4230 to copy the new kill to the window system selection."
4231 :type 'boolean
4232 :group 'killing
4233 :version "23.1")
4235 (defun current-kill (n &optional do-not-move)
4236 "Rotate the yanking point by N places, and then return that kill.
4237 If N is zero and `interprogram-paste-function' is set to a
4238 function that returns a string or a list of strings, and if that
4239 function doesn't return nil, then that string (or list) is added
4240 to the front of the kill ring and the string (or first string in
4241 the list) is returned as the latest kill.
4243 If N is not zero, and if `yank-pop-change-selection' is
4244 non-nil, use `interprogram-cut-function' to transfer the
4245 kill at the new yank point into the window system selection.
4247 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4248 move the yanking point; just return the Nth kill forward."
4250 (let ((interprogram-paste (and (= n 0)
4251 interprogram-paste-function
4252 (funcall interprogram-paste-function))))
4253 (if interprogram-paste
4254 (progn
4255 ;; Disable the interprogram cut function when we add the new
4256 ;; text to the kill ring, so Emacs doesn't try to own the
4257 ;; selection, with identical text.
4258 (let ((interprogram-cut-function nil))
4259 (if (listp interprogram-paste)
4260 (mapc 'kill-new (nreverse interprogram-paste))
4261 (kill-new interprogram-paste)))
4262 (car kill-ring))
4263 (or kill-ring (error "Kill ring is empty"))
4264 (let ((ARGth-kill-element
4265 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4266 (length kill-ring))
4267 kill-ring)))
4268 (unless do-not-move
4269 (setq kill-ring-yank-pointer ARGth-kill-element)
4270 (when (and yank-pop-change-selection
4271 (> n 0)
4272 interprogram-cut-function)
4273 (funcall interprogram-cut-function (car ARGth-kill-element))))
4274 (car ARGth-kill-element)))))
4278 ;;;; Commands for manipulating the kill ring.
4280 (defcustom kill-read-only-ok nil
4281 "Non-nil means don't signal an error for killing read-only text."
4282 :type 'boolean
4283 :group 'killing)
4285 (defun kill-region (beg end &optional region)
4286 "Kill (\"cut\") text between point and mark.
4287 This deletes the text from the buffer and saves it in the kill ring.
4288 The command \\[yank] can retrieve it from there.
4289 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4291 If you want to append the killed region to the last killed text,
4292 use \\[append-next-kill] before \\[kill-region].
4294 Any command that calls this function is a \"kill command\".
4295 If the previous command was also a kill command,
4296 the text killed this time appends to the text killed last time
4297 to make one entry in the kill ring.
4299 The killed text is filtered by `filter-buffer-substring' before it is
4300 saved in the kill ring, so the actual saved text might be different
4301 from what was killed.
4303 If the buffer is read-only, Emacs will beep and refrain from deleting
4304 the text, but put the text in the kill ring anyway. This means that
4305 you can use the killing commands to copy text from a read-only buffer.
4307 Lisp programs should use this function for killing text.
4308 (To delete text, use `delete-region'.)
4309 Supply two arguments, character positions BEG and END indicating the
4310 stretch of text to be killed. If the optional argument REGION is
4311 non-nil, the function ignores BEG and END, and kills the current
4312 region instead."
4313 ;; Pass mark first, then point, because the order matters when
4314 ;; calling `kill-append'.
4315 (interactive (list (mark) (point) 'region))
4316 (unless (and beg end)
4317 (user-error "The mark is not set now, so there is no region"))
4318 (condition-case nil
4319 (let ((string (if region
4320 (funcall region-extract-function 'delete)
4321 (filter-buffer-substring beg end 'delete))))
4322 (when string ;STRING is nil if BEG = END
4323 ;; Add that string to the kill ring, one way or another.
4324 (if (eq last-command 'kill-region)
4325 (kill-append string (< end beg))
4326 (kill-new string)))
4327 (when (or string (eq last-command 'kill-region))
4328 (setq this-command 'kill-region))
4329 (setq deactivate-mark t)
4330 nil)
4331 ((buffer-read-only text-read-only)
4332 ;; The code above failed because the buffer, or some of the characters
4333 ;; in the region, are read-only.
4334 ;; We should beep, in case the user just isn't aware of this.
4335 ;; However, there's no harm in putting
4336 ;; the region's text in the kill ring, anyway.
4337 (copy-region-as-kill beg end region)
4338 ;; Set this-command now, so it will be set even if we get an error.
4339 (setq this-command 'kill-region)
4340 ;; This should barf, if appropriate, and give us the correct error.
4341 (if kill-read-only-ok
4342 (progn (message "Read only text copied to kill ring") nil)
4343 ;; Signal an error if the buffer is read-only.
4344 (barf-if-buffer-read-only)
4345 ;; If the buffer isn't read-only, the text is.
4346 (signal 'text-read-only (list (current-buffer)))))))
4348 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4349 ;; to get two copies of the text when the user accidentally types M-w and
4350 ;; then corrects it with the intended C-w.
4351 (defun copy-region-as-kill (beg end &optional region)
4352 "Save the region as if killed, but don't kill it.
4353 In Transient Mark mode, deactivate the mark.
4354 If `interprogram-cut-function' is non-nil, also save the text for a window
4355 system cut and paste.
4357 The copied text is filtered by `filter-buffer-substring' before it is
4358 saved in the kill ring, so the actual saved text might be different
4359 from what was in the buffer.
4361 When called from Lisp, save in the kill ring the stretch of text
4362 between BEG and END, unless the optional argument REGION is
4363 non-nil, in which case ignore BEG and END, and save the current
4364 region instead.
4366 This command's old key binding has been given to `kill-ring-save'."
4367 ;; Pass mark first, then point, because the order matters when
4368 ;; calling `kill-append'.
4369 (interactive (list (mark) (point)
4370 (prefix-numeric-value current-prefix-arg)))
4371 (let ((str (if region
4372 (funcall region-extract-function nil)
4373 (filter-buffer-substring beg end))))
4374 (if (eq last-command 'kill-region)
4375 (kill-append str (< end beg))
4376 (kill-new str)))
4377 (setq deactivate-mark t)
4378 nil)
4380 (defun kill-ring-save (beg end &optional region)
4381 "Save the region as if killed, but don't kill it.
4382 In Transient Mark mode, deactivate the mark.
4383 If `interprogram-cut-function' is non-nil, also save the text for a window
4384 system cut and paste.
4386 If you want to append the killed line to the last killed text,
4387 use \\[append-next-kill] before \\[kill-ring-save].
4389 The copied text is filtered by `filter-buffer-substring' before it is
4390 saved in the kill ring, so the actual saved text might be different
4391 from what was in the buffer.
4393 When called from Lisp, save in the kill ring the stretch of text
4394 between BEG and END, unless the optional argument REGION is
4395 non-nil, in which case ignore BEG and END, and save the current
4396 region instead.
4398 This command is similar to `copy-region-as-kill', except that it gives
4399 visual feedback indicating the extent of the region being copied."
4400 ;; Pass mark first, then point, because the order matters when
4401 ;; calling `kill-append'.
4402 (interactive (list (mark) (point)
4403 (prefix-numeric-value current-prefix-arg)))
4404 (copy-region-as-kill beg end region)
4405 ;; This use of called-interactively-p is correct because the code it
4406 ;; controls just gives the user visual feedback.
4407 (if (called-interactively-p 'interactive)
4408 (indicate-copied-region)))
4410 (defun indicate-copied-region (&optional message-len)
4411 "Indicate that the region text has been copied interactively.
4412 If the mark is visible in the selected window, blink the cursor
4413 between point and mark if there is currently no active region
4414 highlighting.
4416 If the mark lies outside the selected window, display an
4417 informative message containing a sample of the copied text. The
4418 optional argument MESSAGE-LEN, if non-nil, specifies the length
4419 of this sample text; it defaults to 40."
4420 (let ((mark (mark t))
4421 (point (point))
4422 ;; Inhibit quitting so we can make a quit here
4423 ;; look like a C-g typed as a command.
4424 (inhibit-quit t))
4425 (if (pos-visible-in-window-p mark (selected-window))
4426 ;; Swap point-and-mark quickly so as to show the region that
4427 ;; was selected. Don't do it if the region is highlighted.
4428 (unless (and (region-active-p)
4429 (face-background 'region))
4430 ;; Swap point and mark.
4431 (set-marker (mark-marker) (point) (current-buffer))
4432 (goto-char mark)
4433 (sit-for blink-matching-delay)
4434 ;; Swap back.
4435 (set-marker (mark-marker) mark (current-buffer))
4436 (goto-char point)
4437 ;; If user quit, deactivate the mark
4438 ;; as C-g would as a command.
4439 (and quit-flag (region-active-p)
4440 (deactivate-mark)))
4441 (let ((len (min (abs (- mark point))
4442 (or message-len 40))))
4443 (if (< point mark)
4444 ;; Don't say "killed"; that is misleading.
4445 (message "Saved text until \"%s\""
4446 (buffer-substring-no-properties (- mark len) mark))
4447 (message "Saved text from \"%s\""
4448 (buffer-substring-no-properties mark (+ mark len))))))))
4450 (defun append-next-kill (&optional interactive)
4451 "Cause following command, if it kills, to add to previous kill.
4452 If the next command kills forward from point, the kill is
4453 appended to the previous killed text. If the command kills
4454 backward, the kill is prepended. Kill commands that act on the
4455 region, such as `kill-region', are regarded as killing forward if
4456 point is after mark, and killing backward if point is before
4457 mark.
4459 If the next command is not a kill command, `append-next-kill' has
4460 no effect.
4462 The argument is used for internal purposes; do not supply one."
4463 (interactive "p")
4464 ;; We don't use (interactive-p), since that breaks kbd macros.
4465 (if interactive
4466 (progn
4467 (setq this-command 'kill-region)
4468 (message "If the next command is a kill, it will append"))
4469 (setq last-command 'kill-region)))
4471 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4472 "Character set that matches bidirectional formatting control characters.")
4474 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4475 "Character set that matches any character except bidirectional controls.")
4477 (defun squeeze-bidi-context-1 (from to category replacement)
4478 "A subroutine of `squeeze-bidi-context'.
4479 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4480 (let ((pt (copy-marker from))
4481 (limit (copy-marker to))
4482 (old-pt 0)
4483 lim1)
4484 (setq lim1 limit)
4485 (goto-char pt)
4486 (while (< pt limit)
4487 (if (> pt old-pt)
4488 (move-marker lim1
4489 (save-excursion
4490 ;; L and R categories include embedding and
4491 ;; override controls, but we don't want to
4492 ;; replace them, because that might change
4493 ;; the visual order. Likewise with PDF and
4494 ;; isolate controls.
4495 (+ pt (skip-chars-forward
4496 bidi-directional-non-controls-chars
4497 limit)))))
4498 ;; Replace any run of non-RTL characters by a single LRM.
4499 (if (null (re-search-forward category lim1 t))
4500 ;; No more characters of CATEGORY, we are done.
4501 (setq pt limit)
4502 (replace-match replacement nil t)
4503 (move-marker pt (point)))
4504 (setq old-pt pt)
4505 ;; Skip directional controls, if any.
4506 (move-marker
4507 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4509 (defun squeeze-bidi-context (from to)
4510 "Replace characters between FROM and TO while keeping bidi context.
4512 This function replaces the region of text with as few characters
4513 as possible, while preserving the effect that region will have on
4514 bidirectional display before and after the region."
4515 (let ((start (set-marker (make-marker)
4516 (if (> from 0) from (+ (point-max) from))))
4517 (end (set-marker (make-marker) to))
4518 ;; This is for when they copy text with read-only text
4519 ;; properties.
4520 (inhibit-read-only t))
4521 (if (null (marker-position end))
4522 (setq end (point-max-marker)))
4523 ;; Replace each run of non-RTL characters with a single LRM.
4524 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4525 ;; Replace each run of non-LTR characters with a single RLM. Note
4526 ;; that the \cR category includes both the Arabic Letter (AL) and
4527 ;; R characters; here we ignore the distinction between them,
4528 ;; because that distinction only affects Arabic Number (AN)
4529 ;; characters, which are weak and don't affect the reordering.
4530 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4532 (defun line-substring-with-bidi-context (start end &optional no-properties)
4533 "Return buffer text between START and END with its bidi context.
4535 START and END are assumed to belong to the same physical line
4536 of buffer text. This function prepends and appends to the text
4537 between START and END bidi control characters that preserve the
4538 visual order of that text when it is inserted at some other place."
4539 (if (or (< start (point-min))
4540 (> end (point-max)))
4541 (signal 'args-out-of-range (list (current-buffer) start end)))
4542 (let ((buf (current-buffer))
4543 substr para-dir from to)
4544 (save-excursion
4545 (goto-char start)
4546 (setq para-dir (current-bidi-paragraph-direction))
4547 (setq from (line-beginning-position)
4548 to (line-end-position))
4549 (goto-char from)
4550 ;; If we don't have any mixed directional characters in the
4551 ;; entire line, we can just copy the substring without adding
4552 ;; any context.
4553 (if (or (looking-at-p "\\CR*$")
4554 (looking-at-p "\\CL*$"))
4555 (setq substr (if no-properties
4556 (buffer-substring-no-properties start end)
4557 (buffer-substring start end)))
4558 (setq substr
4559 (with-temp-buffer
4560 (if no-properties
4561 (insert-buffer-substring-no-properties buf from to)
4562 (insert-buffer-substring buf from to))
4563 (squeeze-bidi-context 1 (1+ (- start from)))
4564 (squeeze-bidi-context (- end to) nil)
4565 (buffer-substring 1 (point-max)))))
4567 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4568 ;; (1) force the string to have the same base embedding
4569 ;; direction as the paragraph direction at the source, no matter
4570 ;; what is the paragraph direction at destination; and (2) avoid
4571 ;; affecting the visual order of the surrounding text at
4572 ;; destination if there are characters of different
4573 ;; directionality there.
4574 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4575 substr "\x2069"))))
4577 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4578 "Return portion of current buffer between START and END with bidi context.
4580 This function works similar to `buffer-substring', but it prepends and
4581 appends to the text bidi directional control characters necessary to
4582 preserve the visual appearance of the text if it is inserted at another
4583 place. This is useful when the buffer substring includes bidirectional
4584 text and control characters that cause non-trivial reordering on display.
4585 If copied verbatim, such text can have a very different visual appearance,
4586 and can also change the visual appearance of the surrounding text at the
4587 destination of the copy.
4589 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4590 the text properties."
4591 (let (line-end substr)
4592 (if (or (< start (point-min))
4593 (> end (point-max)))
4594 (signal 'args-out-of-range (list (current-buffer) start end)))
4595 (save-excursion
4596 (goto-char start)
4597 (setq line-end (min end (line-end-position)))
4598 (while (< start end)
4599 (setq substr
4600 (concat substr
4601 (if substr "\n" "")
4602 (line-substring-with-bidi-context start line-end
4603 no-properties)))
4604 (forward-line 1)
4605 (setq start (point))
4606 (setq line-end (min end (line-end-position))))
4607 substr)))
4609 ;; Yanking.
4611 (defcustom yank-handled-properties
4612 '((font-lock-face . yank-handle-font-lock-face-property)
4613 (category . yank-handle-category-property))
4614 "List of special text property handling conditions for yanking.
4615 Each element should have the form (PROP . FUN), where PROP is a
4616 property symbol and FUN is a function. When the `yank' command
4617 inserts text into the buffer, it scans the inserted text for
4618 stretches of text that have `eq' values of the text property
4619 PROP; for each such stretch of text, FUN is called with three
4620 arguments: the property's value in that text, and the start and
4621 end positions of the text.
4623 This is done prior to removing the properties specified by
4624 `yank-excluded-properties'."
4625 :group 'killing
4626 :type '(repeat (cons (symbol :tag "property symbol")
4627 function))
4628 :version "24.3")
4630 ;; This is actually used in subr.el but defcustom does not work there.
4631 (defcustom yank-excluded-properties
4632 '(category field follow-link fontified font-lock-face help-echo
4633 intangible invisible keymap local-map mouse-face read-only
4634 yank-handler)
4635 "Text properties to discard when yanking.
4636 The value should be a list of text properties to discard or t,
4637 which means to discard all text properties.
4639 See also `yank-handled-properties'."
4640 :type '(choice (const :tag "All" t) (repeat symbol))
4641 :group 'killing
4642 :version "24.3")
4644 (defvar yank-window-start nil)
4645 (defvar yank-undo-function nil
4646 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4647 Function is called with two parameters, START and END corresponding to
4648 the value of the mark and point; it is guaranteed that START <= END.
4649 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4651 (defun yank-pop (&optional arg)
4652 "Replace just-yanked stretch of killed text with a different stretch.
4653 This command is allowed only immediately after a `yank' or a `yank-pop'.
4654 At such a time, the region contains a stretch of reinserted
4655 previously-killed text. `yank-pop' deletes that text and inserts in its
4656 place a different stretch of killed text.
4658 With no argument, the previous kill is inserted.
4659 With argument N, insert the Nth previous kill.
4660 If N is negative, this is a more recent kill.
4662 The sequence of kills wraps around, so that after the oldest one
4663 comes the newest one.
4665 When this command inserts killed text into the buffer, it honors
4666 `yank-excluded-properties' and `yank-handler' as described in the
4667 doc string for `insert-for-yank-1', which see."
4668 (interactive "*p")
4669 (if (not (eq last-command 'yank))
4670 (user-error "Previous command was not a yank"))
4671 (setq this-command 'yank)
4672 (unless arg (setq arg 1))
4673 (let ((inhibit-read-only t)
4674 (before (< (point) (mark t))))
4675 (if before
4676 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4677 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4678 (setq yank-undo-function nil)
4679 (set-marker (mark-marker) (point) (current-buffer))
4680 (insert-for-yank (current-kill arg))
4681 ;; Set the window start back where it was in the yank command,
4682 ;; if possible.
4683 (set-window-start (selected-window) yank-window-start t)
4684 (if before
4685 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4686 ;; It is cleaner to avoid activation, even though the command
4687 ;; loop would deactivate the mark because we inserted text.
4688 (goto-char (prog1 (mark t)
4689 (set-marker (mark-marker) (point) (current-buffer))))))
4690 nil)
4692 (defun yank (&optional arg)
4693 "Reinsert (\"paste\") the last stretch of killed text.
4694 More precisely, reinsert the most recent kill, which is the
4695 stretch of killed text most recently killed OR yanked. Put point
4696 at the end, and set mark at the beginning without activating it.
4697 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4698 With argument N, reinsert the Nth most recent kill.
4700 When this command inserts text into the buffer, it honors the
4701 `yank-handled-properties' and `yank-excluded-properties'
4702 variables, and the `yank-handler' text property. See
4703 `insert-for-yank-1' for details.
4705 See also the command `yank-pop' (\\[yank-pop])."
4706 (interactive "*P")
4707 (setq yank-window-start (window-start))
4708 ;; If we don't get all the way thru, make last-command indicate that
4709 ;; for the following command.
4710 (setq this-command t)
4711 (push-mark (point))
4712 (insert-for-yank (current-kill (cond
4713 ((listp arg) 0)
4714 ((eq arg '-) -2)
4715 (t (1- arg)))))
4716 (if (consp arg)
4717 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4718 ;; It is cleaner to avoid activation, even though the command
4719 ;; loop would deactivate the mark because we inserted text.
4720 (goto-char (prog1 (mark t)
4721 (set-marker (mark-marker) (point) (current-buffer)))))
4722 ;; If we do get all the way thru, make this-command indicate that.
4723 (if (eq this-command t)
4724 (setq this-command 'yank))
4725 nil)
4727 (defun rotate-yank-pointer (arg)
4728 "Rotate the yanking point in the kill ring.
4729 With ARG, rotate that many kills forward (or backward, if negative)."
4730 (interactive "p")
4731 (current-kill arg))
4733 ;; Some kill commands.
4735 ;; Internal subroutine of delete-char
4736 (defun kill-forward-chars (arg)
4737 (if (listp arg) (setq arg (car arg)))
4738 (if (eq arg '-) (setq arg -1))
4739 (kill-region (point) (+ (point) arg)))
4741 ;; Internal subroutine of backward-delete-char
4742 (defun kill-backward-chars (arg)
4743 (if (listp arg) (setq arg (car arg)))
4744 (if (eq arg '-) (setq arg -1))
4745 (kill-region (point) (- (point) arg)))
4747 (defcustom backward-delete-char-untabify-method 'untabify
4748 "The method for untabifying when deleting backward.
4749 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4750 `hungry' -- delete all whitespace, both tabs and spaces;
4751 `all' -- delete all whitespace, including tabs, spaces and newlines;
4752 nil -- just delete one character."
4753 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4754 :version "20.3"
4755 :group 'killing)
4757 (defun backward-delete-char-untabify (arg &optional killp)
4758 "Delete characters backward, changing tabs into spaces.
4759 The exact behavior depends on `backward-delete-char-untabify-method'.
4760 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4761 Interactively, ARG is the prefix arg (default 1)
4762 and KILLP is t if a prefix arg was specified."
4763 (interactive "*p\nP")
4764 (when (eq backward-delete-char-untabify-method 'untabify)
4765 (let ((count arg))
4766 (save-excursion
4767 (while (and (> count 0) (not (bobp)))
4768 (if (= (preceding-char) ?\t)
4769 (let ((col (current-column)))
4770 (forward-char -1)
4771 (setq col (- col (current-column)))
4772 (insert-char ?\s col)
4773 (delete-char 1)))
4774 (forward-char -1)
4775 (setq count (1- count))))))
4776 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4777 ((eq backward-delete-char-untabify-method 'all)
4778 " \t\n\r")))
4779 (n (if skip
4780 (let* ((oldpt (point))
4781 (wh (- oldpt (save-excursion
4782 (skip-chars-backward skip)
4783 (constrain-to-field nil oldpt)))))
4784 (+ arg (if (zerop wh) 0 (1- wh))))
4785 arg)))
4786 ;; Avoid warning about delete-backward-char
4787 (with-no-warnings (delete-backward-char n killp))))
4789 (defun zap-to-char (arg char)
4790 "Kill up to and including ARGth occurrence of CHAR.
4791 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4792 Goes backward if ARG is negative; error if CHAR not found."
4793 (interactive (list (prefix-numeric-value current-prefix-arg)
4794 (read-char "Zap to char: " t)))
4795 ;; Avoid "obsolete" warnings for translation-table-for-input.
4796 (with-no-warnings
4797 (if (char-table-p translation-table-for-input)
4798 (setq char (or (aref translation-table-for-input char) char))))
4799 (kill-region (point) (progn
4800 (search-forward (char-to-string char) nil nil arg)
4801 (point))))
4803 ;; kill-line and its subroutines.
4805 (defcustom kill-whole-line nil
4806 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4807 :type 'boolean
4808 :group 'killing)
4810 (defun kill-line (&optional arg)
4811 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4812 With prefix argument ARG, kill that many lines from point.
4813 Negative arguments kill lines backward.
4814 With zero argument, kills the text before point on the current line.
4816 When calling from a program, nil means \"no arg\",
4817 a number counts as a prefix arg.
4819 To kill a whole line, when point is not at the beginning, type \
4820 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4822 If `show-trailing-whitespace' is non-nil, this command will just
4823 kill the rest of the current line, even if there are only
4824 nonblanks there.
4826 If option `kill-whole-line' is non-nil, then this command kills the whole line
4827 including its terminating newline, when used at the beginning of a line
4828 with no argument. As a consequence, you can always kill a whole line
4829 by typing \\[move-beginning-of-line] \\[kill-line].
4831 If you want to append the killed line to the last killed text,
4832 use \\[append-next-kill] before \\[kill-line].
4834 If the buffer is read-only, Emacs will beep and refrain from deleting
4835 the line, but put the line in the kill ring anyway. This means that
4836 you can use this command to copy text from a read-only buffer.
4837 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4838 even beep.)"
4839 (interactive "P")
4840 (kill-region (point)
4841 ;; It is better to move point to the other end of the kill
4842 ;; before killing. That way, in a read-only buffer, point
4843 ;; moves across the text that is copied to the kill ring.
4844 ;; The choice has no effect on undo now that undo records
4845 ;; the value of point from before the command was run.
4846 (progn
4847 (if arg
4848 (forward-visible-line (prefix-numeric-value arg))
4849 (if (eobp)
4850 (signal 'end-of-buffer nil))
4851 (let ((end
4852 (save-excursion
4853 (end-of-visible-line) (point))))
4854 (if (or (save-excursion
4855 ;; If trailing whitespace is visible,
4856 ;; don't treat it as nothing.
4857 (unless show-trailing-whitespace
4858 (skip-chars-forward " \t" end))
4859 (= (point) end))
4860 (and kill-whole-line (bolp)))
4861 (forward-visible-line 1)
4862 (goto-char end))))
4863 (point))))
4865 (defun kill-whole-line (&optional arg)
4866 "Kill current line.
4867 With prefix ARG, kill that many lines starting from the current line.
4868 If ARG is negative, kill backward. Also kill the preceding newline.
4869 \(This is meant to make \\[repeat] work well with negative arguments.)
4870 If ARG is zero, kill current line but exclude the trailing newline."
4871 (interactive "p")
4872 (or arg (setq arg 1))
4873 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4874 (signal 'end-of-buffer nil))
4875 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4876 (signal 'beginning-of-buffer nil))
4877 (unless (eq last-command 'kill-region)
4878 (kill-new "")
4879 (setq last-command 'kill-region))
4880 (cond ((zerop arg)
4881 ;; We need to kill in two steps, because the previous command
4882 ;; could have been a kill command, in which case the text
4883 ;; before point needs to be prepended to the current kill
4884 ;; ring entry and the text after point appended. Also, we
4885 ;; need to use save-excursion to avoid copying the same text
4886 ;; twice to the kill ring in read-only buffers.
4887 (save-excursion
4888 (kill-region (point) (progn (forward-visible-line 0) (point))))
4889 (kill-region (point) (progn (end-of-visible-line) (point))))
4890 ((< arg 0)
4891 (save-excursion
4892 (kill-region (point) (progn (end-of-visible-line) (point))))
4893 (kill-region (point)
4894 (progn (forward-visible-line (1+ arg))
4895 (unless (bobp) (backward-char))
4896 (point))))
4898 (save-excursion
4899 (kill-region (point) (progn (forward-visible-line 0) (point))))
4900 (kill-region (point)
4901 (progn (forward-visible-line arg) (point))))))
4903 (defun forward-visible-line (arg)
4904 "Move forward by ARG lines, ignoring currently invisible newlines only.
4905 If ARG is negative, move backward -ARG lines.
4906 If ARG is zero, move to the beginning of the current line."
4907 (condition-case nil
4908 (if (> arg 0)
4909 (progn
4910 (while (> arg 0)
4911 (or (zerop (forward-line 1))
4912 (signal 'end-of-buffer nil))
4913 ;; If the newline we just skipped is invisible,
4914 ;; don't count it.
4915 (let ((prop
4916 (get-char-property (1- (point)) 'invisible)))
4917 (if (if (eq buffer-invisibility-spec t)
4918 prop
4919 (or (memq prop buffer-invisibility-spec)
4920 (assq prop buffer-invisibility-spec)))
4921 (setq arg (1+ arg))))
4922 (setq arg (1- arg)))
4923 ;; If invisible text follows, and it is a number of complete lines,
4924 ;; skip it.
4925 (let ((opoint (point)))
4926 (while (and (not (eobp))
4927 (let ((prop
4928 (get-char-property (point) 'invisible)))
4929 (if (eq buffer-invisibility-spec t)
4930 prop
4931 (or (memq prop buffer-invisibility-spec)
4932 (assq prop buffer-invisibility-spec)))))
4933 (goto-char
4934 (if (get-text-property (point) 'invisible)
4935 (or (next-single-property-change (point) 'invisible)
4936 (point-max))
4937 (next-overlay-change (point)))))
4938 (unless (bolp)
4939 (goto-char opoint))))
4940 (let ((first t))
4941 (while (or first (<= arg 0))
4942 (if first
4943 (beginning-of-line)
4944 (or (zerop (forward-line -1))
4945 (signal 'beginning-of-buffer nil)))
4946 ;; If the newline we just moved to is invisible,
4947 ;; don't count it.
4948 (unless (bobp)
4949 (let ((prop
4950 (get-char-property (1- (point)) 'invisible)))
4951 (unless (if (eq buffer-invisibility-spec t)
4952 prop
4953 (or (memq prop buffer-invisibility-spec)
4954 (assq prop buffer-invisibility-spec)))
4955 (setq arg (1+ arg)))))
4956 (setq first nil))
4957 ;; If invisible text follows, and it is a number of complete lines,
4958 ;; skip it.
4959 (let ((opoint (point)))
4960 (while (and (not (bobp))
4961 (let ((prop
4962 (get-char-property (1- (point)) 'invisible)))
4963 (if (eq buffer-invisibility-spec t)
4964 prop
4965 (or (memq prop buffer-invisibility-spec)
4966 (assq prop buffer-invisibility-spec)))))
4967 (goto-char
4968 (if (get-text-property (1- (point)) 'invisible)
4969 (or (previous-single-property-change (point) 'invisible)
4970 (point-min))
4971 (previous-overlay-change (point)))))
4972 (unless (bolp)
4973 (goto-char opoint)))))
4974 ((beginning-of-buffer end-of-buffer)
4975 nil)))
4977 (defun end-of-visible-line ()
4978 "Move to end of current visible line."
4979 (end-of-line)
4980 ;; If the following character is currently invisible,
4981 ;; skip all characters with that same `invisible' property value,
4982 ;; then find the next newline.
4983 (while (and (not (eobp))
4984 (save-excursion
4985 (skip-chars-forward "^\n")
4986 (let ((prop
4987 (get-char-property (point) 'invisible)))
4988 (if (eq buffer-invisibility-spec t)
4989 prop
4990 (or (memq prop buffer-invisibility-spec)
4991 (assq prop buffer-invisibility-spec))))))
4992 (skip-chars-forward "^\n")
4993 (if (get-text-property (point) 'invisible)
4994 (goto-char (or (next-single-property-change (point) 'invisible)
4995 (point-max)))
4996 (goto-char (next-overlay-change (point))))
4997 (end-of-line)))
4999 (defun insert-buffer (buffer)
5000 "Insert after point the contents of BUFFER.
5001 Puts mark after the inserted text.
5002 BUFFER may be a buffer or a buffer name."
5003 (declare (interactive-only insert-buffer-substring))
5004 (interactive
5005 (list
5006 (progn
5007 (barf-if-buffer-read-only)
5008 (read-buffer "Insert buffer: "
5009 (if (eq (selected-window) (next-window))
5010 (other-buffer (current-buffer))
5011 (window-buffer (next-window)))
5012 t))))
5013 (push-mark
5014 (save-excursion
5015 (insert-buffer-substring (get-buffer buffer))
5016 (point)))
5017 nil)
5019 (defun append-to-buffer (buffer start end)
5020 "Append to specified buffer the text of the region.
5021 It is inserted into that buffer before its point.
5023 When calling from a program, give three arguments:
5024 BUFFER (or buffer name), START and END.
5025 START and END specify the portion of the current buffer to be copied."
5026 (interactive
5027 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5028 (region-beginning) (region-end)))
5029 (let* ((oldbuf (current-buffer))
5030 (append-to (get-buffer-create buffer))
5031 (windows (get-buffer-window-list append-to t t))
5032 point)
5033 (save-excursion
5034 (with-current-buffer append-to
5035 (setq point (point))
5036 (barf-if-buffer-read-only)
5037 (insert-buffer-substring oldbuf start end)
5038 (dolist (window windows)
5039 (when (= (window-point window) point)
5040 (set-window-point window (point))))))))
5042 (defun prepend-to-buffer (buffer start end)
5043 "Prepend to specified buffer the text of the region.
5044 It is inserted into that buffer after its point.
5046 When calling from a program, give three arguments:
5047 BUFFER (or buffer name), START and END.
5048 START and END specify the portion of the current buffer to be copied."
5049 (interactive "BPrepend to buffer: \nr")
5050 (let ((oldbuf (current-buffer)))
5051 (with-current-buffer (get-buffer-create buffer)
5052 (barf-if-buffer-read-only)
5053 (save-excursion
5054 (insert-buffer-substring oldbuf start end)))))
5056 (defun copy-to-buffer (buffer start end)
5057 "Copy to specified buffer the text of the region.
5058 It is inserted into that buffer, replacing existing text there.
5060 When calling from a program, give three arguments:
5061 BUFFER (or buffer name), START and END.
5062 START and END specify the portion of the current buffer to be copied."
5063 (interactive "BCopy to buffer: \nr")
5064 (let ((oldbuf (current-buffer)))
5065 (with-current-buffer (get-buffer-create buffer)
5066 (barf-if-buffer-read-only)
5067 (erase-buffer)
5068 (save-excursion
5069 (insert-buffer-substring oldbuf start end)))))
5071 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5073 (defvar activate-mark-hook nil
5074 "Hook run when the mark becomes active.
5075 It is also run at the end of a command, if the mark is active and
5076 it is possible that the region may have changed.")
5078 (defvar deactivate-mark-hook nil
5079 "Hook run when the mark becomes inactive.")
5081 (defun mark (&optional force)
5082 "Return this buffer's mark value as integer, or nil if never set.
5084 In Transient Mark mode, this function signals an error if
5085 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5086 or the argument FORCE is non-nil, it disregards whether the mark
5087 is active, and returns an integer or nil in the usual way.
5089 If you are using this in an editing command, you are most likely making
5090 a mistake; see the documentation of `set-mark'."
5091 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5092 (marker-position (mark-marker))
5093 (signal 'mark-inactive nil)))
5095 ;; Behind display-selections-p.
5097 (defun deactivate-mark (&optional force)
5098 "Deactivate the mark.
5099 If Transient Mark mode is disabled, this function normally does
5100 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5102 Deactivating the mark sets `mark-active' to nil, updates the
5103 primary selection according to `select-active-regions', and runs
5104 `deactivate-mark-hook'.
5106 If Transient Mark mode was temporarily enabled, reset the value
5107 of the variable `transient-mark-mode'; if this causes Transient
5108 Mark mode to be disabled, don't change `mark-active' to nil or
5109 run `deactivate-mark-hook'."
5110 (when (or (region-active-p) force)
5111 (when (and (if (eq select-active-regions 'only)
5112 (eq (car-safe transient-mark-mode) 'only)
5113 select-active-regions)
5114 (region-active-p)
5115 (display-selections-p))
5116 ;; The var `saved-region-selection', if non-nil, is the text in
5117 ;; the region prior to the last command modifying the buffer.
5118 ;; Set the selection to that, or to the current region.
5119 (cond (saved-region-selection
5120 (if (gui-backend-selection-owner-p 'PRIMARY)
5121 (gui-set-selection 'PRIMARY saved-region-selection))
5122 (setq saved-region-selection nil))
5123 ;; If another program has acquired the selection, region
5124 ;; deactivation should not clobber it (Bug#11772).
5125 ((and (/= (region-beginning) (region-end))
5126 (or (gui-backend-selection-owner-p 'PRIMARY)
5127 (null (gui-backend-selection-exists-p 'PRIMARY))))
5128 (gui-set-selection 'PRIMARY
5129 (funcall region-extract-function nil)))))
5130 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5131 (cond
5132 ((eq (car-safe transient-mark-mode) 'only)
5133 (setq transient-mark-mode (cdr transient-mark-mode))
5134 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5135 (kill-local-variable 'transient-mark-mode)))
5136 ((eq transient-mark-mode 'lambda)
5137 (kill-local-variable 'transient-mark-mode)))
5138 (setq mark-active nil)
5139 (run-hooks 'deactivate-mark-hook)
5140 (redisplay--update-region-highlight (selected-window))))
5142 (defun activate-mark (&optional no-tmm)
5143 "Activate the mark.
5144 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5145 (when (mark t)
5146 (unless (region-active-p)
5147 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5148 (setq mark-active t)
5149 (unless (or transient-mark-mode no-tmm)
5150 (setq-local transient-mark-mode 'lambda))
5151 (run-hooks 'activate-mark-hook))))
5153 (defun set-mark (pos)
5154 "Set this buffer's mark to POS. Don't use this function!
5155 That is to say, don't use this function unless you want
5156 the user to see that the mark has moved, and you want the previous
5157 mark position to be lost.
5159 Normally, when a new mark is set, the old one should go on the stack.
5160 This is why most applications should use `push-mark', not `set-mark'.
5162 Novice Emacs Lisp programmers often try to use the mark for the wrong
5163 purposes. The mark saves a location for the user's convenience.
5164 Most editing commands should not alter the mark.
5165 To remember a location for internal use in the Lisp program,
5166 store it in a Lisp variable. Example:
5168 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5169 (if pos
5170 (progn
5171 (set-marker (mark-marker) pos (current-buffer))
5172 (activate-mark 'no-tmm))
5173 ;; Normally we never clear mark-active except in Transient Mark mode.
5174 ;; But when we actually clear out the mark value too, we must
5175 ;; clear mark-active in any mode.
5176 (deactivate-mark t)
5177 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5178 ;; it should never be nil if the mark is nil.
5179 (setq mark-active nil)
5180 (set-marker (mark-marker) nil)))
5182 (defun save-mark-and-excursion--save ()
5183 (cons
5184 (let ((mark (mark-marker)))
5185 (and (marker-position mark) (copy-marker mark)))
5186 mark-active))
5188 (defun save-mark-and-excursion--restore (saved-mark-info)
5189 (let ((saved-mark (car saved-mark-info))
5190 (omark (marker-position (mark-marker)))
5191 (nmark nil)
5192 (saved-mark-active (cdr saved-mark-info)))
5193 ;; Mark marker
5194 (if (null saved-mark)
5195 (set-marker (mark-marker) nil)
5196 (setf nmark (marker-position saved-mark))
5197 (set-marker (mark-marker) nmark)
5198 (set-marker saved-mark nil))
5199 ;; Mark active
5200 (let ((cur-mark-active mark-active))
5201 (setq mark-active saved-mark-active)
5202 ;; If mark is active now, and either was not active or was at a
5203 ;; different place, run the activate hook.
5204 (if saved-mark-active
5205 (when (or (not cur-mark-active)
5206 (not (eq omark nmark)))
5207 (run-hooks 'activate-mark-hook))
5208 ;; If mark has ceased to be active, run deactivate hook.
5209 (when cur-mark-active
5210 (run-hooks 'deactivate-mark-hook))))))
5212 (defmacro save-mark-and-excursion (&rest body)
5213 "Like `save-excursion', but also save and restore the mark state.
5214 This macro does what `save-excursion' did before Emacs 25.1."
5215 (let ((saved-marker-sym (make-symbol "saved-marker")))
5216 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5217 (unwind-protect
5218 (save-excursion ,@body)
5219 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5221 (defcustom use-empty-active-region nil
5222 "Whether \"region-aware\" commands should act on empty regions.
5223 If nil, region-aware commands treat the empty region as inactive.
5224 If non-nil, region-aware commands treat the region as active as
5225 long as the mark is active, even if the region is empty.
5227 Region-aware commands are those that act on the region if it is
5228 active and Transient Mark mode is enabled, and on the text near
5229 point otherwise."
5230 :type 'boolean
5231 :version "23.1"
5232 :group 'editing-basics)
5234 (defun use-region-p ()
5235 "Return t if the region is active and it is appropriate to act on it.
5236 This is used by commands that act specially on the region under
5237 Transient Mark mode.
5239 The return value is t if Transient Mark mode is enabled and the
5240 mark is active; furthermore, if `use-empty-active-region' is nil,
5241 the region must not be empty. Otherwise, the return value is nil.
5243 For some commands, it may be appropriate to ignore the value of
5244 `use-empty-active-region'; in that case, use `region-active-p'."
5245 (and (region-active-p)
5246 (or use-empty-active-region (> (region-end) (region-beginning)))))
5248 (defun region-active-p ()
5249 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5251 Some commands act specially on the region when Transient Mark
5252 mode is enabled. Usually, such commands should use
5253 `use-region-p' instead of this function, because `use-region-p'
5254 also checks the value of `use-empty-active-region'."
5255 (and transient-mark-mode mark-active
5256 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5257 ;; without the mark being set (e.g. bug#17324). We really should fix
5258 ;; that problem, but in the mean time, let's make sure we don't say the
5259 ;; region is active when there's no mark.
5260 (progn (cl-assert (mark)) t)))
5262 (defun region-noncontiguous-p ()
5263 "Return non-nil if the region contains several pieces.
5264 An example is a rectangular region handled as a list of
5265 separate contiguous regions for each line."
5266 (> (length (funcall region-extract-function 'bounds)) 1))
5268 (defvar redisplay-unhighlight-region-function
5269 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5271 (defvar redisplay-highlight-region-function
5272 (lambda (start end window rol)
5273 (if (not (overlayp rol))
5274 (let ((nrol (make-overlay start end)))
5275 (funcall redisplay-unhighlight-region-function rol)
5276 (overlay-put nrol 'window window)
5277 (overlay-put nrol 'face 'region)
5278 ;; Normal priority so that a large region doesn't hide all the
5279 ;; overlays within it, but high secondary priority so that if it
5280 ;; ends/starts in the middle of a small overlay, that small overlay
5281 ;; won't hide the region's boundaries.
5282 (overlay-put nrol 'priority '(nil . 100))
5283 nrol)
5284 (unless (and (eq (overlay-buffer rol) (current-buffer))
5285 (eq (overlay-start rol) start)
5286 (eq (overlay-end rol) end))
5287 (move-overlay rol start end (current-buffer)))
5288 rol)))
5290 (defun redisplay--update-region-highlight (window)
5291 (let ((rol (window-parameter window 'internal-region-overlay)))
5292 (if (not (and (region-active-p)
5293 (or highlight-nonselected-windows
5294 (eq window (selected-window))
5295 (and (window-minibuffer-p)
5296 (eq window (minibuffer-selected-window))))))
5297 (funcall redisplay-unhighlight-region-function rol)
5298 (let* ((pt (window-point window))
5299 (mark (mark))
5300 (start (min pt mark))
5301 (end (max pt mark))
5302 (new
5303 (funcall redisplay-highlight-region-function
5304 start end window rol)))
5305 (unless (equal new rol)
5306 (set-window-parameter window 'internal-region-overlay
5307 new))))))
5309 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5310 "Hook run just before redisplay.
5311 It is called in each window that is to be redisplayed. It takes one argument,
5312 which is the window that will be redisplayed. When run, the `current-buffer'
5313 is set to the buffer displayed in that window.")
5315 (defun redisplay--pre-redisplay-functions (windows)
5316 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5317 (if (null windows)
5318 (with-current-buffer (window-buffer (selected-window))
5319 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5320 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5321 (with-current-buffer (window-buffer win)
5322 (run-hook-with-args 'pre-redisplay-functions win))))))
5324 (add-function :before pre-redisplay-function
5325 #'redisplay--pre-redisplay-functions)
5328 (defvar-local mark-ring nil
5329 "The list of former marks of the current buffer, most recent first.")
5330 (put 'mark-ring 'permanent-local t)
5332 (defcustom mark-ring-max 16
5333 "Maximum size of mark ring. Start discarding off end if gets this big."
5334 :type 'integer
5335 :group 'editing-basics)
5337 (defvar global-mark-ring nil
5338 "The list of saved global marks, most recent first.")
5340 (defcustom global-mark-ring-max 16
5341 "Maximum size of global mark ring. \
5342 Start discarding off end if gets this big."
5343 :type 'integer
5344 :group 'editing-basics)
5346 (defun pop-to-mark-command ()
5347 "Jump to mark, and pop a new position for mark off the ring.
5348 \(Does not affect global mark ring)."
5349 (interactive)
5350 (if (null (mark t))
5351 (user-error "No mark set in this buffer")
5352 (if (= (point) (mark t))
5353 (message "Mark popped"))
5354 (goto-char (mark t))
5355 (pop-mark)))
5357 (defun push-mark-command (arg &optional nomsg)
5358 "Set mark at where point is.
5359 If no prefix ARG and mark is already set there, just activate it.
5360 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5361 (interactive "P")
5362 (let ((mark (mark t)))
5363 (if (or arg (null mark) (/= mark (point)))
5364 (push-mark nil nomsg t)
5365 (activate-mark 'no-tmm)
5366 (unless nomsg
5367 (message "Mark activated")))))
5369 (defcustom set-mark-command-repeat-pop nil
5370 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5371 That means that C-u \\[set-mark-command] \\[set-mark-command]
5372 will pop the mark twice, and
5373 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5374 will pop the mark three times.
5376 A value of nil means \\[set-mark-command]'s behavior does not change
5377 after C-u \\[set-mark-command]."
5378 :type 'boolean
5379 :group 'editing-basics)
5381 (defun set-mark-command (arg)
5382 "Set the mark where point is, or jump to the mark.
5383 Setting the mark also alters the region, which is the text
5384 between point and mark; this is the closest equivalent in
5385 Emacs to what some editors call the \"selection\".
5387 With no prefix argument, set the mark at point, and push the
5388 old mark position on local mark ring. Also push the old mark on
5389 global mark ring, if the previous mark was set in another buffer.
5391 When Transient Mark Mode is off, immediately repeating this
5392 command activates `transient-mark-mode' temporarily.
5394 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5395 jump to the mark, and set the mark from
5396 position popped off the local mark ring (this does not affect the global
5397 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5398 mark ring (see `pop-global-mark').
5400 If `set-mark-command-repeat-pop' is non-nil, repeating
5401 the \\[set-mark-command] command with no prefix argument pops the next position
5402 off the local (or global) mark ring and jumps there.
5404 With \\[universal-argument] \\[universal-argument] as prefix
5405 argument, unconditionally set mark where point is, even if
5406 `set-mark-command-repeat-pop' is non-nil.
5408 Novice Emacs Lisp programmers often try to use the mark for the wrong
5409 purposes. See the documentation of `set-mark' for more information."
5410 (interactive "P")
5411 (cond ((eq transient-mark-mode 'lambda)
5412 (kill-local-variable 'transient-mark-mode))
5413 ((eq (car-safe transient-mark-mode) 'only)
5414 (deactivate-mark)))
5415 (cond
5416 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5417 (push-mark-command nil))
5418 ((not (eq this-command 'set-mark-command))
5419 (if arg
5420 (pop-to-mark-command)
5421 (push-mark-command t)))
5422 ((and set-mark-command-repeat-pop
5423 (eq last-command 'pop-global-mark)
5424 (not arg))
5425 (setq this-command 'pop-global-mark)
5426 (pop-global-mark))
5427 ((or (and set-mark-command-repeat-pop
5428 (eq last-command 'pop-to-mark-command))
5429 arg)
5430 (setq this-command 'pop-to-mark-command)
5431 (pop-to-mark-command))
5432 ((eq last-command 'set-mark-command)
5433 (if (region-active-p)
5434 (progn
5435 (deactivate-mark)
5436 (message "Mark deactivated"))
5437 (activate-mark)
5438 (message "Mark activated")))
5440 (push-mark-command nil))))
5442 (defun push-mark (&optional location nomsg activate)
5443 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5444 If the last global mark pushed was not in the current buffer,
5445 also push LOCATION on the global mark ring.
5446 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5448 Novice Emacs Lisp programmers often try to use the mark for the wrong
5449 purposes. See the documentation of `set-mark' for more information.
5451 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5452 (unless (null (mark t))
5453 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5454 (when (> (length mark-ring) mark-ring-max)
5455 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5456 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5457 (set-marker (mark-marker) (or location (point)) (current-buffer))
5458 ;; Now push the mark on the global mark ring.
5459 (if (and global-mark-ring
5460 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5461 ;; The last global mark pushed was in this same buffer.
5462 ;; Don't push another one.
5464 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5465 (when (> (length global-mark-ring) global-mark-ring-max)
5466 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5467 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5468 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5469 (message "Mark set"))
5470 (if (or activate (not transient-mark-mode))
5471 (set-mark (mark t)))
5472 nil)
5474 (defun pop-mark ()
5475 "Pop off mark ring into the buffer's actual mark.
5476 Does not set point. Does nothing if mark ring is empty."
5477 (when mark-ring
5478 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5479 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5480 (move-marker (car mark-ring) nil)
5481 (if (null (mark t)) (ding))
5482 (setq mark-ring (cdr mark-ring)))
5483 (deactivate-mark))
5485 (define-obsolete-function-alias
5486 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5487 (defun exchange-point-and-mark (&optional arg)
5488 "Put the mark where point is now, and point where the mark is now.
5489 This command works even when the mark is not active,
5490 and it reactivates the mark.
5492 If Transient Mark mode is on, a prefix ARG deactivates the mark
5493 if it is active, and otherwise avoids reactivating it. If
5494 Transient Mark mode is off, a prefix ARG enables Transient Mark
5495 mode temporarily."
5496 (interactive "P")
5497 (let ((omark (mark t))
5498 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5499 (if (null omark)
5500 (user-error "No mark set in this buffer"))
5501 (set-mark (point))
5502 (goto-char omark)
5503 (cond (temp-highlight
5504 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5505 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5506 (not (or arg (region-active-p))))
5507 (deactivate-mark))
5508 (t (activate-mark)))
5509 nil))
5511 (defcustom shift-select-mode t
5512 "When non-nil, shifted motion keys activate the mark momentarily.
5514 While the mark is activated in this way, any shift-translated point
5515 motion key extends the region, and if Transient Mark mode was off, it
5516 is temporarily turned on. Furthermore, the mark will be deactivated
5517 by any subsequent point motion key that was not shift-translated, or
5518 by any action that normally deactivates the mark in Transient Mark mode.
5520 See `this-command-keys-shift-translated' for the meaning of
5521 shift-translation."
5522 :type 'boolean
5523 :group 'editing-basics)
5525 (defun handle-shift-selection ()
5526 "Activate/deactivate mark depending on invocation thru shift translation.
5527 This function is called by `call-interactively' when a command
5528 with a `^' character in its `interactive' spec is invoked, before
5529 running the command itself.
5531 If `shift-select-mode' is enabled and the command was invoked
5532 through shift translation, set the mark and activate the region
5533 temporarily, unless it was already set in this way. See
5534 `this-command-keys-shift-translated' for the meaning of shift
5535 translation.
5537 Otherwise, if the region has been activated temporarily,
5538 deactivate it, and restore the variable `transient-mark-mode' to
5539 its earlier value."
5540 (cond ((and shift-select-mode this-command-keys-shift-translated)
5541 (unless (and mark-active
5542 (eq (car-safe transient-mark-mode) 'only))
5543 (setq-local transient-mark-mode
5544 (cons 'only
5545 (unless (eq transient-mark-mode 'lambda)
5546 transient-mark-mode)))
5547 (push-mark nil nil t)))
5548 ((eq (car-safe transient-mark-mode) 'only)
5549 (setq transient-mark-mode (cdr transient-mark-mode))
5550 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5551 (kill-local-variable 'transient-mark-mode))
5552 (deactivate-mark))))
5554 (define-minor-mode transient-mark-mode
5555 "Toggle Transient Mark mode.
5556 With a prefix argument ARG, enable Transient Mark mode if ARG is
5557 positive, and disable it otherwise. If called from Lisp, enable
5558 Transient Mark mode if ARG is omitted or nil.
5560 Transient Mark mode is a global minor mode. When enabled, the
5561 region is highlighted with the `region' face whenever the mark
5562 is active. The mark is \"deactivated\" by changing the buffer,
5563 and after certain other operations that set the mark but whose
5564 main purpose is something else--for example, incremental search,
5565 \\[beginning-of-buffer], and \\[end-of-buffer].
5567 You can also deactivate the mark by typing \\[keyboard-quit] or
5568 \\[keyboard-escape-quit].
5570 Many commands change their behavior when Transient Mark mode is
5571 in effect and the mark is active, by acting on the region instead
5572 of their usual default part of the buffer's text. Examples of
5573 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5574 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5575 To see the documentation of commands which are sensitive to the
5576 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5577 or \"mark.*active\" at the prompt."
5578 :global t
5579 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5580 :variable (default-value 'transient-mark-mode))
5582 (defvar widen-automatically t
5583 "Non-nil means it is ok for commands to call `widen' when they want to.
5584 Some commands will do this in order to go to positions outside
5585 the current accessible part of the buffer.
5587 If `widen-automatically' is nil, these commands will do something else
5588 as a fallback, and won't change the buffer bounds.")
5590 (defvar non-essential nil
5591 "Whether the currently executing code is performing an essential task.
5592 This variable should be non-nil only when running code which should not
5593 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5594 user for a password when we are simply scanning a set of files in the
5595 background or displaying possible completions before the user even asked
5596 for it.")
5598 (defun pop-global-mark ()
5599 "Pop off global mark ring and jump to the top location."
5600 (interactive)
5601 ;; Pop entries which refer to non-existent buffers.
5602 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5603 (setq global-mark-ring (cdr global-mark-ring)))
5604 (or global-mark-ring
5605 (error "No global mark set"))
5606 (let* ((marker (car global-mark-ring))
5607 (buffer (marker-buffer marker))
5608 (position (marker-position marker)))
5609 (setq global-mark-ring (nconc (cdr global-mark-ring)
5610 (list (car global-mark-ring))))
5611 (set-buffer buffer)
5612 (or (and (>= position (point-min))
5613 (<= position (point-max)))
5614 (if widen-automatically
5615 (widen)
5616 (error "Global mark position is outside accessible part of buffer")))
5617 (goto-char position)
5618 (switch-to-buffer buffer)))
5620 (defcustom next-line-add-newlines nil
5621 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5622 :type 'boolean
5623 :version "21.1"
5624 :group 'editing-basics)
5626 (defun next-line (&optional arg try-vscroll)
5627 "Move cursor vertically down ARG lines.
5628 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5629 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5630 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5631 function will not vscroll.
5633 ARG defaults to 1.
5635 If there is no character in the target line exactly under the current column,
5636 the cursor is positioned after the character in that line which spans this
5637 column, or at the end of the line if it is not long enough.
5638 If there is no line in the buffer after this one, behavior depends on the
5639 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5640 to create a line, and moves the cursor to that line. Otherwise it moves the
5641 cursor to the end of the buffer.
5643 If the variable `line-move-visual' is non-nil, this command moves
5644 by display lines. Otherwise, it moves by buffer lines, without
5645 taking variable-width characters or continued lines into account.
5646 See \\[next-logical-line] for a command that always moves by buffer lines.
5648 The command \\[set-goal-column] can be used to create
5649 a semipermanent goal column for this command.
5650 Then instead of trying to move exactly vertically (or as close as possible),
5651 this command moves to the specified goal column (or as close as possible).
5652 The goal column is stored in the variable `goal-column', which is nil
5653 when there is no goal column. Note that setting `goal-column'
5654 overrides `line-move-visual' and causes this command to move by buffer
5655 lines rather than by display lines."
5656 (declare (interactive-only forward-line))
5657 (interactive "^p\np")
5658 (or arg (setq arg 1))
5659 (if (and next-line-add-newlines (= arg 1))
5660 (if (save-excursion (end-of-line) (eobp))
5661 ;; When adding a newline, don't expand an abbrev.
5662 (let ((abbrev-mode nil))
5663 (end-of-line)
5664 (insert (if use-hard-newlines hard-newline "\n")))
5665 (line-move arg nil nil try-vscroll))
5666 (if (called-interactively-p 'interactive)
5667 (condition-case err
5668 (line-move arg nil nil try-vscroll)
5669 ((beginning-of-buffer end-of-buffer)
5670 (signal (car err) (cdr err))))
5671 (line-move arg nil nil try-vscroll)))
5672 nil)
5674 (defun previous-line (&optional arg try-vscroll)
5675 "Move cursor vertically up ARG lines.
5676 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5677 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5678 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5679 function will not vscroll.
5681 ARG defaults to 1.
5683 If there is no character in the target line exactly over the current column,
5684 the cursor is positioned after the character in that line which spans this
5685 column, or at the end of the line if it is not long enough.
5687 If the variable `line-move-visual' is non-nil, this command moves
5688 by display lines. Otherwise, it moves by buffer lines, without
5689 taking variable-width characters or continued lines into account.
5690 See \\[previous-logical-line] for a command that always moves by buffer lines.
5692 The command \\[set-goal-column] can be used to create
5693 a semipermanent goal column for this command.
5694 Then instead of trying to move exactly vertically (or as close as possible),
5695 this command moves to the specified goal column (or as close as possible).
5696 The goal column is stored in the variable `goal-column', which is nil
5697 when there is no goal column. Note that setting `goal-column'
5698 overrides `line-move-visual' and causes this command to move by buffer
5699 lines rather than by display lines."
5700 (declare (interactive-only
5701 "use `forward-line' with negative argument instead."))
5702 (interactive "^p\np")
5703 (or arg (setq arg 1))
5704 (if (called-interactively-p 'interactive)
5705 (condition-case err
5706 (line-move (- arg) nil nil try-vscroll)
5707 ((beginning-of-buffer end-of-buffer)
5708 (signal (car err) (cdr err))))
5709 (line-move (- arg) nil nil try-vscroll))
5710 nil)
5712 (defcustom track-eol nil
5713 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5714 This means moving to the end of each line moved onto.
5715 The beginning of a blank line does not count as the end of a line.
5716 This has no effect when the variable `line-move-visual' is non-nil."
5717 :type 'boolean
5718 :group 'editing-basics)
5720 (defcustom goal-column nil
5721 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5722 A non-nil setting overrides the variable `line-move-visual', which see."
5723 :type '(choice integer
5724 (const :tag "None" nil))
5725 :group 'editing-basics)
5726 (make-variable-buffer-local 'goal-column)
5728 (defvar temporary-goal-column 0
5729 "Current goal column for vertical motion.
5730 It is the column where point was at the start of the current run
5731 of vertical motion commands.
5733 When moving by visual lines via the function `line-move-visual', it is a cons
5734 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5735 divided by the default column width, and HSCROLL is the number of
5736 columns by which window is scrolled from left margin.
5738 When the `track-eol' feature is doing its job, the value is
5739 `most-positive-fixnum'.")
5741 (defcustom line-move-ignore-invisible t
5742 "Non-nil means commands that move by lines ignore invisible newlines.
5743 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5744 as if newlines that are invisible didn't exist, and count
5745 only visible newlines. Thus, moving across across 2 newlines
5746 one of which is invisible will be counted as a one-line move.
5747 Also, a non-nil value causes invisible text to be ignored when
5748 counting columns for the purposes of keeping point in the same
5749 column by \\[next-line] and \\[previous-line].
5751 Outline mode sets this."
5752 :type 'boolean
5753 :group 'editing-basics)
5755 (defcustom line-move-visual t
5756 "When non-nil, `line-move' moves point by visual lines.
5757 This movement is based on where the cursor is displayed on the
5758 screen, instead of relying on buffer contents alone. It takes
5759 into account variable-width characters and line continuation.
5760 If nil, `line-move' moves point by logical lines.
5761 A non-nil setting of `goal-column' overrides the value of this variable
5762 and forces movement by logical lines.
5763 A window that is horizontally scrolled also forces movement by logical
5764 lines."
5765 :type 'boolean
5766 :group 'editing-basics
5767 :version "23.1")
5769 ;; Only used if display-graphic-p.
5770 (declare-function font-info "font.c" (name &optional frame))
5772 (defun default-font-height ()
5773 "Return the height in pixels of the current buffer's default face font.
5775 If the default font is remapped (see `face-remapping-alist'), the
5776 function returns the height of the remapped face."
5777 (let ((default-font (face-font 'default)))
5778 (cond
5779 ((and (display-multi-font-p)
5780 ;; Avoid calling font-info if the frame's default font was
5781 ;; not changed since the frame was created. That's because
5782 ;; font-info is expensive for some fonts, see bug #14838.
5783 (not (string= (frame-parameter nil 'font) default-font)))
5784 (aref (font-info default-font) 3))
5785 (t (frame-char-height)))))
5787 (defun default-font-width ()
5788 "Return the width in pixels of the current buffer's default face font.
5790 If the default font is remapped (see `face-remapping-alist'), the
5791 function returns the width of the remapped face."
5792 (let ((default-font (face-font 'default)))
5793 (cond
5794 ((and (display-multi-font-p)
5795 ;; Avoid calling font-info if the frame's default font was
5796 ;; not changed since the frame was created. That's because
5797 ;; font-info is expensive for some fonts, see bug #14838.
5798 (not (string= (frame-parameter nil 'font) default-font)))
5799 (let* ((info (font-info (face-font 'default)))
5800 (width (aref info 11)))
5801 (if (> width 0)
5802 width
5803 (aref info 10))))
5804 (t (frame-char-width)))))
5806 (defun default-line-height ()
5807 "Return the pixel height of current buffer's default-face text line.
5809 The value includes `line-spacing', if any, defined for the buffer
5810 or the frame."
5811 (let ((dfh (default-font-height))
5812 (lsp (if (display-graphic-p)
5813 (or line-spacing
5814 (default-value 'line-spacing)
5815 (frame-parameter nil 'line-spacing)
5817 0)))
5818 (if (floatp lsp)
5819 (setq lsp (truncate (* (frame-char-height) lsp))))
5820 (+ dfh lsp)))
5822 (defun window-screen-lines ()
5823 "Return the number of screen lines in the text area of the selected window.
5825 This is different from `window-text-height' in that this function counts
5826 lines in units of the height of the font used by the default face displayed
5827 in the window, not in units of the frame's default font, and also accounts
5828 for `line-spacing', if any, defined for the window's buffer or frame.
5830 The value is a floating-point number."
5831 (let ((edges (window-inside-pixel-edges))
5832 (dlh (default-line-height)))
5833 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5835 ;; Returns non-nil if partial move was done.
5836 (defun line-move-partial (arg noerror to-end)
5837 (if (< arg 0)
5838 ;; Move backward (up).
5839 ;; If already vscrolled, reduce vscroll
5840 (let ((vs (window-vscroll nil t))
5841 (dlh (default-line-height)))
5842 (when (> vs dlh)
5843 (set-window-vscroll nil (- vs dlh) t)))
5845 ;; Move forward (down).
5846 (let* ((lh (window-line-height -1))
5847 (rowh (car lh))
5848 (vpos (nth 1 lh))
5849 (ypos (nth 2 lh))
5850 (rbot (nth 3 lh))
5851 (this-lh (window-line-height))
5852 (this-height (car this-lh))
5853 (this-ypos (nth 2 this-lh))
5854 (dlh (default-line-height))
5855 (wslines (window-screen-lines))
5856 (edges (window-inside-pixel-edges))
5857 (winh (- (nth 3 edges) (nth 1 edges) 1))
5858 py vs last-line)
5859 (if (> (mod wslines 1.0) 0.0)
5860 (setq wslines (round (+ wslines 0.5))))
5861 (when (or (null lh)
5862 (>= rbot dlh)
5863 (<= ypos (- dlh))
5864 (null this-lh)
5865 (<= this-ypos (- dlh)))
5866 (unless lh
5867 (let ((wend (pos-visible-in-window-p t nil t)))
5868 (setq rbot (nth 3 wend)
5869 rowh (nth 4 wend)
5870 vpos (nth 5 wend))))
5871 (unless this-lh
5872 (let ((wstart (pos-visible-in-window-p nil nil t)))
5873 (setq this-ypos (nth 2 wstart)
5874 this-height (nth 4 wstart))))
5875 (setq py
5876 (or (nth 1 this-lh)
5877 (let ((ppos (posn-at-point))
5878 col-row)
5879 (setq col-row (posn-actual-col-row ppos))
5880 (if col-row
5881 (- (cdr col-row) (window-vscroll))
5882 (cdr (posn-col-row ppos))))))
5883 ;; VPOS > 0 means the last line is only partially visible.
5884 ;; But if the part that is visible is at least as tall as the
5885 ;; default font, that means the line is actually fully
5886 ;; readable, and something like line-spacing is hidden. So in
5887 ;; that case we accept the last line in the window as still
5888 ;; visible, and consider the margin as starting one line
5889 ;; later.
5890 (if (and vpos (> vpos 0))
5891 (if (and rowh
5892 (>= rowh (default-font-height))
5893 (< rowh dlh))
5894 (setq last-line (min (- wslines scroll-margin) vpos))
5895 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
5896 (cond
5897 ;; If last line of window is fully visible, and vscrolling
5898 ;; more would make this line invisible, move forward.
5899 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
5900 (null this-height)
5901 (<= this-height dlh))
5902 (or (null rbot) (= rbot 0)))
5903 nil)
5904 ;; If cursor is not in the bottom scroll margin, and the
5905 ;; current line is is not too tall, move forward.
5906 ((and (or (null this-height) (<= this-height winh))
5907 vpos
5908 (> vpos 0)
5909 (< py last-line))
5910 nil)
5911 ;; When already vscrolled, we vscroll some more if we can,
5912 ;; or clear vscroll and move forward at end of tall image.
5913 ((> vs 0)
5914 (when (or (and rbot (> rbot 0))
5915 (and this-height (> this-height dlh)))
5916 (set-window-vscroll nil (+ vs dlh) t)))
5917 ;; If cursor just entered the bottom scroll margin, move forward,
5918 ;; but also optionally vscroll one line so redisplay won't recenter.
5919 ((and vpos
5920 (> vpos 0)
5921 (= py last-line))
5922 ;; Don't vscroll if the partially-visible line at window
5923 ;; bottom is not too tall (a.k.a. "just one more text
5924 ;; line"): in that case, we do want redisplay to behave
5925 ;; normally, i.e. recenter or whatever.
5927 ;; Note: ROWH + RBOT from the value returned by
5928 ;; pos-visible-in-window-p give the total height of the
5929 ;; partially-visible glyph row at the end of the window. As
5930 ;; we are dealing with floats, we disregard sub-pixel
5931 ;; discrepancies between that and DLH.
5932 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
5933 (set-window-vscroll nil dlh t))
5934 (line-move-1 arg noerror to-end)
5936 ;; If there are lines above the last line, scroll-up one line.
5937 ((and vpos (> vpos 0))
5938 (scroll-up 1)
5940 ;; Finally, start vscroll.
5942 (set-window-vscroll nil dlh t)))))))
5945 ;; This is like line-move-1 except that it also performs
5946 ;; vertical scrolling of tall images if appropriate.
5947 ;; That is not really a clean thing to do, since it mixes
5948 ;; scrolling with cursor motion. But so far we don't have
5949 ;; a cleaner solution to the problem of making C-n do something
5950 ;; useful given a tall image.
5951 (defun line-move (arg &optional noerror to-end try-vscroll)
5952 "Move forward ARG lines.
5953 If NOERROR, don't signal an error if we can't move ARG lines.
5954 TO-END is unused.
5955 TRY-VSCROLL controls whether to vscroll tall lines: if either
5956 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
5957 not vscroll."
5958 (if noninteractive
5959 (line-move-1 arg noerror to-end)
5960 (unless (and auto-window-vscroll try-vscroll
5961 ;; Only vscroll for single line moves
5962 (= (abs arg) 1)
5963 ;; Under scroll-conservatively, the display engine
5964 ;; does this better.
5965 (zerop scroll-conservatively)
5966 ;; But don't vscroll in a keyboard macro.
5967 (not defining-kbd-macro)
5968 (not executing-kbd-macro)
5969 (line-move-partial arg noerror to-end))
5970 (set-window-vscroll nil 0 t)
5971 (if (and line-move-visual
5972 ;; Display-based column are incompatible with goal-column.
5973 (not goal-column)
5974 ;; When the text in the window is scrolled to the left,
5975 ;; display-based motion doesn't make sense (because each
5976 ;; logical line occupies exactly one screen line).
5977 (not (> (window-hscroll) 0))
5978 ;; Likewise when the text _was_ scrolled to the left
5979 ;; when the current run of vertical motion commands
5980 ;; started.
5981 (not (and (memq last-command
5982 `(next-line previous-line ,this-command))
5983 auto-hscroll-mode
5984 (numberp temporary-goal-column)
5985 (>= temporary-goal-column
5986 (- (window-width) hscroll-margin)))))
5987 (prog1 (line-move-visual arg noerror)
5988 ;; If we moved into a tall line, set vscroll to make
5989 ;; scrolling through tall images more smooth.
5990 (let ((lh (line-pixel-height))
5991 (edges (window-inside-pixel-edges))
5992 (dlh (default-line-height))
5993 winh)
5994 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
5995 (if (and (< arg 0)
5996 (< (point) (window-start))
5997 (> lh winh))
5998 (set-window-vscroll
6000 (- lh dlh) t))))
6001 (line-move-1 arg noerror to-end)))))
6003 ;; Display-based alternative to line-move-1.
6004 ;; Arg says how many lines to move. The value is t if we can move the
6005 ;; specified number of lines.
6006 (defun line-move-visual (arg &optional noerror)
6007 "Move ARG lines forward.
6008 If NOERROR, don't signal an error if we can't move that many lines."
6009 (let ((opoint (point))
6010 (hscroll (window-hscroll))
6011 target-hscroll)
6012 ;; Check if the previous command was a line-motion command, or if
6013 ;; we were called from some other command.
6014 (if (and (consp temporary-goal-column)
6015 (memq last-command `(next-line previous-line ,this-command)))
6016 ;; If so, there's no need to reset `temporary-goal-column',
6017 ;; but we may need to hscroll.
6018 (if (or (/= (cdr temporary-goal-column) hscroll)
6019 (> (cdr temporary-goal-column) 0))
6020 (setq target-hscroll (cdr temporary-goal-column)))
6021 ;; Otherwise, we should reset `temporary-goal-column'.
6022 (let ((posn (posn-at-point))
6023 x-pos)
6024 (cond
6025 ;; Handle the `overflow-newline-into-fringe' case:
6026 ((eq (nth 1 posn) 'right-fringe)
6027 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
6028 ((car (posn-x-y posn))
6029 (setq x-pos (car (posn-x-y posn)))
6030 ;; In R2L lines, the X pixel coordinate is measured from the
6031 ;; left edge of the window, but columns are still counted
6032 ;; from the logical-order beginning of the line, i.e. from
6033 ;; the right edge in this case. We need to adjust for that.
6034 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6035 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6036 (setq temporary-goal-column
6037 (cons (/ (float x-pos)
6038 (frame-char-width))
6039 hscroll))))))
6040 (if target-hscroll
6041 (set-window-hscroll (selected-window) target-hscroll))
6042 ;; vertical-motion can move more than it was asked to if it moves
6043 ;; across display strings with newlines. We don't want to ring
6044 ;; the bell and announce beginning/end of buffer in that case.
6045 (or (and (or (and (>= arg 0)
6046 (>= (vertical-motion
6047 (cons (or goal-column
6048 (if (consp temporary-goal-column)
6049 (car temporary-goal-column)
6050 temporary-goal-column))
6051 arg))
6052 arg))
6053 (and (< arg 0)
6054 (<= (vertical-motion
6055 (cons (or goal-column
6056 (if (consp temporary-goal-column)
6057 (car temporary-goal-column)
6058 temporary-goal-column))
6059 arg))
6060 arg)))
6061 (or (>= arg 0)
6062 (/= (point) opoint)
6063 ;; If the goal column lies on a display string,
6064 ;; `vertical-motion' advances the cursor to the end
6065 ;; of the string. For arg < 0, this can cause the
6066 ;; cursor to get stuck. (Bug#3020).
6067 (= (vertical-motion arg) arg)))
6068 (unless noerror
6069 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6070 nil)))))
6072 ;; This is the guts of next-line and previous-line.
6073 ;; Arg says how many lines to move.
6074 ;; The value is t if we can move the specified number of lines.
6075 (defun line-move-1 (arg &optional noerror _to-end)
6076 ;; Don't run any point-motion hooks, and disregard intangibility,
6077 ;; for intermediate positions.
6078 (let ((inhibit-point-motion-hooks t)
6079 (opoint (point))
6080 (orig-arg arg))
6081 (if (consp temporary-goal-column)
6082 (setq temporary-goal-column (+ (car temporary-goal-column)
6083 (cdr temporary-goal-column))))
6084 (unwind-protect
6085 (progn
6086 (if (not (memq last-command '(next-line previous-line)))
6087 (setq temporary-goal-column
6088 (if (and track-eol (eolp)
6089 ;; Don't count beg of empty line as end of line
6090 ;; unless we just did explicit end-of-line.
6091 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6092 most-positive-fixnum
6093 (current-column))))
6095 (if (not (or (integerp selective-display)
6096 line-move-ignore-invisible))
6097 ;; Use just newline characters.
6098 ;; Set ARG to 0 if we move as many lines as requested.
6099 (or (if (> arg 0)
6100 (progn (if (> arg 1) (forward-line (1- arg)))
6101 ;; This way of moving forward ARG lines
6102 ;; verifies that we have a newline after the last one.
6103 ;; It doesn't get confused by intangible text.
6104 (end-of-line)
6105 (if (zerop (forward-line 1))
6106 (setq arg 0)))
6107 (and (zerop (forward-line arg))
6108 (bolp)
6109 (setq arg 0)))
6110 (unless noerror
6111 (signal (if (< arg 0)
6112 'beginning-of-buffer
6113 'end-of-buffer)
6114 nil)))
6115 ;; Move by arg lines, but ignore invisible ones.
6116 (let (done)
6117 (while (and (> arg 0) (not done))
6118 ;; If the following character is currently invisible,
6119 ;; skip all characters with that same `invisible' property value.
6120 (while (and (not (eobp)) (invisible-p (point)))
6121 (goto-char (next-char-property-change (point))))
6122 ;; Move a line.
6123 ;; We don't use `end-of-line', since we want to escape
6124 ;; from field boundaries occurring exactly at point.
6125 (goto-char (constrain-to-field
6126 (let ((inhibit-field-text-motion t))
6127 (line-end-position))
6128 (point) t t
6129 'inhibit-line-move-field-capture))
6130 ;; If there's no invisibility here, move over the newline.
6131 (cond
6132 ((eobp)
6133 (if (not noerror)
6134 (signal 'end-of-buffer nil)
6135 (setq done t)))
6136 ((and (> arg 1) ;; Use vertical-motion for last move
6137 (not (integerp selective-display))
6138 (not (invisible-p (point))))
6139 ;; We avoid vertical-motion when possible
6140 ;; because that has to fontify.
6141 (forward-line 1))
6142 ;; Otherwise move a more sophisticated way.
6143 ((zerop (vertical-motion 1))
6144 (if (not noerror)
6145 (signal 'end-of-buffer nil)
6146 (setq done t))))
6147 (unless done
6148 (setq arg (1- arg))))
6149 ;; The logic of this is the same as the loop above,
6150 ;; it just goes in the other direction.
6151 (while (and (< arg 0) (not done))
6152 ;; For completely consistency with the forward-motion
6153 ;; case, we should call beginning-of-line here.
6154 ;; However, if point is inside a field and on a
6155 ;; continued line, the call to (vertical-motion -1)
6156 ;; below won't move us back far enough; then we return
6157 ;; to the same column in line-move-finish, and point
6158 ;; gets stuck -- cyd
6159 (forward-line 0)
6160 (cond
6161 ((bobp)
6162 (if (not noerror)
6163 (signal 'beginning-of-buffer nil)
6164 (setq done t)))
6165 ((and (< arg -1) ;; Use vertical-motion for last move
6166 (not (integerp selective-display))
6167 (not (invisible-p (1- (point)))))
6168 (forward-line -1))
6169 ((zerop (vertical-motion -1))
6170 (if (not noerror)
6171 (signal 'beginning-of-buffer nil)
6172 (setq done t))))
6173 (unless done
6174 (setq arg (1+ arg))
6175 (while (and ;; Don't move over previous invis lines
6176 ;; if our target is the middle of this line.
6177 (or (zerop (or goal-column temporary-goal-column))
6178 (< arg 0))
6179 (not (bobp)) (invisible-p (1- (point))))
6180 (goto-char (previous-char-property-change (point))))))))
6181 ;; This is the value the function returns.
6182 (= arg 0))
6184 (cond ((> arg 0)
6185 ;; If we did not move down as far as desired, at least go
6186 ;; to end of line. Be sure to call point-entered and
6187 ;; point-left-hooks.
6188 (let* ((npoint (prog1 (line-end-position)
6189 (goto-char opoint)))
6190 (inhibit-point-motion-hooks nil))
6191 (goto-char npoint)))
6192 ((< arg 0)
6193 ;; If we did not move up as far as desired,
6194 ;; at least go to beginning of line.
6195 (let* ((npoint (prog1 (line-beginning-position)
6196 (goto-char opoint)))
6197 (inhibit-point-motion-hooks nil))
6198 (goto-char npoint)))
6200 (line-move-finish (or goal-column temporary-goal-column)
6201 opoint (> orig-arg 0)))))))
6203 (defun line-move-finish (column opoint forward)
6204 (let ((repeat t))
6205 (while repeat
6206 ;; Set REPEAT to t to repeat the whole thing.
6207 (setq repeat nil)
6209 (let (new
6210 (old (point))
6211 (line-beg (line-beginning-position))
6212 (line-end
6213 ;; Compute the end of the line
6214 ;; ignoring effectively invisible newlines.
6215 (save-excursion
6216 ;; Like end-of-line but ignores fields.
6217 (skip-chars-forward "^\n")
6218 (while (and (not (eobp)) (invisible-p (point)))
6219 (goto-char (next-char-property-change (point)))
6220 (skip-chars-forward "^\n"))
6221 (point))))
6223 ;; Move to the desired column.
6224 (line-move-to-column (truncate column))
6226 ;; Corner case: suppose we start out in a field boundary in
6227 ;; the middle of a continued line. When we get to
6228 ;; line-move-finish, point is at the start of a new *screen*
6229 ;; line but the same text line; then line-move-to-column would
6230 ;; move us backwards. Test using C-n with point on the "x" in
6231 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6232 (and forward
6233 (< (point) old)
6234 (goto-char old))
6236 (setq new (point))
6238 ;; Process intangibility within a line.
6239 ;; With inhibit-point-motion-hooks bound to nil, a call to
6240 ;; goto-char moves point past intangible text.
6242 ;; However, inhibit-point-motion-hooks controls both the
6243 ;; intangibility and the point-entered/point-left hooks. The
6244 ;; following hack avoids calling the point-* hooks
6245 ;; unnecessarily. Note that we move *forward* past intangible
6246 ;; text when the initial and final points are the same.
6247 (goto-char new)
6248 (let ((inhibit-point-motion-hooks nil))
6249 (goto-char new)
6251 ;; If intangibility moves us to a different (later) place
6252 ;; in the same line, use that as the destination.
6253 (if (<= (point) line-end)
6254 (setq new (point))
6255 ;; If that position is "too late",
6256 ;; try the previous allowable position.
6257 ;; See if it is ok.
6258 (backward-char)
6259 (if (if forward
6260 ;; If going forward, don't accept the previous
6261 ;; allowable position if it is before the target line.
6262 (< line-beg (point))
6263 ;; If going backward, don't accept the previous
6264 ;; allowable position if it is still after the target line.
6265 (<= (point) line-end))
6266 (setq new (point))
6267 ;; As a last resort, use the end of the line.
6268 (setq new line-end))))
6270 ;; Now move to the updated destination, processing fields
6271 ;; as well as intangibility.
6272 (goto-char opoint)
6273 (let ((inhibit-point-motion-hooks nil))
6274 (goto-char
6275 ;; Ignore field boundaries if the initial and final
6276 ;; positions have the same `field' property, even if the
6277 ;; fields are non-contiguous. This seems to be "nicer"
6278 ;; behavior in many situations.
6279 (if (eq (get-char-property new 'field)
6280 (get-char-property opoint 'field))
6282 (constrain-to-field new opoint t t
6283 'inhibit-line-move-field-capture))))
6285 ;; If all this moved us to a different line,
6286 ;; retry everything within that new line.
6287 (when (or (< (point) line-beg) (> (point) line-end))
6288 ;; Repeat the intangibility and field processing.
6289 (setq repeat t))))))
6291 (defun line-move-to-column (col)
6292 "Try to find column COL, considering invisibility.
6293 This function works only in certain cases,
6294 because what we really need is for `move-to-column'
6295 and `current-column' to be able to ignore invisible text."
6296 (if (zerop col)
6297 (beginning-of-line)
6298 (move-to-column col))
6300 (when (and line-move-ignore-invisible
6301 (not (bolp)) (invisible-p (1- (point))))
6302 (let ((normal-location (point))
6303 (normal-column (current-column)))
6304 ;; If the following character is currently invisible,
6305 ;; skip all characters with that same `invisible' property value.
6306 (while (and (not (eobp))
6307 (invisible-p (point)))
6308 (goto-char (next-char-property-change (point))))
6309 ;; Have we advanced to a larger column position?
6310 (if (> (current-column) normal-column)
6311 ;; We have made some progress towards the desired column.
6312 ;; See if we can make any further progress.
6313 (line-move-to-column (+ (current-column) (- col normal-column)))
6314 ;; Otherwise, go to the place we originally found
6315 ;; and move back over invisible text.
6316 ;; that will get us to the same place on the screen
6317 ;; but with a more reasonable buffer position.
6318 (goto-char normal-location)
6319 (let ((line-beg
6320 ;; We want the real line beginning, so it's consistent
6321 ;; with bolp below, otherwise we might infloop.
6322 (let ((inhibit-field-text-motion t))
6323 (line-beginning-position))))
6324 (while (and (not (bolp)) (invisible-p (1- (point))))
6325 (goto-char (previous-char-property-change (point) line-beg))))))))
6327 (defun move-end-of-line (arg)
6328 "Move point to end of current line as displayed.
6329 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6330 If point reaches the beginning or end of buffer, it stops there.
6332 To ignore the effects of the `intangible' text or overlay
6333 property, bind `inhibit-point-motion-hooks' to t.
6334 If there is an image in the current line, this function
6335 disregards newlines that are part of the text on which the image
6336 rests."
6337 (interactive "^p")
6338 (or arg (setq arg 1))
6339 (let (done)
6340 (while (not done)
6341 (let ((newpos
6342 (save-excursion
6343 (let ((goal-column 0)
6344 (line-move-visual nil))
6345 (and (line-move arg t)
6346 ;; With bidi reordering, we may not be at bol,
6347 ;; so make sure we are.
6348 (skip-chars-backward "^\n")
6349 (not (bobp))
6350 (progn
6351 (while (and (not (bobp)) (invisible-p (1- (point))))
6352 (goto-char (previous-single-char-property-change
6353 (point) 'invisible)))
6354 (backward-char 1)))
6355 (point)))))
6356 (goto-char newpos)
6357 (if (and (> (point) newpos)
6358 (eq (preceding-char) ?\n))
6359 (backward-char 1)
6360 (if (and (> (point) newpos) (not (eobp))
6361 (not (eq (following-char) ?\n)))
6362 ;; If we skipped something intangible and now we're not
6363 ;; really at eol, keep going.
6364 (setq arg 1)
6365 (setq done t)))))))
6367 (defun move-beginning-of-line (arg)
6368 "Move point to beginning of current line as displayed.
6369 \(If there's an image in the line, this disregards newlines
6370 which are part of the text that the image rests on.)
6372 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6373 If point reaches the beginning or end of buffer, it stops there.
6374 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6375 (interactive "^p")
6376 (or arg (setq arg 1))
6378 (let ((orig (point))
6379 first-vis first-vis-field-value)
6381 ;; Move by lines, if ARG is not 1 (the default).
6382 (if (/= arg 1)
6383 (let ((line-move-visual nil))
6384 (line-move (1- arg) t)))
6386 ;; Move to beginning-of-line, ignoring fields and invisible text.
6387 (skip-chars-backward "^\n")
6388 (while (and (not (bobp)) (invisible-p (1- (point))))
6389 (goto-char (previous-char-property-change (point)))
6390 (skip-chars-backward "^\n"))
6392 ;; Now find first visible char in the line.
6393 (while (and (< (point) orig) (invisible-p (point)))
6394 (goto-char (next-char-property-change (point) orig)))
6395 (setq first-vis (point))
6397 ;; See if fields would stop us from reaching FIRST-VIS.
6398 (setq first-vis-field-value
6399 (constrain-to-field first-vis orig (/= arg 1) t nil))
6401 (goto-char (if (/= first-vis-field-value first-vis)
6402 ;; If yes, obey them.
6403 first-vis-field-value
6404 ;; Otherwise, move to START with attention to fields.
6405 ;; (It is possible that fields never matter in this case.)
6406 (constrain-to-field (point) orig
6407 (/= arg 1) t nil)))))
6410 ;; Many people have said they rarely use this feature, and often type
6411 ;; it by accident. Maybe it shouldn't even be on a key.
6412 (put 'set-goal-column 'disabled t)
6414 (defun set-goal-column (arg)
6415 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6416 Those commands will move to this position in the line moved to
6417 rather than trying to keep the same horizontal position.
6418 With a non-nil argument ARG, clears out the goal column
6419 so that \\[next-line] and \\[previous-line] resume vertical motion.
6420 The goal column is stored in the variable `goal-column'.
6421 This is a buffer-local setting."
6422 (interactive "P")
6423 (if arg
6424 (progn
6425 (setq goal-column nil)
6426 (message "No goal column"))
6427 (setq goal-column (current-column))
6428 ;; The older method below can be erroneous if `set-goal-column' is bound
6429 ;; to a sequence containing %
6430 ;;(message (substitute-command-keys
6431 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6432 ;;goal-column)
6433 (message "%s"
6434 (concat
6435 (format "Goal column %d " goal-column)
6436 (substitute-command-keys
6437 "(use \\[set-goal-column] with an arg to unset it)")))
6440 nil)
6442 ;;; Editing based on visual lines, as opposed to logical lines.
6444 (defun end-of-visual-line (&optional n)
6445 "Move point to end of current visual line.
6446 With argument N not nil or 1, move forward N - 1 visual lines first.
6447 If point reaches the beginning or end of buffer, it stops there.
6448 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6449 (interactive "^p")
6450 (or n (setq n 1))
6451 (if (/= n 1)
6452 (let ((line-move-visual t))
6453 (line-move (1- n) t)))
6454 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6455 ;; constrain to field boundaries, so we don't either.
6456 (vertical-motion (cons (window-width) 0)))
6458 (defun beginning-of-visual-line (&optional n)
6459 "Move point to beginning of current visual line.
6460 With argument N not nil or 1, move forward N - 1 visual lines first.
6461 If point reaches the beginning or end of buffer, it stops there.
6462 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6463 (interactive "^p")
6464 (or n (setq n 1))
6465 (let ((opoint (point)))
6466 (if (/= n 1)
6467 (let ((line-move-visual t))
6468 (line-move (1- n) t)))
6469 (vertical-motion 0)
6470 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6471 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6473 (defun kill-visual-line (&optional arg)
6474 "Kill the rest of the visual line.
6475 With prefix argument ARG, kill that many visual lines from point.
6476 If ARG is negative, kill visual lines backward.
6477 If ARG is zero, kill the text before point on the current visual
6478 line.
6480 If you want to append the killed line to the last killed text,
6481 use \\[append-next-kill] before \\[kill-line].
6483 If the buffer is read-only, Emacs will beep and refrain from deleting
6484 the line, but put the line in the kill ring anyway. This means that
6485 you can use this command to copy text from a read-only buffer.
6486 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6487 even beep.)"
6488 (interactive "P")
6489 ;; Like in `kill-line', it's better to move point to the other end
6490 ;; of the kill before killing.
6491 (let ((opoint (point))
6492 (kill-whole-line (and kill-whole-line (bolp))))
6493 (if arg
6494 (vertical-motion (prefix-numeric-value arg))
6495 (end-of-visual-line 1)
6496 (if (= (point) opoint)
6497 (vertical-motion 1)
6498 ;; Skip any trailing whitespace at the end of the visual line.
6499 ;; We used to do this only if `show-trailing-whitespace' is
6500 ;; nil, but that's wrong; the correct thing would be to check
6501 ;; whether the trailing whitespace is highlighted. But, it's
6502 ;; OK to just do this unconditionally.
6503 (skip-chars-forward " \t")))
6504 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
6505 (1+ (point))
6506 (point)))))
6508 (defun next-logical-line (&optional arg try-vscroll)
6509 "Move cursor vertically down ARG lines.
6510 This is identical to `next-line', except that it always moves
6511 by logical lines instead of visual lines, ignoring the value of
6512 the variable `line-move-visual'."
6513 (interactive "^p\np")
6514 (let ((line-move-visual nil))
6515 (with-no-warnings
6516 (next-line arg try-vscroll))))
6518 (defun previous-logical-line (&optional arg try-vscroll)
6519 "Move cursor vertically up ARG lines.
6520 This is identical to `previous-line', except that it always moves
6521 by logical lines instead of visual lines, ignoring the value of
6522 the variable `line-move-visual'."
6523 (interactive "^p\np")
6524 (let ((line-move-visual nil))
6525 (with-no-warnings
6526 (previous-line arg try-vscroll))))
6528 (defgroup visual-line nil
6529 "Editing based on visual lines."
6530 :group 'convenience
6531 :version "23.1")
6533 (defvar visual-line-mode-map
6534 (let ((map (make-sparse-keymap)))
6535 (define-key map [remap kill-line] 'kill-visual-line)
6536 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6537 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6538 ;; These keybindings interfere with xterm function keys. Are
6539 ;; there any other suitable bindings?
6540 ;; (define-key map "\M-[" 'previous-logical-line)
6541 ;; (define-key map "\M-]" 'next-logical-line)
6542 map))
6544 (defcustom visual-line-fringe-indicators '(nil nil)
6545 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6546 The value should be a list of the form (LEFT RIGHT), where LEFT
6547 and RIGHT are symbols representing the bitmaps to display, to
6548 indicate wrapped lines, in the left and right fringes respectively.
6549 See also `fringe-indicator-alist'.
6550 The default is not to display fringe indicators for wrapped lines.
6551 This variable does not affect fringe indicators displayed for
6552 other purposes."
6553 :type '(list (choice (const :tag "Hide left indicator" nil)
6554 (const :tag "Left curly arrow" left-curly-arrow)
6555 (symbol :tag "Other bitmap"))
6556 (choice (const :tag "Hide right indicator" nil)
6557 (const :tag "Right curly arrow" right-curly-arrow)
6558 (symbol :tag "Other bitmap")))
6559 :set (lambda (symbol value)
6560 (dolist (buf (buffer-list))
6561 (with-current-buffer buf
6562 (when (and (boundp 'visual-line-mode)
6563 (symbol-value 'visual-line-mode))
6564 (setq fringe-indicator-alist
6565 (cons (cons 'continuation value)
6566 (assq-delete-all
6567 'continuation
6568 (copy-tree fringe-indicator-alist)))))))
6569 (set-default symbol value)))
6571 (defvar visual-line--saved-state nil)
6573 (define-minor-mode visual-line-mode
6574 "Toggle visual line based editing (Visual Line mode).
6575 With a prefix argument ARG, enable Visual Line mode if ARG is
6576 positive, and disable it otherwise. If called from Lisp, enable
6577 the mode if ARG is omitted or nil.
6579 When Visual Line mode is enabled, `word-wrap' is turned on in
6580 this buffer, and simple editing commands are redefined to act on
6581 visual lines, not logical lines. See Info node `Visual Line
6582 Mode' for details."
6583 :keymap visual-line-mode-map
6584 :group 'visual-line
6585 :lighter " Wrap"
6586 (if visual-line-mode
6587 (progn
6588 (set (make-local-variable 'visual-line--saved-state) nil)
6589 ;; Save the local values of some variables, to be restored if
6590 ;; visual-line-mode is turned off.
6591 (dolist (var '(line-move-visual truncate-lines
6592 truncate-partial-width-windows
6593 word-wrap fringe-indicator-alist))
6594 (if (local-variable-p var)
6595 (push (cons var (symbol-value var))
6596 visual-line--saved-state)))
6597 (set (make-local-variable 'line-move-visual) t)
6598 (set (make-local-variable 'truncate-partial-width-windows) nil)
6599 (setq truncate-lines nil
6600 word-wrap t
6601 fringe-indicator-alist
6602 (cons (cons 'continuation visual-line-fringe-indicators)
6603 fringe-indicator-alist)))
6604 (kill-local-variable 'line-move-visual)
6605 (kill-local-variable 'word-wrap)
6606 (kill-local-variable 'truncate-lines)
6607 (kill-local-variable 'truncate-partial-width-windows)
6608 (kill-local-variable 'fringe-indicator-alist)
6609 (dolist (saved visual-line--saved-state)
6610 (set (make-local-variable (car saved)) (cdr saved)))
6611 (kill-local-variable 'visual-line--saved-state)))
6613 (defun turn-on-visual-line-mode ()
6614 (visual-line-mode 1))
6616 (define-globalized-minor-mode global-visual-line-mode
6617 visual-line-mode turn-on-visual-line-mode)
6620 (defun transpose-chars (arg)
6621 "Interchange characters around point, moving forward one character.
6622 With prefix arg ARG, effect is to take character before point
6623 and drag it forward past ARG other characters (backward if ARG negative).
6624 If no argument and at end of line, the previous two chars are exchanged."
6625 (interactive "*P")
6626 (when (and (null arg) (eolp) (not (bobp))
6627 (not (get-text-property (1- (point)) 'read-only)))
6628 (forward-char -1))
6629 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6631 (defun transpose-words (arg)
6632 "Interchange words around point, leaving point at end of them.
6633 With prefix arg ARG, effect is to take word before or around point
6634 and drag it forward past ARG other words (backward if ARG negative).
6635 If ARG is zero, the words around or after point and around or after mark
6636 are interchanged."
6637 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6638 (interactive "*p")
6639 (transpose-subr 'forward-word arg))
6641 (defun transpose-sexps (arg)
6642 "Like \\[transpose-words] but applies to sexps.
6643 Does not work on a sexp that point is in the middle of
6644 if it is a list or string."
6645 (interactive "*p")
6646 (transpose-subr
6647 (lambda (arg)
6648 ;; Here we should try to simulate the behavior of
6649 ;; (cons (progn (forward-sexp x) (point))
6650 ;; (progn (forward-sexp (- x)) (point)))
6651 ;; Except that we don't want to rely on the second forward-sexp
6652 ;; putting us back to where we want to be, since forward-sexp-function
6653 ;; might do funny things like infix-precedence.
6654 (if (if (> arg 0)
6655 (looking-at "\\sw\\|\\s_")
6656 (and (not (bobp))
6657 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6658 ;; Jumping over a symbol. We might be inside it, mind you.
6659 (progn (funcall (if (> arg 0)
6660 'skip-syntax-backward 'skip-syntax-forward)
6661 "w_")
6662 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6663 ;; Otherwise, we're between sexps. Take a step back before jumping
6664 ;; to make sure we'll obey the same precedence no matter which direction
6665 ;; we're going.
6666 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6667 (cons (save-excursion (forward-sexp arg) (point))
6668 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6669 (not (zerop (funcall (if (> arg 0)
6670 'skip-syntax-forward
6671 'skip-syntax-backward)
6672 ".")))))
6673 (point)))))
6674 arg 'special))
6676 (defun transpose-lines (arg)
6677 "Exchange current line and previous line, leaving point after both.
6678 With argument ARG, takes previous line and moves it past ARG lines.
6679 With argument 0, interchanges line point is in with line mark is in."
6680 (interactive "*p")
6681 (transpose-subr (function
6682 (lambda (arg)
6683 (if (> arg 0)
6684 (progn
6685 ;; Move forward over ARG lines,
6686 ;; but create newlines if necessary.
6687 (setq arg (forward-line arg))
6688 (if (/= (preceding-char) ?\n)
6689 (setq arg (1+ arg)))
6690 (if (> arg 0)
6691 (newline arg)))
6692 (forward-line arg))))
6693 arg))
6695 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6696 ;; which seems inconsistent with the ARG /= 0 case.
6697 ;; FIXME document SPECIAL.
6698 (defun transpose-subr (mover arg &optional special)
6699 "Subroutine to do the work of transposing objects.
6700 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6701 moves forward by units of the given object (e.g. forward-sentence,
6702 forward-paragraph). If ARG is zero, exchanges the current object
6703 with the one containing mark. If ARG is an integer, moves the
6704 current object past ARG following (if ARG is positive) or
6705 preceding (if ARG is negative) objects, leaving point after the
6706 current object."
6707 (let ((aux (if special mover
6708 (lambda (x)
6709 (cons (progn (funcall mover x) (point))
6710 (progn (funcall mover (- x)) (point))))))
6711 pos1 pos2)
6712 (cond
6713 ((= arg 0)
6714 (save-excursion
6715 (setq pos1 (funcall aux 1))
6716 (goto-char (or (mark) (error "No mark set in this buffer")))
6717 (setq pos2 (funcall aux 1))
6718 (transpose-subr-1 pos1 pos2))
6719 (exchange-point-and-mark))
6720 ((> arg 0)
6721 (setq pos1 (funcall aux -1))
6722 (setq pos2 (funcall aux arg))
6723 (transpose-subr-1 pos1 pos2)
6724 (goto-char (car pos2)))
6726 (setq pos1 (funcall aux -1))
6727 (goto-char (car pos1))
6728 (setq pos2 (funcall aux arg))
6729 (transpose-subr-1 pos1 pos2)
6730 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6732 (defun transpose-subr-1 (pos1 pos2)
6733 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6734 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6735 (when (> (car pos1) (car pos2))
6736 (let ((swap pos1))
6737 (setq pos1 pos2 pos2 swap)))
6738 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6739 (atomic-change-group
6740 ;; This sequence of insertions attempts to preserve marker
6741 ;; positions at the start and end of the transposed objects.
6742 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6743 (len1 (- (cdr pos1) (car pos1)))
6744 (len2 (length word))
6745 (boundary (make-marker)))
6746 (set-marker boundary (car pos2))
6747 (goto-char (cdr pos1))
6748 (insert-before-markers word)
6749 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6750 (goto-char boundary)
6751 (insert word)
6752 (goto-char (+ boundary len1))
6753 (delete-region (point) (+ (point) len2))
6754 (set-marker boundary nil))))
6756 (defun backward-word (&optional arg)
6757 "Move backward until encountering the beginning of a word.
6758 With argument ARG, do this that many times.
6759 If ARG is omitted or nil, move point backward one word.
6761 The word boundaries are normally determined by the buffer's syntax
6762 table, but `find-word-boundary-function-table', such as set up
6763 by `subword-mode', can change that. If a Lisp program needs to
6764 move by words determined strictly by the syntax table, it should
6765 use `backward-word-strictly' instead."
6766 (interactive "^p")
6767 (forward-word (- (or arg 1))))
6769 (defun mark-word (&optional arg allow-extend)
6770 "Set mark ARG words away from point.
6771 The place mark goes is the same place \\[forward-word] would
6772 move to with the same argument.
6773 Interactively, if this command is repeated
6774 or (in Transient Mark mode) if the mark is active,
6775 it marks the next ARG words after the ones already marked."
6776 (interactive "P\np")
6777 (cond ((and allow-extend
6778 (or (and (eq last-command this-command) (mark t))
6779 (region-active-p)))
6780 (setq arg (if arg (prefix-numeric-value arg)
6781 (if (< (mark) (point)) -1 1)))
6782 (set-mark
6783 (save-excursion
6784 (goto-char (mark))
6785 (forward-word arg)
6786 (point))))
6788 (push-mark
6789 (save-excursion
6790 (forward-word (prefix-numeric-value arg))
6791 (point))
6792 nil t))))
6794 (defun kill-word (arg)
6795 "Kill characters forward until encountering the end of a word.
6796 With argument ARG, do this that many times."
6797 (interactive "p")
6798 (kill-region (point) (progn (forward-word arg) (point))))
6800 (defun backward-kill-word (arg)
6801 "Kill characters backward until encountering the beginning of a word.
6802 With argument ARG, do this that many times."
6803 (interactive "p")
6804 (kill-word (- arg)))
6806 (defun current-word (&optional strict really-word)
6807 "Return the symbol or word that point is on (or a nearby one) as a string.
6808 The return value includes no text properties.
6809 If optional arg STRICT is non-nil, return nil unless point is within
6810 or adjacent to a symbol or word. In all cases the value can be nil
6811 if there is no word nearby.
6812 The function, belying its name, normally finds a symbol.
6813 If optional arg REALLY-WORD is non-nil, it finds just a word."
6814 (save-excursion
6815 (let* ((oldpoint (point)) (start (point)) (end (point))
6816 (syntaxes (if really-word "w" "w_"))
6817 (not-syntaxes (concat "^" syntaxes)))
6818 (skip-syntax-backward syntaxes) (setq start (point))
6819 (goto-char oldpoint)
6820 (skip-syntax-forward syntaxes) (setq end (point))
6821 (when (and (eq start oldpoint) (eq end oldpoint)
6822 ;; Point is neither within nor adjacent to a word.
6823 (not strict))
6824 ;; Look for preceding word in same line.
6825 (skip-syntax-backward not-syntaxes (line-beginning-position))
6826 (if (bolp)
6827 ;; No preceding word in same line.
6828 ;; Look for following word in same line.
6829 (progn
6830 (skip-syntax-forward not-syntaxes (line-end-position))
6831 (setq start (point))
6832 (skip-syntax-forward syntaxes)
6833 (setq end (point)))
6834 (setq end (point))
6835 (skip-syntax-backward syntaxes)
6836 (setq start (point))))
6837 ;; If we found something nonempty, return it as a string.
6838 (unless (= start end)
6839 (buffer-substring-no-properties start end)))))
6841 (defcustom fill-prefix nil
6842 "String for filling to insert at front of new line, or nil for none."
6843 :type '(choice (const :tag "None" nil)
6844 string)
6845 :group 'fill)
6846 (make-variable-buffer-local 'fill-prefix)
6847 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
6849 (defcustom auto-fill-inhibit-regexp nil
6850 "Regexp to match lines which should not be auto-filled."
6851 :type '(choice (const :tag "None" nil)
6852 regexp)
6853 :group 'fill)
6855 (defun do-auto-fill ()
6856 "The default value for `normal-auto-fill-function'.
6857 This is the default auto-fill function, some major modes use a different one.
6858 Returns t if it really did any work."
6859 (let (fc justify give-up
6860 (fill-prefix fill-prefix))
6861 (if (or (not (setq justify (current-justification)))
6862 (null (setq fc (current-fill-column)))
6863 (and (eq justify 'left)
6864 (<= (current-column) fc))
6865 (and auto-fill-inhibit-regexp
6866 (save-excursion (beginning-of-line)
6867 (looking-at auto-fill-inhibit-regexp))))
6868 nil ;; Auto-filling not required
6869 (if (memq justify '(full center right))
6870 (save-excursion (unjustify-current-line)))
6872 ;; Choose a fill-prefix automatically.
6873 (when (and adaptive-fill-mode
6874 (or (null fill-prefix) (string= fill-prefix "")))
6875 (let ((prefix
6876 (fill-context-prefix
6877 (save-excursion (fill-forward-paragraph -1) (point))
6878 (save-excursion (fill-forward-paragraph 1) (point)))))
6879 (and prefix (not (equal prefix ""))
6880 ;; Use auto-indentation rather than a guessed empty prefix.
6881 (not (and fill-indent-according-to-mode
6882 (string-match "\\`[ \t]*\\'" prefix)))
6883 (setq fill-prefix prefix))))
6885 (while (and (not give-up) (> (current-column) fc))
6886 ;; Determine where to split the line.
6887 (let* (after-prefix
6888 (fill-point
6889 (save-excursion
6890 (beginning-of-line)
6891 (setq after-prefix (point))
6892 (and fill-prefix
6893 (looking-at (regexp-quote fill-prefix))
6894 (setq after-prefix (match-end 0)))
6895 (move-to-column (1+ fc))
6896 (fill-move-to-break-point after-prefix)
6897 (point))))
6899 ;; See whether the place we found is any good.
6900 (if (save-excursion
6901 (goto-char fill-point)
6902 (or (bolp)
6903 ;; There is no use breaking at end of line.
6904 (save-excursion (skip-chars-forward " ") (eolp))
6905 ;; It is futile to split at the end of the prefix
6906 ;; since we would just insert the prefix again.
6907 (and after-prefix (<= (point) after-prefix))
6908 ;; Don't split right after a comment starter
6909 ;; since we would just make another comment starter.
6910 (and comment-start-skip
6911 (let ((limit (point)))
6912 (beginning-of-line)
6913 (and (re-search-forward comment-start-skip
6914 limit t)
6915 (eq (point) limit))))))
6916 ;; No good place to break => stop trying.
6917 (setq give-up t)
6918 ;; Ok, we have a useful place to break the line. Do it.
6919 (let ((prev-column (current-column)))
6920 ;; If point is at the fill-point, do not `save-excursion'.
6921 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6922 ;; point will end up before it rather than after it.
6923 (if (save-excursion
6924 (skip-chars-backward " \t")
6925 (= (point) fill-point))
6926 (default-indent-new-line t)
6927 (save-excursion
6928 (goto-char fill-point)
6929 (default-indent-new-line t)))
6930 ;; Now do justification, if required
6931 (if (not (eq justify 'left))
6932 (save-excursion
6933 (end-of-line 0)
6934 (justify-current-line justify nil t)))
6935 ;; If making the new line didn't reduce the hpos of
6936 ;; the end of the line, then give up now;
6937 ;; trying again will not help.
6938 (if (>= (current-column) prev-column)
6939 (setq give-up t))))))
6940 ;; Justify last line.
6941 (justify-current-line justify t t)
6942 t)))
6944 (defvar comment-line-break-function 'comment-indent-new-line
6945 "Mode-specific function which line breaks and continues a comment.
6946 This function is called during auto-filling when a comment syntax
6947 is defined.
6948 The function should take a single optional argument, which is a flag
6949 indicating whether it should use soft newlines.")
6951 (defun default-indent-new-line (&optional soft)
6952 "Break line at point and indent.
6953 If a comment syntax is defined, call `comment-indent-new-line'.
6955 The inserted newline is marked hard if variable `use-hard-newlines' is true,
6956 unless optional argument SOFT is non-nil."
6957 (interactive)
6958 (if comment-start
6959 (funcall comment-line-break-function soft)
6960 ;; Insert the newline before removing empty space so that markers
6961 ;; get preserved better.
6962 (if soft (insert-and-inherit ?\n) (newline 1))
6963 (save-excursion (forward-char -1) (delete-horizontal-space))
6964 (delete-horizontal-space)
6966 (if (and fill-prefix (not adaptive-fill-mode))
6967 ;; Blindly trust a non-adaptive fill-prefix.
6968 (progn
6969 (indent-to-left-margin)
6970 (insert-before-markers-and-inherit fill-prefix))
6972 (cond
6973 ;; If there's an adaptive prefix, use it unless we're inside
6974 ;; a comment and the prefix is not a comment starter.
6975 (fill-prefix
6976 (indent-to-left-margin)
6977 (insert-and-inherit fill-prefix))
6978 ;; If we're not inside a comment, just try to indent.
6979 (t (indent-according-to-mode))))))
6981 (defvar normal-auto-fill-function 'do-auto-fill
6982 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6983 Some major modes set this.")
6985 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
6986 ;; `functions' and `hooks' are usually unsafe to set, but setting
6987 ;; auto-fill-function to nil in a file-local setting is safe and
6988 ;; can be useful to prevent auto-filling.
6989 (put 'auto-fill-function 'safe-local-variable 'null)
6991 (define-minor-mode auto-fill-mode
6992 "Toggle automatic line breaking (Auto Fill mode).
6993 With a prefix argument ARG, enable Auto Fill mode if ARG is
6994 positive, and disable it otherwise. If called from Lisp, enable
6995 the mode if ARG is omitted or nil.
6997 When Auto Fill mode is enabled, inserting a space at a column
6998 beyond `current-fill-column' automatically breaks the line at a
6999 previous space.
7001 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7002 non-nil.
7004 The value of `normal-auto-fill-function' specifies the function to use
7005 for `auto-fill-function' when turning Auto Fill mode on."
7006 :variable (auto-fill-function
7007 . (lambda (v) (setq auto-fill-function
7008 (if v normal-auto-fill-function)))))
7010 ;; This holds a document string used to document auto-fill-mode.
7011 (defun auto-fill-function ()
7012 "Automatically break line at a previous space, in insertion of text."
7013 nil)
7015 (defun turn-on-auto-fill ()
7016 "Unconditionally turn on Auto Fill mode."
7017 (auto-fill-mode 1))
7019 (defun turn-off-auto-fill ()
7020 "Unconditionally turn off Auto Fill mode."
7021 (auto-fill-mode -1))
7023 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7025 (defun set-fill-column (arg)
7026 "Set `fill-column' to specified argument.
7027 Use \\[universal-argument] followed by a number to specify a column.
7028 Just \\[universal-argument] as argument means to use the current column."
7029 (interactive
7030 (list (or current-prefix-arg
7031 ;; We used to use current-column silently, but C-x f is too easily
7032 ;; typed as a typo for C-x C-f, so we turned it into an error and
7033 ;; now an interactive prompt.
7034 (read-number "Set fill-column to: " (current-column)))))
7035 (if (consp arg)
7036 (setq arg (current-column)))
7037 (if (not (integerp arg))
7038 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7039 (error "set-fill-column requires an explicit argument")
7040 (message "Fill column set to %d (was %d)" arg fill-column)
7041 (setq fill-column arg)))
7043 (defun set-selective-display (arg)
7044 "Set `selective-display' to ARG; clear it if no arg.
7045 When the value of `selective-display' is a number > 0,
7046 lines whose indentation is >= that value are not displayed.
7047 The variable `selective-display' has a separate value for each buffer."
7048 (interactive "P")
7049 (if (eq selective-display t)
7050 (error "selective-display already in use for marked lines"))
7051 (let ((current-vpos
7052 (save-restriction
7053 (narrow-to-region (point-min) (point))
7054 (goto-char (window-start))
7055 (vertical-motion (window-height)))))
7056 (setq selective-display
7057 (and arg (prefix-numeric-value arg)))
7058 (recenter current-vpos))
7059 (set-window-start (selected-window) (window-start))
7060 (princ "selective-display set to " t)
7061 (prin1 selective-display t)
7062 (princ "." t))
7064 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7066 (defun toggle-truncate-lines (&optional arg)
7067 "Toggle truncating of long lines for the current buffer.
7068 When truncating is off, long lines are folded.
7069 With prefix argument ARG, truncate long lines if ARG is positive,
7070 otherwise fold them. Note that in side-by-side windows, this
7071 command has no effect if `truncate-partial-width-windows' is
7072 non-nil."
7073 (interactive "P")
7074 (setq truncate-lines
7075 (if (null arg)
7076 (not truncate-lines)
7077 (> (prefix-numeric-value arg) 0)))
7078 (force-mode-line-update)
7079 (unless truncate-lines
7080 (let ((buffer (current-buffer)))
7081 (walk-windows (lambda (window)
7082 (if (eq buffer (window-buffer window))
7083 (set-window-hscroll window 0)))
7084 nil t)))
7085 (message "Truncate long lines %s"
7086 (if truncate-lines "enabled" "disabled")))
7088 (defun toggle-word-wrap (&optional arg)
7089 "Toggle whether to use word-wrapping for continuation lines.
7090 With prefix argument ARG, wrap continuation lines at word boundaries
7091 if ARG is positive, otherwise wrap them at the right screen edge.
7092 This command toggles the value of `word-wrap'. It has no effect
7093 if long lines are truncated."
7094 (interactive "P")
7095 (setq word-wrap
7096 (if (null arg)
7097 (not word-wrap)
7098 (> (prefix-numeric-value arg) 0)))
7099 (force-mode-line-update)
7100 (message "Word wrapping %s"
7101 (if word-wrap "enabled" "disabled")))
7103 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7104 "The string displayed in the mode line when in overwrite mode.")
7105 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7106 "The string displayed in the mode line when in binary overwrite mode.")
7108 (define-minor-mode overwrite-mode
7109 "Toggle Overwrite mode.
7110 With a prefix argument ARG, enable Overwrite mode if ARG is
7111 positive, and disable it otherwise. If called from Lisp, enable
7112 the mode if ARG is omitted or nil.
7114 When Overwrite mode is enabled, printing characters typed in
7115 replace existing text on a one-for-one basis, rather than pushing
7116 it to the right. At the end of a line, such characters extend
7117 the line. Before a tab, such characters insert until the tab is
7118 filled in. \\[quoted-insert] still inserts characters in
7119 overwrite mode; this is supposed to make it easier to insert
7120 characters when necessary."
7121 :variable (overwrite-mode
7122 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7124 (define-minor-mode binary-overwrite-mode
7125 "Toggle Binary Overwrite mode.
7126 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7127 is positive, and disable it otherwise. If called from Lisp,
7128 enable the mode if ARG is omitted or nil.
7130 When Binary Overwrite mode is enabled, printing characters typed
7131 in replace existing text. Newlines are not treated specially, so
7132 typing at the end of a line joins the line to the next, with the
7133 typed character between them. Typing before a tab character
7134 simply replaces the tab with the character typed.
7135 \\[quoted-insert] replaces the text at the cursor, just as
7136 ordinary typing characters do.
7138 Note that Binary Overwrite mode is not its own minor mode; it is
7139 a specialization of overwrite mode, entered by setting the
7140 `overwrite-mode' variable to `overwrite-mode-binary'."
7141 :variable (overwrite-mode
7142 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7144 (define-minor-mode line-number-mode
7145 "Toggle line number display in the mode line (Line Number mode).
7146 With a prefix argument ARG, enable Line Number mode if ARG is
7147 positive, and disable it otherwise. If called from Lisp, enable
7148 the mode if ARG is omitted or nil.
7150 Line numbers do not appear for very large buffers and buffers
7151 with very long lines; see variables `line-number-display-limit'
7152 and `line-number-display-limit-width'."
7153 :init-value t :global t :group 'mode-line)
7155 (define-minor-mode column-number-mode
7156 "Toggle column number display in the mode line (Column Number mode).
7157 With a prefix argument ARG, enable Column Number mode if ARG is
7158 positive, and disable it otherwise.
7160 If called from Lisp, enable the mode if ARG is omitted or nil."
7161 :global t :group 'mode-line)
7163 (define-minor-mode size-indication-mode
7164 "Toggle buffer size display in the mode line (Size Indication mode).
7165 With a prefix argument ARG, enable Size Indication mode if ARG is
7166 positive, and disable it otherwise.
7168 If called from Lisp, enable the mode if ARG is omitted or nil."
7169 :global t :group 'mode-line)
7171 (define-minor-mode auto-save-mode
7172 "Toggle auto-saving in the current buffer (Auto Save mode).
7173 With a prefix argument ARG, enable Auto Save mode if ARG is
7174 positive, and disable it otherwise.
7176 If called from Lisp, enable the mode if ARG is omitted or nil."
7177 :variable ((and buffer-auto-save-file-name
7178 ;; If auto-save is off because buffer has shrunk,
7179 ;; then toggling should turn it on.
7180 (>= buffer-saved-size 0))
7181 . (lambda (val)
7182 (setq buffer-auto-save-file-name
7183 (cond
7184 ((null val) nil)
7185 ((and buffer-file-name auto-save-visited-file-name
7186 (not buffer-read-only))
7187 buffer-file-name)
7188 (t (make-auto-save-file-name))))))
7189 ;; If -1 was stored here, to temporarily turn off saving,
7190 ;; turn it back on.
7191 (and (< buffer-saved-size 0)
7192 (setq buffer-saved-size 0)))
7194 (defgroup paren-blinking nil
7195 "Blinking matching of parens and expressions."
7196 :prefix "blink-matching-"
7197 :group 'paren-matching)
7199 (defcustom blink-matching-paren t
7200 "Non-nil means show matching open-paren when close-paren is inserted.
7201 If t, highlight the paren. If `jump', briefly move cursor to its
7202 position. If `jump-offscreen', move cursor there even if the
7203 position is off screen. With any other non-nil value, the
7204 off-screen position of the opening paren will be shown in the
7205 echo area."
7206 :type '(choice
7207 (const :tag "Disable" nil)
7208 (const :tag "Highlight" t)
7209 (const :tag "Move cursor" jump)
7210 (const :tag "Move cursor, even if off screen" jump-offscreen))
7211 :group 'paren-blinking)
7213 (defcustom blink-matching-paren-on-screen t
7214 "Non-nil means show matching open-paren when it is on screen.
7215 If nil, don't show it (but the open-paren can still be shown
7216 in the echo area when it is off screen).
7218 This variable has no effect if `blink-matching-paren' is nil.
7219 \(In that case, the open-paren is never shown.)
7220 It is also ignored if `show-paren-mode' is enabled."
7221 :type 'boolean
7222 :group 'paren-blinking)
7224 (defcustom blink-matching-paren-distance (* 100 1024)
7225 "If non-nil, maximum distance to search backwards for matching open-paren.
7226 If nil, search stops at the beginning of the accessible portion of the buffer."
7227 :version "23.2" ; 25->100k
7228 :type '(choice (const nil) integer)
7229 :group 'paren-blinking)
7231 (defcustom blink-matching-delay 1
7232 "Time in seconds to delay after showing a matching paren."
7233 :type 'number
7234 :group 'paren-blinking)
7236 (defcustom blink-matching-paren-dont-ignore-comments nil
7237 "If nil, `blink-matching-paren' ignores comments.
7238 More precisely, when looking for the matching parenthesis,
7239 it skips the contents of comments that end before point."
7240 :type 'boolean
7241 :group 'paren-blinking)
7243 (defun blink-matching-check-mismatch (start end)
7244 "Return whether or not START...END are matching parens.
7245 END is the current point and START is the blink position.
7246 START might be nil if no matching starter was found.
7247 Returns non-nil if we find there is a mismatch."
7248 (let* ((end-syntax (syntax-after (1- end)))
7249 (matching-paren (and (consp end-syntax)
7250 (eq (syntax-class end-syntax) 5)
7251 (cdr end-syntax))))
7252 ;; For self-matched chars like " and $, we can't know when they're
7253 ;; mismatched or unmatched, so we can only do it for parens.
7254 (when matching-paren
7255 (not (and start
7257 (eq (char-after start) matching-paren)
7258 ;; The cdr might hold a new paren-class info rather than
7259 ;; a matching-char info, in which case the two CDRs
7260 ;; should match.
7261 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7263 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7264 "Function to check parentheses mismatches.
7265 The function takes two arguments (START and END) where START is the
7266 position just before the opening token and END is the position right after.
7267 START can be nil, if it was not found.
7268 The function should return non-nil if the two tokens do not match.")
7270 (defvar blink-matching--overlay
7271 (let ((ol (make-overlay (point) (point) nil t)))
7272 (overlay-put ol 'face 'show-paren-match)
7273 (delete-overlay ol)
7275 "Overlay used to highlight the matching paren.")
7277 (defun blink-matching-open ()
7278 "Momentarily highlight the beginning of the sexp before point."
7279 (interactive)
7280 (when (and (not (bobp))
7281 blink-matching-paren)
7282 (let* ((oldpos (point))
7283 (message-log-max nil) ; Don't log messages about paren matching.
7284 (blinkpos
7285 (save-excursion
7286 (save-restriction
7287 (if blink-matching-paren-distance
7288 (narrow-to-region
7289 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7290 (- (point) blink-matching-paren-distance))
7291 oldpos))
7292 (let ((parse-sexp-ignore-comments
7293 (and parse-sexp-ignore-comments
7294 (not blink-matching-paren-dont-ignore-comments))))
7295 (condition-case ()
7296 (progn
7297 (syntax-propertize (point))
7298 (forward-sexp -1)
7299 ;; backward-sexp skips backward over prefix chars,
7300 ;; so move back to the matching paren.
7301 (while (and (< (point) (1- oldpos))
7302 (let ((code (syntax-after (point))))
7303 (or (eq (syntax-class code) 6)
7304 (eq (logand 1048576 (car code))
7305 1048576))))
7306 (forward-char 1))
7307 (point))
7308 (error nil))))))
7309 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7310 (cond
7311 (mismatch
7312 (if blinkpos
7313 (if (minibufferp)
7314 (minibuffer-message "Mismatched parentheses")
7315 (message "Mismatched parentheses"))
7316 (if (minibufferp)
7317 (minibuffer-message "No matching parenthesis found")
7318 (message "No matching parenthesis found"))))
7319 ((not blinkpos) nil)
7320 ((or
7321 (eq blink-matching-paren 'jump-offscreen)
7322 (pos-visible-in-window-p blinkpos))
7323 ;; Matching open within window, temporarily move to or highlight
7324 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7325 ;; is non-nil.
7326 (and blink-matching-paren-on-screen
7327 (not show-paren-mode)
7328 (if (memq blink-matching-paren '(jump jump-offscreen))
7329 (save-excursion
7330 (goto-char blinkpos)
7331 (sit-for blink-matching-delay))
7332 (unwind-protect
7333 (progn
7334 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7335 (current-buffer))
7336 (sit-for blink-matching-delay))
7337 (delete-overlay blink-matching--overlay)))))
7339 (let ((open-paren-line-string
7340 (save-excursion
7341 (goto-char blinkpos)
7342 ;; Show what precedes the open in its line, if anything.
7343 (cond
7344 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7345 (buffer-substring (line-beginning-position)
7346 (1+ blinkpos)))
7347 ;; Show what follows the open in its line, if anything.
7348 ((save-excursion
7349 (forward-char 1)
7350 (skip-chars-forward " \t")
7351 (not (eolp)))
7352 (buffer-substring blinkpos
7353 (line-end-position)))
7354 ;; Otherwise show the previous nonblank line,
7355 ;; if there is one.
7356 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7357 (concat
7358 (buffer-substring (progn
7359 (skip-chars-backward "\n \t")
7360 (line-beginning-position))
7361 (progn (end-of-line)
7362 (skip-chars-backward " \t")
7363 (point)))
7364 ;; Replace the newline and other whitespace with `...'.
7365 "..."
7366 (buffer-substring blinkpos (1+ blinkpos))))
7367 ;; There is nothing to show except the char itself.
7368 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7369 (minibuffer-message
7370 "Matches %s"
7371 (substring-no-properties open-paren-line-string))))))))
7373 (defvar blink-paren-function 'blink-matching-open
7374 "Function called, if non-nil, whenever a close parenthesis is inserted.
7375 More precisely, a char with closeparen syntax is self-inserted.")
7377 (defun blink-paren-post-self-insert-function ()
7378 (when (and (eq (char-before) last-command-event) ; Sanity check.
7379 (memq (char-syntax last-command-event) '(?\) ?\$))
7380 blink-paren-function
7381 (not executing-kbd-macro)
7382 (not noninteractive)
7383 ;; Verify an even number of quoting characters precede the close.
7384 ;; FIXME: Also check if this parenthesis closes a comment as
7385 ;; can happen in Pascal and SML.
7386 (= 1 (logand 1 (- (point)
7387 (save-excursion
7388 (forward-char -1)
7389 (skip-syntax-backward "/\\")
7390 (point))))))
7391 (funcall blink-paren-function)))
7393 (put 'blink-paren-post-self-insert-function 'priority 100)
7395 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7396 ;; Most likely, this hook is nil, so this arg doesn't matter,
7397 ;; but I use it as a reminder that this function usually
7398 ;; likes to be run after others since it does
7399 ;; `sit-for'. That's also the reason it get a `priority' prop
7400 ;; of 100.
7401 'append)
7403 ;; This executes C-g typed while Emacs is waiting for a command.
7404 ;; Quitting out of a program does not go through here;
7405 ;; that happens in the QUIT macro at the C code level.
7406 (defun keyboard-quit ()
7407 "Signal a `quit' condition.
7408 During execution of Lisp code, this character causes a quit directly.
7409 At top-level, as an editor command, this simply beeps."
7410 (interactive)
7411 ;; Avoid adding the region to the window selection.
7412 (setq saved-region-selection nil)
7413 (let (select-active-regions)
7414 (deactivate-mark))
7415 (if (fboundp 'kmacro-keyboard-quit)
7416 (kmacro-keyboard-quit))
7417 (when completion-in-region-mode
7418 (completion-in-region-mode -1))
7419 ;; Force the next redisplay cycle to remove the "Def" indicator from
7420 ;; all the mode lines.
7421 (if defining-kbd-macro
7422 (force-mode-line-update t))
7423 (setq defining-kbd-macro nil)
7424 (let ((debug-on-quit nil))
7425 (signal 'quit nil)))
7427 (defvar buffer-quit-function nil
7428 "Function to call to \"quit\" the current buffer, or nil if none.
7429 \\[keyboard-escape-quit] calls this function when its more local actions
7430 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7432 (defun keyboard-escape-quit ()
7433 "Exit the current \"mode\" (in a generalized sense of the word).
7434 This command can exit an interactive command such as `query-replace',
7435 can clear out a prefix argument or a region,
7436 can get out of the minibuffer or other recursive edit,
7437 cancel the use of the current buffer (for special-purpose buffers),
7438 or go back to just one window (by deleting all but the selected window)."
7439 (interactive)
7440 (cond ((eq last-command 'mode-exited) nil)
7441 ((region-active-p)
7442 (deactivate-mark))
7443 ((> (minibuffer-depth) 0)
7444 (abort-recursive-edit))
7445 (current-prefix-arg
7446 nil)
7447 ((> (recursion-depth) 0)
7448 (exit-recursive-edit))
7449 (buffer-quit-function
7450 (funcall buffer-quit-function))
7451 ((not (one-window-p t))
7452 (delete-other-windows))
7453 ((string-match "^ \\*" (buffer-name (current-buffer)))
7454 (bury-buffer))))
7456 (defun play-sound-file (file &optional volume device)
7457 "Play sound stored in FILE.
7458 VOLUME and DEVICE correspond to the keywords of the sound
7459 specification for `play-sound'."
7460 (interactive "fPlay sound file: ")
7461 (let ((sound (list :file file)))
7462 (if volume
7463 (plist-put sound :volume volume))
7464 (if device
7465 (plist-put sound :device device))
7466 (push 'sound sound)
7467 (play-sound sound)))
7470 (defcustom read-mail-command 'rmail
7471 "Your preference for a mail reading package.
7472 This is used by some keybindings which support reading mail.
7473 See also `mail-user-agent' concerning sending mail."
7474 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7475 (function-item :tag "Gnus" :format "%t\n" gnus)
7476 (function-item :tag "Emacs interface to MH"
7477 :format "%t\n" mh-rmail)
7478 (function :tag "Other"))
7479 :version "21.1"
7480 :group 'mail)
7482 (defcustom mail-user-agent 'message-user-agent
7483 "Your preference for a mail composition package.
7484 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7485 outgoing email message. This variable lets you specify which
7486 mail-sending package you prefer.
7488 Valid values include:
7490 `message-user-agent' -- use the Message package.
7491 See Info node `(message)'.
7492 `sendmail-user-agent' -- use the Mail package.
7493 See Info node `(emacs)Sending Mail'.
7494 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7495 See Info node `(mh-e)'.
7496 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7497 paraphernalia if Gnus is running, particularly
7498 the Gcc: header for archiving.
7500 Additional valid symbols may be available; check with the author of
7501 your package for details. The function should return non-nil if it
7502 succeeds.
7504 See also `read-mail-command' concerning reading mail."
7505 :type '(radio (function-item :tag "Message package"
7506 :format "%t\n"
7507 message-user-agent)
7508 (function-item :tag "Mail package"
7509 :format "%t\n"
7510 sendmail-user-agent)
7511 (function-item :tag "Emacs interface to MH"
7512 :format "%t\n"
7513 mh-e-user-agent)
7514 (function-item :tag "Message with full Gnus features"
7515 :format "%t\n"
7516 gnus-user-agent)
7517 (function :tag "Other"))
7518 :version "23.2" ; sendmail->message
7519 :group 'mail)
7521 (defcustom compose-mail-user-agent-warnings t
7522 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7523 If the value of `mail-user-agent' is the default, and the user
7524 appears to have customizations applying to the old default,
7525 `compose-mail' issues a warning."
7526 :type 'boolean
7527 :version "23.2"
7528 :group 'mail)
7530 (defun rfc822-goto-eoh ()
7531 "If the buffer starts with a mail header, move point to the header's end.
7532 Otherwise, moves to `point-min'.
7533 The end of the header is the start of the next line, if there is one,
7534 else the end of the last line. This function obeys RFC822."
7535 (goto-char (point-min))
7536 (when (re-search-forward
7537 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7538 (goto-char (match-beginning 0))))
7540 ;; Used by Rmail (e.g., rmail-forward).
7541 (defvar mail-encode-mml nil
7542 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7543 the outgoing message before sending it.")
7545 (defun compose-mail (&optional to subject other-headers continue
7546 switch-function yank-action send-actions
7547 return-action)
7548 "Start composing a mail message to send.
7549 This uses the user's chosen mail composition package
7550 as selected with the variable `mail-user-agent'.
7551 The optional arguments TO and SUBJECT specify recipients
7552 and the initial Subject field, respectively.
7554 OTHER-HEADERS is an alist specifying additional
7555 header fields. Elements look like (HEADER . VALUE) where both
7556 HEADER and VALUE are strings.
7558 CONTINUE, if non-nil, says to continue editing a message already
7559 being composed. Interactively, CONTINUE is the prefix argument.
7561 SWITCH-FUNCTION, if non-nil, is a function to use to
7562 switch to and display the buffer used for mail composition.
7564 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7565 to insert the raw text of the message being replied to.
7566 It has the form (FUNCTION . ARGS). The user agent will apply
7567 FUNCTION to ARGS, to insert the raw text of the original message.
7568 \(The user agent will also run `mail-citation-hook', *after* the
7569 original text has been inserted in this way.)
7571 SEND-ACTIONS is a list of actions to call when the message is sent.
7572 Each action has the form (FUNCTION . ARGS).
7574 RETURN-ACTION, if non-nil, is an action for returning to the
7575 caller. It has the form (FUNCTION . ARGS). The function is
7576 called after the mail has been sent or put aside, and the mail
7577 buffer buried."
7578 (interactive
7579 (list nil nil nil current-prefix-arg))
7581 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7582 ;; from sendmail-user-agent to message-user-agent. Some users may
7583 ;; encounter incompatibilities. This hack tries to detect problems
7584 ;; and warn about them.
7585 (and compose-mail-user-agent-warnings
7586 (eq mail-user-agent 'message-user-agent)
7587 (let (warn-vars)
7588 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7589 mail-yank-hooks mail-archive-file-name
7590 mail-default-reply-to mail-mailing-lists
7591 mail-self-blind))
7592 (and (boundp var)
7593 (symbol-value var)
7594 (push var warn-vars)))
7595 (when warn-vars
7596 (display-warning 'mail
7597 (format-message "\
7598 The default mail mode is now Message mode.
7599 You have the following Mail mode variable%s customized:
7600 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7601 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7602 (if (> (length warn-vars) 1) "s" "")
7603 (mapconcat 'symbol-name
7604 warn-vars " "))))))
7606 (let ((function (get mail-user-agent 'composefunc)))
7607 (funcall function to subject other-headers continue switch-function
7608 yank-action send-actions return-action)))
7610 (defun compose-mail-other-window (&optional to subject other-headers continue
7611 yank-action send-actions
7612 return-action)
7613 "Like \\[compose-mail], but edit the outgoing message in another window."
7614 (interactive (list nil nil nil current-prefix-arg))
7615 (compose-mail to subject other-headers continue
7616 'switch-to-buffer-other-window yank-action send-actions
7617 return-action))
7619 (defun compose-mail-other-frame (&optional to subject other-headers continue
7620 yank-action send-actions
7621 return-action)
7622 "Like \\[compose-mail], but edit the outgoing message in another frame."
7623 (interactive (list nil nil nil current-prefix-arg))
7624 (compose-mail to subject other-headers continue
7625 'switch-to-buffer-other-frame yank-action send-actions
7626 return-action))
7629 (defvar set-variable-value-history nil
7630 "History of values entered with `set-variable'.
7632 Maximum length of the history list is determined by the value
7633 of `history-length', which see.")
7635 (defun set-variable (variable value &optional make-local)
7636 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7637 VARIABLE should be a user option variable name, a Lisp variable
7638 meant to be customized by users. You should enter VALUE in Lisp syntax,
7639 so if you want VALUE to be a string, you must surround it with doublequotes.
7640 VALUE is used literally, not evaluated.
7642 If VARIABLE has a `variable-interactive' property, that is used as if
7643 it were the arg to `interactive' (which see) to interactively read VALUE.
7645 If VARIABLE has been defined with `defcustom', then the type information
7646 in the definition is used to check that VALUE is valid.
7648 Note that this function is at heart equivalent to the basic `set' function.
7649 For a variable defined with `defcustom', it does not pay attention to
7650 any :set property that the variable might have (if you want that, use
7651 \\[customize-set-variable] instead).
7653 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7654 (interactive
7655 (let* ((default-var (variable-at-point))
7656 (var (if (custom-variable-p default-var)
7657 (read-variable (format "Set variable (default %s): " default-var)
7658 default-var)
7659 (read-variable "Set variable: ")))
7660 (minibuffer-help-form '(describe-variable var))
7661 (prop (get var 'variable-interactive))
7662 (obsolete (car (get var 'byte-obsolete-variable)))
7663 (prompt (format "Set %s %s to value: " var
7664 (cond ((local-variable-p var)
7665 "(buffer-local)")
7666 ((or current-prefix-arg
7667 (local-variable-if-set-p var))
7668 "buffer-locally")
7669 (t "globally"))))
7670 (val (progn
7671 (when obsolete
7672 (message (concat "`%S' is obsolete; "
7673 (if (symbolp obsolete) "use `%S' instead" "%s"))
7674 var obsolete)
7675 (sit-for 3))
7676 (if prop
7677 ;; Use VAR's `variable-interactive' property
7678 ;; as an interactive spec for prompting.
7679 (call-interactively `(lambda (arg)
7680 (interactive ,prop)
7681 arg))
7682 (read-from-minibuffer prompt nil
7683 read-expression-map t
7684 'set-variable-value-history
7685 (format "%S" (symbol-value var)))))))
7686 (list var val current-prefix-arg)))
7688 (and (custom-variable-p variable)
7689 (not (get variable 'custom-type))
7690 (custom-load-symbol variable))
7691 (let ((type (get variable 'custom-type)))
7692 (when type
7693 ;; Match with custom type.
7694 (require 'cus-edit)
7695 (setq type (widget-convert type))
7696 (unless (widget-apply type :match value)
7697 (user-error "Value `%S' does not match type %S of %S"
7698 value (car type) variable))))
7700 (if make-local
7701 (make-local-variable variable))
7703 (set variable value)
7705 ;; Force a thorough redisplay for the case that the variable
7706 ;; has an effect on the display, like `tab-width' has.
7707 (force-mode-line-update))
7709 ;; Define the major mode for lists of completions.
7711 (defvar completion-list-mode-map
7712 (let ((map (make-sparse-keymap)))
7713 (define-key map [mouse-2] 'choose-completion)
7714 (define-key map [follow-link] 'mouse-face)
7715 (define-key map [down-mouse-2] nil)
7716 (define-key map "\C-m" 'choose-completion)
7717 (define-key map "\e\e\e" 'delete-completion-window)
7718 (define-key map [left] 'previous-completion)
7719 (define-key map [right] 'next-completion)
7720 (define-key map [?\t] 'next-completion)
7721 (define-key map [backtab] 'previous-completion)
7722 (define-key map "q" 'quit-window)
7723 (define-key map "z" 'kill-this-buffer)
7724 map)
7725 "Local map for completion list buffers.")
7727 ;; Completion mode is suitable only for specially formatted data.
7728 (put 'completion-list-mode 'mode-class 'special)
7730 (defvar completion-reference-buffer nil
7731 "Record the buffer that was current when the completion list was requested.
7732 This is a local variable in the completion list buffer.
7733 Initial value is nil to avoid some compiler warnings.")
7735 (defvar completion-no-auto-exit nil
7736 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7737 This also applies to other functions such as `choose-completion'.")
7739 (defvar completion-base-position nil
7740 "Position of the base of the text corresponding to the shown completions.
7741 This variable is used in the *Completions* buffers.
7742 Its value is a list of the form (START END) where START is the place
7743 where the completion should be inserted and END (if non-nil) is the end
7744 of the text to replace. If END is nil, point is used instead.")
7746 (defvar completion-list-insert-choice-function #'completion--replace
7747 "Function to use to insert the text chosen in *Completions*.
7748 Called with three arguments (BEG END TEXT), it should replace the text
7749 between BEG and END with TEXT. Expected to be set buffer-locally
7750 in the *Completions* buffer.")
7752 (defvar completion-base-size nil
7753 "Number of chars before point not involved in completion.
7754 This is a local variable in the completion list buffer.
7755 It refers to the chars in the minibuffer if completing in the
7756 minibuffer, or in `completion-reference-buffer' otherwise.
7757 Only characters in the field at point are included.
7759 If nil, Emacs determines which part of the tail end of the
7760 buffer's text is involved in completion by comparing the text
7761 directly.")
7762 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7764 (defun delete-completion-window ()
7765 "Delete the completion list window.
7766 Go to the window from which completion was requested."
7767 (interactive)
7768 (let ((buf completion-reference-buffer))
7769 (if (one-window-p t)
7770 (if (window-dedicated-p) (delete-frame))
7771 (delete-window (selected-window))
7772 (if (get-buffer-window buf)
7773 (select-window (get-buffer-window buf))))))
7775 (defun previous-completion (n)
7776 "Move to the previous item in the completion list."
7777 (interactive "p")
7778 (next-completion (- n)))
7780 (defun next-completion (n)
7781 "Move to the next item in the completion list.
7782 With prefix argument N, move N items (negative N means move backward)."
7783 (interactive "p")
7784 (let ((beg (point-min)) (end (point-max)))
7785 (while (and (> n 0) (not (eobp)))
7786 ;; If in a completion, move to the end of it.
7787 (when (get-text-property (point) 'mouse-face)
7788 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7789 ;; Move to start of next one.
7790 (unless (get-text-property (point) 'mouse-face)
7791 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7792 (setq n (1- n)))
7793 (while (and (< n 0) (not (bobp)))
7794 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7795 ;; If in a completion, move to the start of it.
7796 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7797 (goto-char (previous-single-property-change
7798 (point) 'mouse-face nil beg)))
7799 ;; Move to end of the previous completion.
7800 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7801 (goto-char (previous-single-property-change
7802 (point) 'mouse-face nil beg)))
7803 ;; Move to the start of that one.
7804 (goto-char (previous-single-property-change
7805 (point) 'mouse-face nil beg))
7806 (setq n (1+ n))))))
7808 (defun choose-completion (&optional event)
7809 "Choose the completion at point.
7810 If EVENT, use EVENT's position to determine the starting position."
7811 (interactive (list last-nonmenu-event))
7812 ;; In case this is run via the mouse, give temporary modes such as
7813 ;; isearch a chance to turn off.
7814 (run-hooks 'mouse-leave-buffer-hook)
7815 (with-current-buffer (window-buffer (posn-window (event-start event)))
7816 (let ((buffer completion-reference-buffer)
7817 (base-size completion-base-size)
7818 (base-position completion-base-position)
7819 (insert-function completion-list-insert-choice-function)
7820 (choice
7821 (save-excursion
7822 (goto-char (posn-point (event-start event)))
7823 (let (beg end)
7824 (cond
7825 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7826 (setq end (point) beg (1+ (point))))
7827 ((and (not (bobp))
7828 (get-text-property (1- (point)) 'mouse-face))
7829 (setq end (1- (point)) beg (point)))
7830 (t (error "No completion here")))
7831 (setq beg (previous-single-property-change beg 'mouse-face))
7832 (setq end (or (next-single-property-change end 'mouse-face)
7833 (point-max)))
7834 (buffer-substring-no-properties beg end)))))
7836 (unless (buffer-live-p buffer)
7837 (error "Destination buffer is dead"))
7838 (quit-window nil (posn-window (event-start event)))
7840 (with-current-buffer buffer
7841 (choose-completion-string
7842 choice buffer
7843 (or base-position
7844 (when base-size
7845 ;; Someone's using old completion code that doesn't know
7846 ;; about base-position yet.
7847 (list (+ base-size (field-beginning))))
7848 ;; If all else fails, just guess.
7849 (list (choose-completion-guess-base-position choice)))
7850 insert-function)))))
7852 ;; Delete the longest partial match for STRING
7853 ;; that can be found before POINT.
7854 (defun choose-completion-guess-base-position (string)
7855 (save-excursion
7856 (let ((opoint (point))
7857 len)
7858 ;; Try moving back by the length of the string.
7859 (goto-char (max (- (point) (length string))
7860 (minibuffer-prompt-end)))
7861 ;; See how far back we were actually able to move. That is the
7862 ;; upper bound on how much we can match and delete.
7863 (setq len (- opoint (point)))
7864 (if completion-ignore-case
7865 (setq string (downcase string)))
7866 (while (and (> len 0)
7867 (let ((tail (buffer-substring (point) opoint)))
7868 (if completion-ignore-case
7869 (setq tail (downcase tail)))
7870 (not (string= tail (substring string 0 len)))))
7871 (setq len (1- len))
7872 (forward-char 1))
7873 (point))))
7875 (defun choose-completion-delete-max-match (string)
7876 (declare (obsolete choose-completion-guess-base-position "23.2"))
7877 (delete-region (choose-completion-guess-base-position string) (point)))
7879 (defvar choose-completion-string-functions nil
7880 "Functions that may override the normal insertion of a completion choice.
7881 These functions are called in order with three arguments:
7882 CHOICE - the string to insert in the buffer,
7883 BUFFER - the buffer in which the choice should be inserted,
7884 BASE-POSITION - where to insert the completion.
7886 If a function in the list returns non-nil, that function is supposed
7887 to have inserted the CHOICE in the BUFFER, and possibly exited
7888 the minibuffer; no further functions will be called.
7890 If all functions in the list return nil, that means to use
7891 the default method of inserting the completion in BUFFER.")
7893 (defun choose-completion-string (choice &optional
7894 buffer base-position insert-function)
7895 "Switch to BUFFER and insert the completion choice CHOICE.
7896 BASE-POSITION says where to insert the completion.
7897 INSERT-FUNCTION says how to insert the completion and falls
7898 back on `completion-list-insert-choice-function' when nil."
7900 ;; If BUFFER is the minibuffer, exit the minibuffer
7901 ;; unless it is reading a file name and CHOICE is a directory,
7902 ;; or completion-no-auto-exit is non-nil.
7904 ;; Some older code may call us passing `base-size' instead of
7905 ;; `base-position'. It's difficult to make any use of `base-size',
7906 ;; so we just ignore it.
7907 (unless (consp base-position)
7908 (message "Obsolete `base-size' passed to choose-completion-string")
7909 (setq base-position nil))
7911 (let* ((buffer (or buffer completion-reference-buffer))
7912 (mini-p (minibufferp buffer)))
7913 ;; If BUFFER is a minibuffer, barf unless it's the currently
7914 ;; active minibuffer.
7915 (if (and mini-p
7916 (not (and (active-minibuffer-window)
7917 (equal buffer
7918 (window-buffer (active-minibuffer-window))))))
7919 (error "Minibuffer is not active for completion")
7920 ;; Set buffer so buffer-local choose-completion-string-functions works.
7921 (set-buffer buffer)
7922 (unless (run-hook-with-args-until-success
7923 'choose-completion-string-functions
7924 ;; The fourth arg used to be `mini-p' but was useless
7925 ;; (since minibufferp can be used on the `buffer' arg)
7926 ;; and indeed unused. The last used to be `base-size', so we
7927 ;; keep it to try and avoid breaking old code.
7928 choice buffer base-position nil)
7929 ;; This remove-text-properties should be unnecessary since `choice'
7930 ;; comes from buffer-substring-no-properties.
7931 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7932 ;; Insert the completion into the buffer where it was requested.
7933 (funcall (or insert-function completion-list-insert-choice-function)
7934 (or (car base-position) (point))
7935 (or (cadr base-position) (point))
7936 choice)
7937 ;; Update point in the window that BUFFER is showing in.
7938 (let ((window (get-buffer-window buffer t)))
7939 (set-window-point window (point)))
7940 ;; If completing for the minibuffer, exit it with this choice.
7941 (and (not completion-no-auto-exit)
7942 (minibufferp buffer)
7943 minibuffer-completion-table
7944 ;; If this is reading a file name, and the file name chosen
7945 ;; is a directory, don't exit the minibuffer.
7946 (let* ((result (buffer-substring (field-beginning) (point)))
7947 (bounds
7948 (completion-boundaries result minibuffer-completion-table
7949 minibuffer-completion-predicate
7950 "")))
7951 (if (eq (car bounds) (length result))
7952 ;; The completion chosen leads to a new set of completions
7953 ;; (e.g. it's a directory): don't exit the minibuffer yet.
7954 (let ((mini (active-minibuffer-window)))
7955 (select-window mini)
7956 (when minibuffer-auto-raise
7957 (raise-frame (window-frame mini))))
7958 (exit-minibuffer))))))))
7960 (define-derived-mode completion-list-mode nil "Completion List"
7961 "Major mode for buffers showing lists of possible completions.
7962 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
7963 to select the completion near point.
7964 Or click to select one with the mouse.
7966 \\{completion-list-mode-map}"
7967 (set (make-local-variable 'completion-base-size) nil))
7969 (defun completion-list-mode-finish ()
7970 "Finish setup of the completions buffer.
7971 Called from `temp-buffer-show-hook'."
7972 (when (eq major-mode 'completion-list-mode)
7973 (setq buffer-read-only t)))
7975 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
7978 ;; Variables and faces used in `completion-setup-function'.
7980 (defcustom completion-show-help t
7981 "Non-nil means show help message in *Completions* buffer."
7982 :type 'boolean
7983 :version "22.1"
7984 :group 'completion)
7986 ;; This function goes in completion-setup-hook, so that it is called
7987 ;; after the text of the completion list buffer is written.
7988 (defun completion-setup-function ()
7989 (let* ((mainbuf (current-buffer))
7990 (base-dir
7991 ;; FIXME: This is a bad hack. We try to set the default-directory
7992 ;; in the *Completions* buffer so that the relative file names
7993 ;; displayed there can be treated as valid file names, independently
7994 ;; from the completion context. But this suffers from many problems:
7995 ;; - It's not clear when the completions are file names. With some
7996 ;; completion tables (e.g. bzr revision specs), the listed
7997 ;; completions can mix file names and other things.
7998 ;; - It doesn't pay attention to possible quoting.
7999 ;; - With fancy completion styles, the code below will not always
8000 ;; find the right base directory.
8001 (if minibuffer-completing-file-name
8002 (file-name-as-directory
8003 (expand-file-name
8004 (buffer-substring (minibuffer-prompt-end)
8005 (- (point) (or completion-base-size 0))))))))
8006 (with-current-buffer standard-output
8007 (let ((base-size completion-base-size) ;Read before killing localvars.
8008 (base-position completion-base-position)
8009 (insert-fun completion-list-insert-choice-function))
8010 (completion-list-mode)
8011 (set (make-local-variable 'completion-base-size) base-size)
8012 (set (make-local-variable 'completion-base-position) base-position)
8013 (set (make-local-variable 'completion-list-insert-choice-function)
8014 insert-fun))
8015 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8016 (if base-dir (setq default-directory base-dir))
8017 ;; Maybe insert help string.
8018 (when completion-show-help
8019 (goto-char (point-min))
8020 (if (display-mouse-p)
8021 (insert "Click on a completion to select it.\n"))
8022 (insert (substitute-command-keys
8023 "In this buffer, type \\[choose-completion] to \
8024 select the completion near point.\n\n"))))))
8026 (add-hook 'completion-setup-hook 'completion-setup-function)
8028 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8029 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8031 (defun switch-to-completions ()
8032 "Select the completion list window."
8033 (interactive)
8034 (let ((window (or (get-buffer-window "*Completions*" 0)
8035 ;; Make sure we have a completions window.
8036 (progn (minibuffer-completion-help)
8037 (get-buffer-window "*Completions*" 0)))))
8038 (when window
8039 (select-window window)
8040 ;; In the new buffer, go to the first completion.
8041 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8042 (when (bobp)
8043 (next-completion 1)))))
8045 ;;; Support keyboard commands to turn on various modifiers.
8047 ;; These functions -- which are not commands -- each add one modifier
8048 ;; to the following event.
8050 (defun event-apply-alt-modifier (_ignore-prompt)
8051 "\\<function-key-map>Add the Alt modifier to the following event.
8052 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8053 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8054 (defun event-apply-super-modifier (_ignore-prompt)
8055 "\\<function-key-map>Add the Super modifier to the following event.
8056 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8057 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8058 (defun event-apply-hyper-modifier (_ignore-prompt)
8059 "\\<function-key-map>Add the Hyper modifier to the following event.
8060 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8061 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8062 (defun event-apply-shift-modifier (_ignore-prompt)
8063 "\\<function-key-map>Add the Shift modifier to the following event.
8064 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8065 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8066 (defun event-apply-control-modifier (_ignore-prompt)
8067 "\\<function-key-map>Add the Ctrl modifier to the following event.
8068 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8069 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8070 (defun event-apply-meta-modifier (_ignore-prompt)
8071 "\\<function-key-map>Add the Meta modifier to the following event.
8072 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8073 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8075 (defun event-apply-modifier (event symbol lshiftby prefix)
8076 "Apply a modifier flag to event EVENT.
8077 SYMBOL is the name of this modifier, as a symbol.
8078 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8079 PREFIX is the string that represents this modifier in an event type symbol."
8080 (if (numberp event)
8081 (cond ((eq symbol 'control)
8082 (if (and (<= (downcase event) ?z)
8083 (>= (downcase event) ?a))
8084 (- (downcase event) ?a -1)
8085 (if (and (<= (downcase event) ?Z)
8086 (>= (downcase event) ?A))
8087 (- (downcase event) ?A -1)
8088 (logior (lsh 1 lshiftby) event))))
8089 ((eq symbol 'shift)
8090 (if (and (<= (downcase event) ?z)
8091 (>= (downcase event) ?a))
8092 (upcase event)
8093 (logior (lsh 1 lshiftby) event)))
8095 (logior (lsh 1 lshiftby) event)))
8096 (if (memq symbol (event-modifiers event))
8097 event
8098 (let ((event-type (if (symbolp event) event (car event))))
8099 (setq event-type (intern (concat prefix (symbol-name event-type))))
8100 (if (symbolp event)
8101 event-type
8102 (cons event-type (cdr event)))))))
8104 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8105 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8106 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8107 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8108 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8109 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8111 ;;;; Keypad support.
8113 ;; Make the keypad keys act like ordinary typing keys. If people add
8114 ;; bindings for the function key symbols, then those bindings will
8115 ;; override these, so this shouldn't interfere with any existing
8116 ;; bindings.
8118 ;; Also tell read-char how to handle these keys.
8119 (mapc
8120 (lambda (keypad-normal)
8121 (let ((keypad (nth 0 keypad-normal))
8122 (normal (nth 1 keypad-normal)))
8123 (put keypad 'ascii-character normal)
8124 (define-key function-key-map (vector keypad) (vector normal))))
8125 ;; See also kp-keys bound in bindings.el.
8126 '((kp-space ?\s)
8127 (kp-tab ?\t)
8128 (kp-enter ?\r)
8129 (kp-separator ?,)
8130 (kp-equal ?=)
8131 ;; Do the same for various keys that are represented as symbols under
8132 ;; GUIs but naturally correspond to characters.
8133 (backspace 127)
8134 (delete 127)
8135 (tab ?\t)
8136 (linefeed ?\n)
8137 (clear ?\C-l)
8138 (return ?\C-m)
8139 (escape ?\e)
8142 ;;;;
8143 ;;;; forking a twin copy of a buffer.
8144 ;;;;
8146 (defvar clone-buffer-hook nil
8147 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8149 (defvar clone-indirect-buffer-hook nil
8150 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8152 (defun clone-process (process &optional newname)
8153 "Create a twin copy of PROCESS.
8154 If NEWNAME is nil, it defaults to PROCESS' name;
8155 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8156 If PROCESS is associated with a buffer, the new process will be associated
8157 with the current buffer instead.
8158 Returns nil if PROCESS has already terminated."
8159 (setq newname (or newname (process-name process)))
8160 (if (string-match "<[0-9]+>\\'" newname)
8161 (setq newname (substring newname 0 (match-beginning 0))))
8162 (when (memq (process-status process) '(run stop open))
8163 (let* ((process-connection-type (process-tty-name process))
8164 (new-process
8165 (if (memq (process-status process) '(open))
8166 (let ((args (process-contact process t)))
8167 (setq args (plist-put args :name newname))
8168 (setq args (plist-put args :buffer
8169 (if (process-buffer process)
8170 (current-buffer))))
8171 (apply 'make-network-process args))
8172 (apply 'start-process newname
8173 (if (process-buffer process) (current-buffer))
8174 (process-command process)))))
8175 (set-process-query-on-exit-flag
8176 new-process (process-query-on-exit-flag process))
8177 (set-process-inherit-coding-system-flag
8178 new-process (process-inherit-coding-system-flag process))
8179 (set-process-filter new-process (process-filter process))
8180 (set-process-sentinel new-process (process-sentinel process))
8181 (set-process-plist new-process (copy-sequence (process-plist process)))
8182 new-process)))
8184 ;; things to maybe add (currently partly covered by `funcall mode'):
8185 ;; - syntax-table
8186 ;; - overlays
8187 (defun clone-buffer (&optional newname display-flag)
8188 "Create and return a twin copy of the current buffer.
8189 Unlike an indirect buffer, the new buffer can be edited
8190 independently of the old one (if it is not read-only).
8191 NEWNAME is the name of the new buffer. It may be modified by
8192 adding or incrementing <N> at the end as necessary to create a
8193 unique buffer name. If nil, it defaults to the name of the
8194 current buffer, with the proper suffix. If DISPLAY-FLAG is
8195 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8196 clone a file-visiting buffer, or a buffer whose major mode symbol
8197 has a non-nil `no-clone' property, results in an error.
8199 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8200 current buffer with appropriate suffix. However, if a prefix
8201 argument is given, then the command prompts for NEWNAME in the
8202 minibuffer.
8204 This runs the normal hook `clone-buffer-hook' in the new buffer
8205 after it has been set up properly in other respects."
8206 (interactive
8207 (progn
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 (list (if current-prefix-arg
8213 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8214 t)))
8215 (if buffer-file-name
8216 (error "Cannot clone a file-visiting buffer"))
8217 (if (get major-mode 'no-clone)
8218 (error "Cannot clone a buffer in %s mode" mode-name))
8219 (setq newname (or newname (buffer-name)))
8220 (if (string-match "<[0-9]+>\\'" newname)
8221 (setq newname (substring newname 0 (match-beginning 0))))
8222 (let ((buf (current-buffer))
8223 (ptmin (point-min))
8224 (ptmax (point-max))
8225 (pt (point))
8226 (mk (if mark-active (mark t)))
8227 (modified (buffer-modified-p))
8228 (mode major-mode)
8229 (lvars (buffer-local-variables))
8230 (process (get-buffer-process (current-buffer)))
8231 (new (generate-new-buffer (or newname (buffer-name)))))
8232 (save-restriction
8233 (widen)
8234 (with-current-buffer new
8235 (insert-buffer-substring buf)))
8236 (with-current-buffer new
8237 (narrow-to-region ptmin ptmax)
8238 (goto-char pt)
8239 (if mk (set-mark mk))
8240 (set-buffer-modified-p modified)
8242 ;; Clone the old buffer's process, if any.
8243 (when process (clone-process process))
8245 ;; Now set up the major mode.
8246 (funcall mode)
8248 ;; Set up other local variables.
8249 (mapc (lambda (v)
8250 (condition-case () ;in case var is read-only
8251 (if (symbolp v)
8252 (makunbound v)
8253 (set (make-local-variable (car v)) (cdr v)))
8254 (error nil)))
8255 lvars)
8257 ;; Run any hooks (typically set up by the major mode
8258 ;; for cloning to work properly).
8259 (run-hooks 'clone-buffer-hook))
8260 (if display-flag
8261 ;; Presumably the current buffer is shown in the selected frame, so
8262 ;; we want to display the clone elsewhere.
8263 (let ((same-window-regexps nil)
8264 (same-window-buffer-names))
8265 (pop-to-buffer new)))
8266 new))
8269 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8270 "Create an indirect buffer that is a twin copy of the current buffer.
8272 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8273 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8274 or if not called with a prefix arg, NEWNAME defaults to the current
8275 buffer's name. The name is modified by adding a `<N>' suffix to it
8276 or by incrementing the N in an existing suffix. Trying to clone a
8277 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8278 property results in an error.
8280 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8281 This is always done when called interactively.
8283 Optional third arg NORECORD non-nil means do not put this buffer at the
8284 front of the list of recently selected ones.
8286 Returns the newly created indirect buffer."
8287 (interactive
8288 (progn
8289 (if (get major-mode 'no-clone-indirect)
8290 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8291 (list (if current-prefix-arg
8292 (read-buffer "Name of indirect buffer: " (current-buffer)))
8293 t)))
8294 (if (get major-mode 'no-clone-indirect)
8295 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8296 (setq newname (or newname (buffer-name)))
8297 (if (string-match "<[0-9]+>\\'" newname)
8298 (setq newname (substring newname 0 (match-beginning 0))))
8299 (let* ((name (generate-new-buffer-name newname))
8300 (buffer (make-indirect-buffer (current-buffer) name t)))
8301 (with-current-buffer buffer
8302 (run-hooks 'clone-indirect-buffer-hook))
8303 (when display-flag
8304 (pop-to-buffer buffer norecord))
8305 buffer))
8308 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8309 "Like `clone-indirect-buffer' but display in another window."
8310 (interactive
8311 (progn
8312 (if (get major-mode 'no-clone-indirect)
8313 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8314 (list (if current-prefix-arg
8315 (read-buffer "Name of indirect buffer: " (current-buffer)))
8316 t)))
8317 (let ((pop-up-windows t))
8318 (clone-indirect-buffer newname display-flag norecord)))
8321 ;;; Handling of Backspace and Delete keys.
8323 (defcustom normal-erase-is-backspace 'maybe
8324 "Set the default behavior of the Delete and Backspace keys.
8326 If set to t, Delete key deletes forward and Backspace key deletes
8327 backward.
8329 If set to nil, both Delete and Backspace keys delete backward.
8331 If set to `maybe' (which is the default), Emacs automatically
8332 selects a behavior. On window systems, the behavior depends on
8333 the keyboard used. If the keyboard has both a Backspace key and
8334 a Delete key, and both are mapped to their usual meanings, the
8335 option's default value is set to t, so that Backspace can be used
8336 to delete backward, and Delete can be used to delete forward.
8338 If not running under a window system, customizing this option
8339 accomplishes a similar effect by mapping C-h, which is usually
8340 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8341 via `keyboard-translate'. The former functionality of C-h is
8342 available on the F1 key. You should probably not use this
8343 setting if you don't have both Backspace, Delete and F1 keys.
8345 Setting this variable with setq doesn't take effect. Programmatically,
8346 call `normal-erase-is-backspace-mode' (which see) instead."
8347 :type '(choice (const :tag "Off" nil)
8348 (const :tag "Maybe" maybe)
8349 (other :tag "On" t))
8350 :group 'editing-basics
8351 :version "21.1"
8352 :set (lambda (symbol value)
8353 ;; The fboundp is because of a problem with :set when
8354 ;; dumping Emacs. It doesn't really matter.
8355 (if (fboundp 'normal-erase-is-backspace-mode)
8356 (normal-erase-is-backspace-mode (or value 0))
8357 (set-default symbol value))))
8359 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8360 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8361 (unless frame (setq frame (selected-frame)))
8362 (with-selected-frame frame
8363 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8364 (normal-erase-is-backspace-mode
8365 (if (if (eq normal-erase-is-backspace 'maybe)
8366 (and (not noninteractive)
8367 (or (memq system-type '(ms-dos windows-nt))
8368 (memq window-system '(w32 ns))
8369 (and (memq window-system '(x))
8370 (fboundp 'x-backspace-delete-keys-p)
8371 (x-backspace-delete-keys-p))
8372 ;; If the terminal Emacs is running on has erase char
8373 ;; set to ^H, use the Backspace key for deleting
8374 ;; backward, and the Delete key for deleting forward.
8375 (and (null window-system)
8376 (eq tty-erase-char ?\^H))))
8377 normal-erase-is-backspace)
8378 1 0)))))
8380 (define-minor-mode normal-erase-is-backspace-mode
8381 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8382 With a prefix argument ARG, enable this feature if ARG is
8383 positive, and disable it otherwise. If called from Lisp, enable
8384 the mode if ARG is omitted or nil.
8386 On window systems, when this mode is on, Delete is mapped to C-d
8387 and Backspace is mapped to DEL; when this mode is off, both
8388 Delete and Backspace are mapped to DEL. (The remapping goes via
8389 `local-function-key-map', so binding Delete or Backspace in the
8390 global or local keymap will override that.)
8392 In addition, on window systems, the bindings of C-Delete, M-Delete,
8393 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8394 the global keymap in accordance with the functionality of Delete and
8395 Backspace. For example, if Delete is remapped to C-d, which deletes
8396 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8397 to DEL, which deletes backward, C-Delete is bound to
8398 `backward-kill-word'.
8400 If not running on a window system, a similar effect is accomplished by
8401 remapping C-h (normally produced by the Backspace key) and DEL via
8402 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8403 to C-d; if it's off, the keys are not remapped.
8405 When not running on a window system, and this mode is turned on, the
8406 former functionality of C-h is available on the F1 key. You should
8407 probably not turn on this mode on a text-only terminal if you don't
8408 have both Backspace, Delete and F1 keys.
8410 See also `normal-erase-is-backspace'."
8411 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8412 . (lambda (v)
8413 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8414 (if v 1 0))))
8415 (let ((enabled (eq 1 (terminal-parameter
8416 nil 'normal-erase-is-backspace))))
8418 (cond ((or (memq window-system '(x w32 ns pc))
8419 (memq system-type '(ms-dos windows-nt)))
8420 (let ((bindings
8421 `(([M-delete] [M-backspace])
8422 ([C-M-delete] [C-M-backspace])
8423 ([?\e C-delete] [?\e C-backspace]))))
8425 (if enabled
8426 (progn
8427 (define-key local-function-key-map [delete] [deletechar])
8428 (define-key local-function-key-map [kp-delete] [deletechar])
8429 (define-key local-function-key-map [backspace] [?\C-?])
8430 (dolist (b bindings)
8431 ;; Not sure if input-decode-map is really right, but
8432 ;; keyboard-translate-table (used below) only works
8433 ;; for integer events, and key-translation-table is
8434 ;; global (like the global-map, used earlier).
8435 (define-key input-decode-map (car b) nil)
8436 (define-key input-decode-map (cadr b) nil)))
8437 (define-key local-function-key-map [delete] [?\C-?])
8438 (define-key local-function-key-map [kp-delete] [?\C-?])
8439 (define-key local-function-key-map [backspace] [?\C-?])
8440 (dolist (b bindings)
8441 (define-key input-decode-map (car b) (cadr b))
8442 (define-key input-decode-map (cadr b) (car b))))))
8444 (if enabled
8445 (progn
8446 (keyboard-translate ?\C-h ?\C-?)
8447 (keyboard-translate ?\C-? ?\C-d))
8448 (keyboard-translate ?\C-h ?\C-h)
8449 (keyboard-translate ?\C-? ?\C-?))))
8451 (if (called-interactively-p 'interactive)
8452 (message "Delete key deletes %s"
8453 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8454 "forward" "backward")))))
8456 (defvar vis-mode-saved-buffer-invisibility-spec nil
8457 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8459 (define-minor-mode read-only-mode
8460 "Change whether the current buffer is read-only.
8461 With prefix argument ARG, make the buffer read-only if ARG is
8462 positive, otherwise make it writable. If buffer is read-only
8463 and `view-read-only' is non-nil, enter view mode.
8465 Do not call this from a Lisp program unless you really intend to
8466 do the same thing as the \\[read-only-mode] command, including
8467 possibly enabling or disabling View mode. Also, note that this
8468 command works by setting the variable `buffer-read-only', which
8469 does not affect read-only regions caused by text properties. To
8470 ignore read-only status in a Lisp program (whether due to text
8471 properties or buffer state), bind `inhibit-read-only' temporarily
8472 to a non-nil value."
8473 :variable buffer-read-only
8474 (cond
8475 ((and (not buffer-read-only) view-mode)
8476 (View-exit-and-edit)
8477 (make-local-variable 'view-read-only)
8478 (setq view-read-only t)) ; Must leave view mode.
8479 ((and buffer-read-only view-read-only
8480 ;; If view-mode is already active, `view-mode-enter' is a nop.
8481 (not view-mode)
8482 (not (eq (get major-mode 'mode-class) 'special)))
8483 (view-mode-enter))))
8485 (define-minor-mode visible-mode
8486 "Toggle making all invisible text temporarily visible (Visible mode).
8487 With a prefix argument ARG, enable Visible mode if ARG is
8488 positive, and disable it otherwise. If called from Lisp, enable
8489 the mode if ARG is omitted or nil.
8491 This mode works by saving the value of `buffer-invisibility-spec'
8492 and setting it to nil."
8493 :lighter " Vis"
8494 :group 'editing-basics
8495 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8496 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8497 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8498 (when visible-mode
8499 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8500 buffer-invisibility-spec)
8501 (setq buffer-invisibility-spec nil)))
8503 (defvar messages-buffer-mode-map
8504 (let ((map (make-sparse-keymap)))
8505 (set-keymap-parent map special-mode-map)
8506 (define-key map "g" nil) ; nothing to revert
8507 map))
8509 (define-derived-mode messages-buffer-mode special-mode "Messages"
8510 "Major mode used in the \"*Messages*\" buffer.")
8512 (defun messages-buffer ()
8513 "Return the \"*Messages*\" buffer.
8514 If it does not exist, create and it switch it to `messages-buffer-mode'."
8515 (or (get-buffer "*Messages*")
8516 (with-current-buffer (get-buffer-create "*Messages*")
8517 (messages-buffer-mode)
8518 (current-buffer))))
8521 ;; Minibuffer prompt stuff.
8523 ;;(defun minibuffer-prompt-modification (start end)
8524 ;; (error "You cannot modify the prompt"))
8527 ;;(defun minibuffer-prompt-insertion (start end)
8528 ;; (let ((inhibit-modification-hooks t))
8529 ;; (delete-region start end)
8530 ;; ;; Discard undo information for the text insertion itself
8531 ;; ;; and for the text deletion.above.
8532 ;; (when (consp buffer-undo-list)
8533 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8534 ;; (message "You cannot modify the prompt")))
8537 ;;(setq minibuffer-prompt-properties
8538 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8539 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8542 ;;;; Problematic external packages.
8544 ;; rms says this should be done by specifying symbols that define
8545 ;; versions together with bad values. This is therefore not as
8546 ;; flexible as it could be. See the thread:
8547 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8548 (defconst bad-packages-alist
8549 ;; Not sure exactly which semantic versions have problems.
8550 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8551 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8552 "The version of `semantic' loaded does not work in Emacs 22.
8553 It can cause constant high CPU load.
8554 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8555 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8556 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8557 ;; provided the `CUA-mode' feature. Since this is no longer true,
8558 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8559 (CUA-mode t nil
8560 "CUA-mode is now part of the standard GNU Emacs distribution,
8561 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8563 You have loaded an older version of CUA-mode which does not work
8564 correctly with this version of Emacs. You should remove the old
8565 version and use the one distributed with Emacs."))
8566 "Alist of packages known to cause problems in this version of Emacs.
8567 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8568 PACKAGE is either a regular expression to match file names, or a
8569 symbol (a feature name), like for `with-eval-after-load'.
8570 SYMBOL is either the name of a string variable, or t. Upon
8571 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8572 warning using STRING as the message.")
8574 (defun bad-package-check (package)
8575 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8576 (condition-case nil
8577 (let* ((list (assoc package bad-packages-alist))
8578 (symbol (nth 1 list)))
8579 (and list
8580 (boundp symbol)
8581 (or (eq symbol t)
8582 (and (stringp (setq symbol (eval symbol)))
8583 (string-match-p (nth 2 list) symbol)))
8584 (display-warning package (nth 3 list) :warning)))
8585 (error nil)))
8587 (dolist (elem bad-packages-alist)
8588 (let ((pkg (car elem)))
8589 (with-eval-after-load pkg
8590 (bad-package-check pkg))))
8593 ;;; Generic dispatcher commands
8595 ;; Macro `define-alternatives' is used to create generic commands.
8596 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8597 ;; that can have different alternative implementations where choosing
8598 ;; among them is exclusively a matter of user preference.
8600 ;; (define-alternatives COMMAND) creates a new interactive command
8601 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8602 ;; Typically, the user will not need to customize this variable; packages
8603 ;; wanting to add alternative implementations should use
8605 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8607 (defmacro define-alternatives (command &rest customizations)
8608 "Define the new command `COMMAND'.
8610 The argument `COMMAND' should be a symbol.
8612 Running `M-x COMMAND RET' for the first time prompts for which
8613 alternative to use and records the selected command as a custom
8614 variable.
8616 Running `C-u M-x COMMAND RET' prompts again for an alternative
8617 and overwrites the previous choice.
8619 The variable `COMMAND-alternatives' contains an alist with
8620 alternative implementations of COMMAND. `define-alternatives'
8621 does not have any effect until this variable is set.
8623 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8624 `defcustom' keywords and values to add to the declaration of
8625 `COMMAND-alternatives' (typically :group and :version)."
8626 (let* ((command-name (symbol-name command))
8627 (varalt-name (concat command-name "-alternatives"))
8628 (varalt-sym (intern varalt-name))
8629 (varimp-sym (intern (concat command-name "--implementation"))))
8630 `(progn
8632 (defcustom ,varalt-sym nil
8633 ,(format "Alist of alternative implementations for the `%s' command.
8635 Each entry must be a pair (ALTNAME . ALTFUN), where:
8636 ALTNAME - The name shown at user to describe the alternative implementation.
8637 ALTFUN - The function called to implement this alternative."
8638 command-name)
8639 :type '(alist :key-type string :value-type function)
8640 ,@customizations)
8642 (put ',varalt-sym 'definition-name ',command)
8643 (defvar ,varimp-sym nil "Internal use only.")
8645 (defun ,command (&optional arg)
8646 ,(format "Run generic command `%s'.
8647 If used for the first time, or with interactive ARG, ask the user which
8648 implementation to use for `%s'. The variable `%s'
8649 contains the list of implementations currently supported for this command."
8650 command-name command-name varalt-name)
8651 (interactive "P")
8652 (when (or arg (null ,varimp-sym))
8653 (let ((val (completing-read
8654 ,(format-message
8655 "Select implementation for command `%s': "
8656 command-name)
8657 ,varalt-sym nil t)))
8658 (unless (string-equal val "")
8659 (when (null ,varimp-sym)
8660 (message
8661 "Use C-u M-x %s RET`to select another implementation"
8662 ,command-name)
8663 (sit-for 3))
8664 (customize-save-variable ',varimp-sym
8665 (cdr (assoc-string val ,varalt-sym))))))
8666 (if ,varimp-sym
8667 (call-interactively ,varimp-sym)
8668 (message "%s" ,(format-message
8669 "No implementation selected for command `%s'"
8670 command-name)))))))
8673 ;;; Functions for changing capitalization that Do What I Mean
8674 (defun upcase-dwim (arg)
8675 "Upcase words in the region, if active; if not, upcase word at point.
8676 If the region is active, this function calls `upcase-region'.
8677 Otherwise, it calls `upcase-word', with prefix argument passed to it
8678 to upcase ARG words."
8679 (interactive "*p")
8680 (if (use-region-p)
8681 (upcase-region (region-beginning) (region-end))
8682 (upcase-word arg)))
8684 (defun downcase-dwim (arg)
8685 "Downcase words in the region, if active; if not, downcase word at point.
8686 If the region is active, this function calls `downcase-region'.
8687 Otherwise, it calls `downcase-word', with prefix argument passed to it
8688 to downcase ARG words."
8689 (interactive "*p")
8690 (if (use-region-p)
8691 (downcase-region (region-beginning) (region-end))
8692 (downcase-word arg)))
8694 (defun capitalize-dwim (arg)
8695 "Capitalize words in the region, if active; if not, capitalize word at point.
8696 If the region is active, this function calls `capitalize-region'.
8697 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8698 to capitalize ARG words."
8699 (interactive "*p")
8700 (if (use-region-p)
8701 (capitalize-region (region-beginning) (region-end))
8702 (capitalize-word arg)))
8706 (provide 'simple)
8708 ;;; simple.el ends here