Show ancestor buffer in 3way merges
[emacs.git] / lisp / simple.el
blobf110c6f3267e9b0f07644c30da2f9726bd9914d6
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2017 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 shell-command-dont-erase-buffer nil
41 "If non-nil, output buffer is not erased between shell commands.
42 Also, a non-nil value set the point in the output buffer
43 once the command complete.
44 The value `beg-last-out' set point at the beginning of the output,
45 `end-last-out' set point at the end of the buffer, `save-point'
46 restore the buffer position before the command."
47 :type '(choice
48 (const :tag "Erase buffer" nil)
49 (const :tag "Set point to beginning of last output" beg-last-out)
50 (const :tag "Set point to end of last output" end-last-out)
51 (const :tag "Save point" save-point))
52 :group 'shell
53 :version "26.1")
55 (defvar shell-command-saved-pos nil
56 "Point position in the output buffer after command complete.
57 It is an alist (BUFFER . POS), where BUFFER is the output
58 buffer, and POS is the point position in BUFFER once the command finish.
59 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
61 (defcustom idle-update-delay 0.5
62 "Idle time delay before updating various things on the screen.
63 Various Emacs features that update auxiliary information when point moves
64 wait this many seconds after Emacs becomes idle before doing an update."
65 :type 'number
66 :group 'display
67 :version "22.1")
69 (defgroup killing nil
70 "Killing and yanking commands."
71 :group 'editing)
73 (defgroup paren-matching nil
74 "Highlight (un)matching of parens and expressions."
75 :group 'matching)
77 ;;; next-error support framework
79 (defgroup next-error nil
80 "`next-error' support framework."
81 :group 'compilation
82 :version "22.1")
84 (defface next-error
85 '((t (:inherit region)))
86 "Face used to highlight next error locus."
87 :group 'next-error
88 :version "22.1")
90 (defcustom next-error-highlight 0.5
91 "Highlighting of locations in selected source buffers.
92 If a number, highlight the locus in `next-error' face for the given time
93 in seconds, or until the next command is executed.
94 If t, highlight the locus until the next command is executed, or until
95 some other locus replaces it.
96 If nil, don't highlight the locus in the source buffer.
97 If `fringe-arrow', indicate the locus by the fringe arrow
98 indefinitely until some other locus replaces it."
99 :type '(choice (number :tag "Highlight for specified time")
100 (const :tag "Semipermanent highlighting" t)
101 (const :tag "No highlighting" nil)
102 (const :tag "Fringe arrow" fringe-arrow))
103 :group 'next-error
104 :version "22.1")
106 (defcustom next-error-highlight-no-select 0.5
107 "Highlighting of locations in `next-error-no-select'.
108 If number, highlight the locus in `next-error' face for given time in seconds.
109 If t, highlight the locus indefinitely until some other locus replaces it.
110 If nil, don't highlight the locus in the source buffer.
111 If `fringe-arrow', indicate the locus by the fringe arrow
112 indefinitely until some other locus replaces it."
113 :type '(choice (number :tag "Highlight for specified time")
114 (const :tag "Semipermanent highlighting" t)
115 (const :tag "No highlighting" nil)
116 (const :tag "Fringe arrow" fringe-arrow))
117 :group 'next-error
118 :version "22.1")
120 (defcustom next-error-recenter nil
121 "Display the line in the visited source file recentered as specified.
122 If non-nil, the value is passed directly to `recenter'."
123 :type '(choice (integer :tag "Line to recenter to")
124 (const :tag "Center of window" (4))
125 (const :tag "No recentering" nil))
126 :group 'next-error
127 :version "23.1")
129 (defcustom next-error-hook nil
130 "List of hook functions run by `next-error' after visiting source file."
131 :type 'hook
132 :group 'next-error)
134 (defvar next-error-highlight-timer nil)
136 (defvar next-error-overlay-arrow-position nil)
137 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
138 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
140 (defvar next-error-last-buffer nil
141 "The most recent `next-error' buffer.
142 A buffer becomes most recent when its compilation, grep, or
143 similar mode is started, or when it is used with \\[next-error]
144 or \\[compile-goto-error].")
146 (defvar next-error-function nil
147 "Function to use to find the next error in the current buffer.
148 The function is called with 2 parameters:
149 ARG is an integer specifying by how many errors to move.
150 RESET is a boolean which, if non-nil, says to go back to the beginning
151 of the errors before moving.
152 Major modes providing compile-like functionality should set this variable
153 to indicate to `next-error' that this is a candidate buffer and how
154 to navigate in it.")
155 (make-variable-buffer-local 'next-error-function)
157 (defvar next-error-move-function nil
158 "Function to use to move to an error locus.
159 It takes two arguments, a buffer position in the error buffer
160 and a buffer position in the error locus buffer.
161 The buffer for the error locus should already be current.
162 nil means use goto-char using the second argument position.")
163 (make-variable-buffer-local 'next-error-move-function)
165 (defsubst next-error-buffer-p (buffer
166 &optional avoid-current
167 extra-test-inclusive
168 extra-test-exclusive)
169 "Return non-nil if BUFFER is a `next-error' capable buffer.
170 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
171 return nil.
173 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
174 BUFFER would not normally qualify. If it returns non-nil, BUFFER
175 is considered `next-error' capable, anyway, and the function
176 returns non-nil.
178 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
179 buffer would normally qualify. If it returns nil, BUFFER is
180 rejected, and the function returns nil."
181 (and (buffer-name buffer) ;First make sure it's live.
182 (not (and avoid-current (eq buffer (current-buffer))))
183 (with-current-buffer buffer
184 (if next-error-function ; This is the normal test.
185 ;; Optionally reject some buffers.
186 (if extra-test-exclusive
187 (funcall extra-test-exclusive)
189 ;; Optionally accept some other buffers.
190 (and extra-test-inclusive
191 (funcall extra-test-inclusive))))))
193 (defun next-error-find-buffer (&optional avoid-current
194 extra-test-inclusive
195 extra-test-exclusive)
196 "Return a `next-error' capable buffer.
198 If AVOID-CURRENT is non-nil, treat the current buffer
199 as an absolute last resort only.
201 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
202 that normally would not qualify. If it returns t, the buffer
203 in question is treated as usable.
205 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
206 that would normally be considered usable. If it returns nil,
207 that buffer is rejected."
209 ;; 1. If one window on the selected frame displays such buffer, return it.
210 (let ((window-buffers
211 (delete-dups
212 (delq nil (mapcar (lambda (w)
213 (if (next-error-buffer-p
214 (window-buffer w)
215 avoid-current
216 extra-test-inclusive extra-test-exclusive)
217 (window-buffer w)))
218 (window-list))))))
219 (if (eq (length window-buffers) 1)
220 (car window-buffers)))
221 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
222 (if (and next-error-last-buffer
223 (next-error-buffer-p next-error-last-buffer avoid-current
224 extra-test-inclusive extra-test-exclusive))
225 next-error-last-buffer)
226 ;; 3. If the current buffer is acceptable, choose it.
227 (if (next-error-buffer-p (current-buffer) avoid-current
228 extra-test-inclusive extra-test-exclusive)
229 (current-buffer))
230 ;; 4. Look for any acceptable buffer.
231 (let ((buffers (buffer-list)))
232 (while (and buffers
233 (not (next-error-buffer-p
234 (car buffers) avoid-current
235 extra-test-inclusive extra-test-exclusive)))
236 (setq buffers (cdr buffers)))
237 (car buffers))
238 ;; 5. Use the current buffer as a last resort if it qualifies,
239 ;; even despite AVOID-CURRENT.
240 (and avoid-current
241 (next-error-buffer-p (current-buffer) nil
242 extra-test-inclusive extra-test-exclusive)
243 (progn
244 (message "This is the only buffer with error message locations")
245 (current-buffer)))
246 ;; 6. Give up.
247 (error "No buffers contain error message locations")))
249 (defun next-error (&optional arg reset)
250 "Visit next `next-error' message and corresponding source code.
252 If all the error messages parsed so far have been processed already,
253 the message buffer is checked for new ones.
255 A prefix ARG specifies how many error messages to move;
256 negative means move back to previous error messages.
257 Just \\[universal-argument] as a prefix means reparse the error message buffer
258 and start at the first error.
260 The RESET argument specifies that we should restart from the beginning.
262 \\[next-error] normally uses the most recently started
263 compilation, grep, or occur buffer. It can also operate on any
264 buffer with output from the \\[compile], \\[grep] commands, or,
265 more generally, on any buffer in Compilation mode or with
266 Compilation Minor mode enabled, or any buffer in which
267 `next-error-function' is bound to an appropriate function.
268 To specify use of a particular buffer for error messages, type
269 \\[next-error] in that buffer when it is the only one displayed
270 in the current frame.
272 Once \\[next-error] has chosen the buffer for error messages, it
273 runs `next-error-hook' with `run-hooks', and stays with that buffer
274 until you use it in some other buffer which uses Compilation mode
275 or Compilation Minor mode.
277 To control which errors are matched, customize the variable
278 `compilation-error-regexp-alist'."
279 (interactive "P")
280 (if (consp arg) (setq reset t arg nil))
281 (when (setq next-error-last-buffer (next-error-find-buffer))
282 ;; we know here that next-error-function is a valid symbol we can funcall
283 (with-current-buffer next-error-last-buffer
284 (funcall next-error-function (prefix-numeric-value arg) reset)
285 (when next-error-recenter
286 (recenter next-error-recenter))
287 (run-hooks 'next-error-hook))))
289 (defun next-error-internal ()
290 "Visit the source code corresponding to the `next-error' message at point."
291 (setq next-error-last-buffer (current-buffer))
292 ;; we know here that next-error-function is a valid symbol we can funcall
293 (with-current-buffer next-error-last-buffer
294 (funcall next-error-function 0 nil)
295 (when next-error-recenter
296 (recenter next-error-recenter))
297 (run-hooks 'next-error-hook)))
299 (defalias 'goto-next-locus 'next-error)
300 (defalias 'next-match 'next-error)
302 (defun previous-error (&optional n)
303 "Visit previous `next-error' message and corresponding source code.
305 Prefix arg N says how many error messages to move backwards (or
306 forwards, if negative).
308 This operates on the output from the \\[compile] and \\[grep] commands."
309 (interactive "p")
310 (next-error (- (or n 1))))
312 (defun first-error (&optional n)
313 "Restart at the first error.
314 Visit corresponding source code.
315 With prefix arg N, visit the source code of the Nth error.
316 This operates on the output from the \\[compile] command, for instance."
317 (interactive "p")
318 (next-error n t))
320 (defun next-error-no-select (&optional n)
321 "Move point to the next error in the `next-error' buffer and highlight match.
322 Prefix arg N says how many error messages to move forwards (or
323 backwards, if negative).
324 Finds and highlights the source line like \\[next-error], but does not
325 select the source buffer."
326 (interactive "p")
327 (let ((next-error-highlight next-error-highlight-no-select))
328 (next-error n))
329 (pop-to-buffer next-error-last-buffer))
331 (defun previous-error-no-select (&optional n)
332 "Move point to the previous error in the `next-error' buffer and highlight match.
333 Prefix arg N says how many error messages to move backwards (or
334 forwards, if negative).
335 Finds and highlights the source line like \\[previous-error], but does not
336 select the source buffer."
337 (interactive "p")
338 (next-error-no-select (- (or n 1))))
340 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
341 (defvar next-error-follow-last-line nil)
343 (define-minor-mode next-error-follow-minor-mode
344 "Minor mode for compilation, occur and diff modes.
345 With a prefix argument ARG, enable mode if ARG is positive, and
346 disable it otherwise. If called from Lisp, enable mode if ARG is
347 omitted or nil.
348 When turned on, cursor motion in the compilation, grep, occur or diff
349 buffer causes automatic display of the corresponding source code location."
350 :group 'next-error :init-value nil :lighter " Fol"
351 (if (not next-error-follow-minor-mode)
352 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
353 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
354 (make-local-variable 'next-error-follow-last-line)))
356 ;; Used as a `post-command-hook' by `next-error-follow-mode'
357 ;; for the *Compilation* *grep* and *Occur* buffers.
358 (defun next-error-follow-mode-post-command-hook ()
359 (unless (equal next-error-follow-last-line (line-number-at-pos))
360 (setq next-error-follow-last-line (line-number-at-pos))
361 (condition-case nil
362 (let ((compilation-context-lines nil))
363 (setq compilation-current-error (point))
364 (next-error-no-select 0))
365 (error t))))
370 (defun fundamental-mode ()
371 "Major mode not specialized for anything in particular.
372 Other major modes are defined by comparison with this one."
373 (interactive)
374 (kill-all-local-variables)
375 (run-mode-hooks))
377 ;; Special major modes to view specially formatted data rather than files.
379 (defvar special-mode-map
380 (let ((map (make-sparse-keymap)))
381 (suppress-keymap map)
382 (define-key map "q" 'quit-window)
383 (define-key map " " 'scroll-up-command)
384 (define-key map [?\S-\ ] 'scroll-down-command)
385 (define-key map "\C-?" 'scroll-down-command)
386 (define-key map "?" 'describe-mode)
387 (define-key map "h" 'describe-mode)
388 (define-key map ">" 'end-of-buffer)
389 (define-key map "<" 'beginning-of-buffer)
390 (define-key map "g" 'revert-buffer)
391 map))
393 (put 'special-mode 'mode-class 'special)
394 (define-derived-mode special-mode nil "Special"
395 "Parent major mode from which special major modes should inherit."
396 (setq buffer-read-only t))
398 ;; Making and deleting lines.
400 (defvar self-insert-uses-region-functions nil
401 "Special hook to tell if `self-insert-command' will use the region.
402 It must be called via `run-hook-with-args-until-success' with no arguments.
403 Any `post-self-insert-command' which consumes the region should
404 register a function on this hook so that things like `delete-selection-mode'
405 can refrain from consuming the region.")
407 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
408 "Propertized string representing a hard newline character.")
410 (defun newline (&optional arg interactive)
411 "Insert a newline, and move to left margin of the new line if it's blank.
412 If option `use-hard-newlines' is non-nil, the newline is marked with the
413 text-property `hard'.
414 With ARG, insert that many newlines.
416 If `electric-indent-mode' is enabled, this indents the final new line
417 that it adds, and reindents the preceding line. To just insert
418 a newline, use \\[electric-indent-just-newline].
420 Calls `auto-fill-function' if the current column number is greater
421 than the value of `fill-column' and ARG is nil.
422 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
423 (interactive "*P\np")
424 (barf-if-buffer-read-only)
425 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
426 ;; Set last-command-event to tell self-insert what to insert.
427 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
428 (beforepos (point))
429 (last-command-event ?\n)
430 ;; Don't auto-fill if we have a numeric argument.
431 (auto-fill-function (if arg nil auto-fill-function))
432 (arg (prefix-numeric-value arg))
433 (postproc
434 ;; Do the rest in post-self-insert-hook, because we want to do it
435 ;; *before* other functions on that hook.
436 (lambda ()
437 ;; We are not going to insert any newlines if arg is
438 ;; non-positive.
439 (or (and (numberp arg) (<= arg 0))
440 (cl-assert (eq ?\n (char-before))))
441 ;; Mark the newline(s) `hard'.
442 (if use-hard-newlines
443 (set-hard-newline-properties
444 (- (point) arg) (point)))
445 ;; If the newline leaves the previous line blank, and we
446 ;; have a left margin, delete that from the blank line.
447 (save-excursion
448 (goto-char beforepos)
449 (beginning-of-line)
450 (and (looking-at "[ \t]$")
451 (> (current-left-margin) 0)
452 (delete-region (point)
453 (line-end-position))))
454 ;; Indent the line after the newline, except in one case:
455 ;; when we added the newline at the beginning of a line which
456 ;; starts a page.
457 (or was-page-start
458 (move-to-left-margin nil t)))))
459 (unwind-protect
460 (if (not interactive)
461 ;; FIXME: For non-interactive uses, many calls actually
462 ;; just want (insert "\n"), so maybe we should do just
463 ;; that, so as to avoid the risk of filling or running
464 ;; abbrevs unexpectedly.
465 (let ((post-self-insert-hook (list postproc)))
466 (self-insert-command arg))
467 (unwind-protect
468 (progn
469 (add-hook 'post-self-insert-hook postproc nil t)
470 (self-insert-command arg))
471 ;; We first used let-binding to protect the hook, but that
472 ;; was naive since add-hook affects the symbol-default
473 ;; value of the variable, whereas the let-binding might
474 ;; only protect the buffer-local value.
475 (remove-hook 'post-self-insert-hook postproc t)))
476 (cl-assert (not (member postproc post-self-insert-hook)))
477 (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
478 nil)
480 (defun set-hard-newline-properties (from to)
481 (let ((sticky (get-text-property from 'rear-nonsticky)))
482 (put-text-property from to 'hard 't)
483 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
484 (if (and (listp sticky) (not (memq 'hard sticky)))
485 (put-text-property from (point) 'rear-nonsticky
486 (cons 'hard sticky)))))
488 (defun open-line (n)
489 "Insert a newline and leave point before it.
490 If there is a fill prefix and/or a `left-margin', insert them on
491 the new line if the line would have been blank.
492 With arg N, insert N newlines."
493 (interactive "*p")
494 (let* ((do-fill-prefix (and fill-prefix (bolp)))
495 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
496 (loc (point-marker))
497 ;; Don't expand an abbrev before point.
498 (abbrev-mode nil))
499 (newline n)
500 (goto-char loc)
501 (while (> n 0)
502 (cond ((bolp)
503 (if do-left-margin (indent-to (current-left-margin)))
504 (if do-fill-prefix (insert-and-inherit fill-prefix))))
505 (forward-line 1)
506 (setq n (1- n)))
507 (goto-char loc)
508 ;; Necessary in case a margin or prefix was inserted.
509 (end-of-line)))
511 (defun split-line (&optional arg)
512 "Split current line, moving portion beyond point vertically down.
513 If the current line starts with `fill-prefix', insert it on the new
514 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
516 When called from Lisp code, ARG may be a prefix string to copy."
517 (interactive "*P")
518 (skip-chars-forward " \t")
519 (let* ((col (current-column))
520 (pos (point))
521 ;; What prefix should we check for (nil means don't).
522 (prefix (cond ((stringp arg) arg)
523 (arg nil)
524 (t fill-prefix)))
525 ;; Does this line start with it?
526 (have-prfx (and prefix
527 (save-excursion
528 (beginning-of-line)
529 (looking-at (regexp-quote prefix))))))
530 (newline 1)
531 (if have-prfx (insert-and-inherit prefix))
532 (indent-to col 0)
533 (goto-char pos)))
535 (defun delete-indentation (&optional arg)
536 "Join this line to previous and fix up whitespace at join.
537 If there is a fill prefix, delete it from the beginning of this line.
538 With argument, join this line to following line."
539 (interactive "*P")
540 (beginning-of-line)
541 (if arg (forward-line 1))
542 (if (eq (preceding-char) ?\n)
543 (progn
544 (delete-region (point) (1- (point)))
545 ;; If the second line started with the fill prefix,
546 ;; delete the prefix.
547 (if (and fill-prefix
548 (<= (+ (point) (length fill-prefix)) (point-max))
549 (string= fill-prefix
550 (buffer-substring (point)
551 (+ (point) (length fill-prefix)))))
552 (delete-region (point) (+ (point) (length fill-prefix))))
553 (fixup-whitespace))))
555 (defalias 'join-line #'delete-indentation) ; easier to find
557 (defun delete-blank-lines ()
558 "On blank line, delete all surrounding blank lines, leaving just one.
559 On isolated blank line, delete that one.
560 On nonblank line, delete any immediately following blank lines."
561 (interactive "*")
562 (let (thisblank singleblank)
563 (save-excursion
564 (beginning-of-line)
565 (setq thisblank (looking-at "[ \t]*$"))
566 ;; Set singleblank if there is just one blank line here.
567 (setq singleblank
568 (and thisblank
569 (not (looking-at "[ \t]*\n[ \t]*$"))
570 (or (bobp)
571 (progn (forward-line -1)
572 (not (looking-at "[ \t]*$")))))))
573 ;; Delete preceding blank lines, and this one too if it's the only one.
574 (if thisblank
575 (progn
576 (beginning-of-line)
577 (if singleblank (forward-line 1))
578 (delete-region (point)
579 (if (re-search-backward "[^ \t\n]" nil t)
580 (progn (forward-line 1) (point))
581 (point-min)))))
582 ;; Delete following blank lines, unless the current line is blank
583 ;; and there are no following blank lines.
584 (if (not (and thisblank singleblank))
585 (save-excursion
586 (end-of-line)
587 (forward-line 1)
588 (delete-region (point)
589 (if (re-search-forward "[^ \t\n]" nil t)
590 (progn (beginning-of-line) (point))
591 (point-max)))))
592 ;; Handle the special case where point is followed by newline and eob.
593 ;; Delete the line, leaving point at eob.
594 (if (looking-at "^[ \t]*\n\\'")
595 (delete-region (point) (point-max)))))
597 (defcustom delete-trailing-lines t
598 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
599 Trailing lines are deleted only if `delete-trailing-whitespace'
600 is called on the entire buffer (rather than an active region)."
601 :type 'boolean
602 :group 'editing
603 :version "24.3")
605 (defun region-modifiable-p (start end)
606 "Return non-nil if the region contains no read-only text."
607 (and (not (get-text-property start 'read-only))
608 (eq end (next-single-property-change start 'read-only nil end))))
610 (defun delete-trailing-whitespace (&optional start end)
611 "Delete trailing whitespace between START and END.
612 If called interactively, START and END are the start/end of the
613 region if the mark is active, or of the buffer's accessible
614 portion if the mark is inactive.
616 This command deletes whitespace characters after the last
617 non-whitespace character in each line between START and END. It
618 does not consider formfeed characters to be whitespace.
620 If this command acts on the entire buffer (i.e. if called
621 interactively with the mark inactive, or called from Lisp with
622 END nil), it also deletes all trailing lines at the end of the
623 buffer if the variable `delete-trailing-lines' is non-nil."
624 (interactive (progn
625 (barf-if-buffer-read-only)
626 (if (use-region-p)
627 (list (region-beginning) (region-end))
628 (list nil nil))))
629 (save-match-data
630 (save-excursion
631 (let ((end-marker (and end (copy-marker end))))
632 (goto-char (or start (point-min)))
633 (with-syntax-table (make-syntax-table (syntax-table))
634 ;; Don't delete formfeeds, even if they are considered whitespace.
635 (modify-syntax-entry ?\f "_")
636 ;; Treating \n as non-whitespace makes things easier.
637 (modify-syntax-entry ?\n "_")
638 (while (re-search-forward "\\s-+$" end-marker t)
639 (let ((b (match-beginning 0)) (e (match-end 0)))
640 (when (region-modifiable-p b e)
641 (delete-region b e)))))
642 (if end
643 (set-marker end-marker nil)
644 ;; Delete trailing empty lines.
645 (and delete-trailing-lines
646 ;; Really the end of buffer.
647 (= (goto-char (point-max)) (1+ (buffer-size)))
648 (<= (skip-chars-backward "\n") -2)
649 (region-modifiable-p (1+ (point)) (point-max))
650 (delete-region (1+ (point)) (point-max)))))))
651 ;; Return nil for the benefit of `write-file-functions'.
652 nil)
654 (defun newline-and-indent ()
655 "Insert a newline, then indent according to major mode.
656 Indentation is done using the value of `indent-line-function'.
657 In programming language modes, this is the same as TAB.
658 In some text modes, where TAB inserts a tab, this command indents to the
659 column specified by the function `current-left-margin'."
660 (interactive "*")
661 (delete-horizontal-space t)
662 (newline nil t)
663 (indent-according-to-mode))
665 (defun reindent-then-newline-and-indent ()
666 "Reindent current line, insert newline, then indent the new line.
667 Indentation of both lines is done according to the current major mode,
668 which means calling the current value of `indent-line-function'.
669 In programming language modes, this is the same as TAB.
670 In some text modes, where TAB inserts a tab, this indents to the
671 column specified by the function `current-left-margin'."
672 (interactive "*")
673 (let ((pos (point)))
674 ;; Be careful to insert the newline before indenting the line.
675 ;; Otherwise, the indentation might be wrong.
676 (newline)
677 (save-excursion
678 (goto-char pos)
679 ;; We are at EOL before the call to indent-according-to-mode, and
680 ;; after it we usually are as well, but not always. We tried to
681 ;; address it with `save-excursion' but that uses a normal marker
682 ;; whereas we need `move after insertion', so we do the save/restore
683 ;; by hand.
684 (setq pos (copy-marker pos t))
685 (indent-according-to-mode)
686 (goto-char pos)
687 ;; Remove the trailing white-space after indentation because
688 ;; indentation may introduce the whitespace.
689 (delete-horizontal-space t))
690 (indent-according-to-mode)))
692 (defcustom read-quoted-char-radix 8
693 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
694 Legitimate radix values are 8, 10 and 16."
695 :type '(choice (const 8) (const 10) (const 16))
696 :group 'editing-basics)
698 (defun read-quoted-char (&optional prompt)
699 "Like `read-char', but do not allow quitting.
700 Also, if the first character read is an octal digit,
701 we read any number of octal digits and return the
702 specified character code. Any nondigit terminates the sequence.
703 If the terminator is RET, it is discarded;
704 any other terminator is used itself as input.
706 The optional argument PROMPT specifies a string to use to prompt the user.
707 The variable `read-quoted-char-radix' controls which radix to use
708 for numeric input."
709 (let ((message-log-max nil)
710 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
711 help-event-list)))
712 done (first t) (code 0) char translated)
713 (while (not done)
714 (let ((inhibit-quit first)
715 ;; Don't let C-h or other help chars get the help
716 ;; message--only help function keys. See bug#16617.
717 (help-char nil)
718 (help-event-list help-events)
719 (help-form
720 "Type the special character you want to use,
721 or the octal character code.
722 RET terminates the character code and is discarded;
723 any other non-digit terminates the character code and is then used as input."))
724 (setq char (read-event (and prompt (format "%s-" prompt)) t))
725 (if inhibit-quit (setq quit-flag nil)))
726 ;; Translate TAB key into control-I ASCII character, and so on.
727 ;; Note: `read-char' does it using the `ascii-character' property.
728 ;; We tried using read-key instead, but that disables the keystroke
729 ;; echo produced by 'C-q', see bug#24635.
730 (let ((translation (lookup-key local-function-key-map (vector char))))
731 (setq translated (if (arrayp translation)
732 (aref translation 0)
733 char)))
734 (if (integerp translated)
735 (setq translated (char-resolve-modifiers translated)))
736 (cond ((null translated))
737 ((not (integerp translated))
738 (setq unread-command-events (list char)
739 done t))
740 ((/= (logand translated ?\M-\^@) 0)
741 ;; Turn a meta-character into a character with the 0200 bit set.
742 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
743 done t))
744 ((and (<= ?0 translated)
745 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
746 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
747 (and prompt (setq prompt (message "%s %c" prompt translated))))
748 ((and (<= ?a (downcase translated))
749 (< (downcase translated)
750 (+ ?a -10 (min 36 read-quoted-char-radix))))
751 (setq code (+ (* code read-quoted-char-radix)
752 (+ 10 (- (downcase translated) ?a))))
753 (and prompt (setq prompt (message "%s %c" prompt translated))))
754 ((and (not first) (eq translated ?\C-m))
755 (setq done t))
756 ((not first)
757 (setq unread-command-events (list char)
758 done t))
759 (t (setq code translated
760 done t)))
761 (setq first nil))
762 code))
764 (defun quoted-insert (arg)
765 "Read next input character and insert it.
766 This is useful for inserting control characters.
767 With argument, insert ARG copies of the character.
769 If the first character you type after this command is an octal digit,
770 you should type a sequence of octal digits which specify a character code.
771 Any nondigit terminates the sequence. If the terminator is a RET,
772 it is discarded; any other terminator is used itself as input.
773 The variable `read-quoted-char-radix' specifies the radix for this feature;
774 set it to 10 or 16 to use decimal or hex instead of octal.
776 In overwrite mode, this function inserts the character anyway, and
777 does not handle octal digits specially. This means that if you use
778 overwrite as your normal editing mode, you can use this function to
779 insert characters when necessary.
781 In binary overwrite mode, this function does overwrite, and octal
782 digits are interpreted as a character code. This is intended to be
783 useful for editing binary files."
784 (interactive "*p")
785 (let* ((char
786 ;; Avoid "obsolete" warnings for translation-table-for-input.
787 (with-no-warnings
788 (let (translation-table-for-input input-method-function)
789 (if (or (not overwrite-mode)
790 (eq overwrite-mode 'overwrite-mode-binary))
791 (read-quoted-char)
792 (read-char))))))
793 ;; This used to assume character codes 0240 - 0377 stand for
794 ;; characters in some single-byte character set, and converted them
795 ;; to Emacs characters. But in 23.1 this feature is deprecated
796 ;; in favor of inserting the corresponding Unicode characters.
797 ;; (if (and enable-multibyte-characters
798 ;; (>= char ?\240)
799 ;; (<= char ?\377))
800 ;; (setq char (unibyte-char-to-multibyte char)))
801 (unless (characterp char)
802 (user-error "%s is not a valid character"
803 (key-description (vector char))))
804 (if (> arg 0)
805 (if (eq overwrite-mode 'overwrite-mode-binary)
806 (delete-char arg)))
807 (while (> arg 0)
808 (insert-and-inherit char)
809 (setq arg (1- arg)))))
811 (defun forward-to-indentation (&optional arg)
812 "Move forward ARG lines and position at first nonblank character."
813 (interactive "^p")
814 (forward-line (or arg 1))
815 (skip-chars-forward " \t"))
817 (defun backward-to-indentation (&optional arg)
818 "Move backward ARG lines and position at first nonblank character."
819 (interactive "^p")
820 (forward-line (- (or arg 1)))
821 (skip-chars-forward " \t"))
823 (defun back-to-indentation ()
824 "Move point to the first non-whitespace character on this line."
825 (interactive "^")
826 (beginning-of-line 1)
827 (skip-syntax-forward " " (line-end-position))
828 ;; Move back over chars that have whitespace syntax but have the p flag.
829 (backward-prefix-chars))
831 (defun fixup-whitespace ()
832 "Fixup white space between objects around point.
833 Leave one space or none, according to the context."
834 (interactive "*")
835 (save-excursion
836 (delete-horizontal-space)
837 (if (or (looking-at "^\\|\\s)")
838 (save-excursion (forward-char -1)
839 (looking-at "$\\|\\s(\\|\\s'")))
841 (insert ?\s))))
843 (defun delete-horizontal-space (&optional backward-only)
844 "Delete all spaces and tabs around point.
845 If BACKWARD-ONLY is non-nil, only delete them before point."
846 (interactive "*P")
847 (let ((orig-pos (point)))
848 (delete-region
849 (if backward-only
850 orig-pos
851 (progn
852 (skip-chars-forward " \t")
853 (constrain-to-field nil orig-pos t)))
854 (progn
855 (skip-chars-backward " \t")
856 (constrain-to-field nil orig-pos)))))
858 (defun just-one-space (&optional n)
859 "Delete all spaces and tabs around point, leaving one space (or N spaces).
860 If N is negative, delete newlines as well, leaving -N spaces.
861 See also `cycle-spacing'."
862 (interactive "*p")
863 (cycle-spacing n nil 'single-shot))
865 (defvar cycle-spacing--context nil
866 "Store context used in consecutive calls to `cycle-spacing' command.
867 The first time `cycle-spacing' runs, it saves in this variable:
868 its N argument, the original point position, and the original spacing
869 around point.")
871 (defun cycle-spacing (&optional n preserve-nl-back mode)
872 "Manipulate whitespace around point in a smart way.
873 In interactive use, this function behaves differently in successive
874 consecutive calls.
876 The first call in a sequence acts like `just-one-space'.
877 It deletes all spaces and tabs around point, leaving one space
878 \(or N spaces). N is the prefix argument. If N is negative,
879 it deletes newlines as well, leaving -N spaces.
880 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
882 The second call in a sequence deletes all spaces.
884 The third call in a sequence restores the original whitespace (and point).
886 If MODE is `single-shot', it only performs the first step in the sequence.
887 If MODE is `fast' and the first step would not result in any change
888 \(i.e., there are exactly (abs N) spaces around point),
889 the function goes straight to the second step.
891 Repeatedly calling the function with different values of N starts a
892 new sequence each time."
893 (interactive "*p")
894 (let ((orig-pos (point))
895 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
896 (num (abs (or n 1))))
897 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
898 (constrain-to-field nil orig-pos)
899 (cond
900 ;; Command run for the first time, single-shot mode or different argument
901 ((or (eq 'single-shot mode)
902 (not (equal last-command this-command))
903 (not cycle-spacing--context)
904 (not (eq (car cycle-spacing--context) n)))
905 (let* ((start (point))
906 (num (- num (skip-chars-forward " " (+ num (point)))))
907 (mid (point))
908 (end (progn
909 (skip-chars-forward skip-characters)
910 (constrain-to-field nil orig-pos t))))
911 (setq cycle-spacing--context ;; Save for later.
912 ;; Special handling for case where there was no space at all.
913 (unless (= start end)
914 (cons n (cons orig-pos (buffer-substring start (point))))))
915 ;; If this run causes no change in buffer content, delete all spaces,
916 ;; otherwise delete all excess spaces.
917 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
918 start mid) end)
919 (insert (make-string num ?\s))))
921 ;; Command run for the second time.
922 ((not (equal orig-pos (point)))
923 (delete-region (point) orig-pos))
925 ;; Command run for the third time.
927 (insert (cddr cycle-spacing--context))
928 (goto-char (cadr cycle-spacing--context))
929 (setq cycle-spacing--context nil)))))
931 (defun beginning-of-buffer (&optional arg)
932 "Move point to the beginning of the buffer.
933 With numeric arg N, put point N/10 of the way from the beginning.
934 If the buffer is narrowed, this command uses the beginning of the
935 accessible part of the buffer.
937 Push mark at previous position, unless either a \\[universal-argument] prefix
938 is supplied, or Transient Mark mode is enabled and the mark is active."
939 (declare (interactive-only "use `(goto-char (point-min))' instead."))
940 (interactive "^P")
941 (or (consp arg)
942 (region-active-p)
943 (push-mark))
944 (let ((size (- (point-max) (point-min))))
945 (goto-char (if (and arg (not (consp arg)))
946 (+ (point-min)
947 (if (> size 10000)
948 ;; Avoid overflow for large buffer sizes!
949 (* (prefix-numeric-value arg)
950 (/ size 10))
951 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
952 (point-min))))
953 (if (and arg (not (consp arg))) (forward-line 1)))
955 (defun end-of-buffer (&optional arg)
956 "Move point to the end of the buffer.
957 With numeric arg N, put point N/10 of the way from the end.
958 If the buffer is narrowed, this command uses the end of the
959 accessible part of the buffer.
961 Push mark at previous position, unless either a \\[universal-argument] prefix
962 is supplied, or Transient Mark mode is enabled and the mark is active."
963 (declare (interactive-only "use `(goto-char (point-max))' instead."))
964 (interactive "^P")
965 (or (consp arg) (region-active-p) (push-mark))
966 (let ((size (- (point-max) (point-min))))
967 (goto-char (if (and arg (not (consp arg)))
968 (- (point-max)
969 (if (> size 10000)
970 ;; Avoid overflow for large buffer sizes!
971 (* (prefix-numeric-value arg)
972 (/ size 10))
973 (/ (* size (prefix-numeric-value arg)) 10)))
974 (point-max))))
975 ;; If we went to a place in the middle of the buffer,
976 ;; adjust it to the beginning of a line.
977 (cond ((and arg (not (consp arg))) (forward-line 1))
978 ((and (eq (current-buffer) (window-buffer))
979 (> (point) (window-end nil t)))
980 ;; If the end of the buffer is not already on the screen,
981 ;; then scroll specially to put it near, but not at, the bottom.
982 (overlay-recenter (point))
983 (recenter -3))))
985 (defcustom delete-active-region t
986 "Whether single-char deletion commands delete an active region.
987 This has an effect only if Transient Mark mode is enabled, and
988 affects `delete-forward-char' and `delete-backward-char', though
989 not `delete-char'.
991 If the value is the symbol `kill', the active region is killed
992 instead of deleted."
993 :type '(choice (const :tag "Delete active region" t)
994 (const :tag "Kill active region" kill)
995 (const :tag "Do ordinary deletion" nil))
996 :group 'killing
997 :version "24.1")
999 (defvar region-extract-function
1000 (lambda (delete)
1001 (when (region-beginning)
1002 (cond
1003 ((eq delete 'bounds)
1004 (list (cons (region-beginning) (region-end))))
1005 ((eq delete 'delete-only)
1006 (delete-region (region-beginning) (region-end)))
1008 (filter-buffer-substring (region-beginning) (region-end) delete)))))
1009 "Function to get the region's content.
1010 Called with one argument DELETE.
1011 If DELETE is `delete-only', then only delete the region and the return value
1012 is undefined. If DELETE is nil, just return the content as a string.
1013 If DELETE is `bounds', then don't delete, but just return the
1014 boundaries of the region as a list of (START . END) positions.
1015 If anything else, delete the region and return its content as a string,
1016 after filtering it with `filter-buffer-substring'.")
1018 (defvar region-insert-function
1019 (lambda (lines)
1020 (let ((first t))
1021 (while lines
1022 (or first
1023 (insert ?\n))
1024 (insert-for-yank (car lines))
1025 (setq lines (cdr lines)
1026 first nil))))
1027 "Function to insert the region's content.
1028 Called with one argument LINES.
1029 Insert the region as a list of lines.")
1031 (defun delete-backward-char (n &optional killflag)
1032 "Delete the previous N characters (following if N is negative).
1033 If Transient Mark mode is enabled, the mark is active, and N is 1,
1034 delete the text in the region and deactivate the mark instead.
1035 To disable this, set option `delete-active-region' to nil.
1037 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1038 kill ring) instead of delete. Interactively, N is the prefix
1039 arg, and KILLFLAG is set if N is explicitly specified.
1041 When killing, the killed text is filtered by
1042 `filter-buffer-substring' before it is saved in the kill ring, so
1043 the actual saved text might be different from what was killed.
1045 In Overwrite mode, single character backward deletion may replace
1046 tabs with spaces so as to back over columns, unless point is at
1047 the end of the line."
1048 (declare (interactive-only delete-char))
1049 (interactive "p\nP")
1050 (unless (integerp n)
1051 (signal 'wrong-type-argument (list 'integerp n)))
1052 (cond ((and (use-region-p)
1053 delete-active-region
1054 (= n 1))
1055 ;; If a region is active, kill or delete it.
1056 (if (eq delete-active-region 'kill)
1057 (kill-region (region-beginning) (region-end) 'region)
1058 (funcall region-extract-function 'delete-only)))
1059 ;; In Overwrite mode, maybe untabify while deleting
1060 ((null (or (null overwrite-mode)
1061 (<= n 0)
1062 (memq (char-before) '(?\t ?\n))
1063 (eobp)
1064 (eq (char-after) ?\n)))
1065 (let ((ocol (current-column)))
1066 (delete-char (- n) killflag)
1067 (save-excursion
1068 (insert-char ?\s (- ocol (current-column)) nil))))
1069 ;; Otherwise, do simple deletion.
1070 (t (delete-char (- n) killflag))))
1072 (defun delete-forward-char (n &optional killflag)
1073 "Delete the following N characters (previous if N is negative).
1074 If Transient Mark mode is enabled, the mark is active, and N is 1,
1075 delete the text in the region and deactivate the mark instead.
1076 To disable this, set variable `delete-active-region' to nil.
1078 Optional second arg KILLFLAG non-nil means to kill (save in kill
1079 ring) instead of delete. Interactively, N is the prefix arg, and
1080 KILLFLAG is set if N was explicitly specified.
1082 When killing, the killed text is filtered by
1083 `filter-buffer-substring' before it is saved in the kill ring, so
1084 the actual saved text might be different from what was killed."
1085 (declare (interactive-only delete-char))
1086 (interactive "p\nP")
1087 (unless (integerp n)
1088 (signal 'wrong-type-argument (list 'integerp n)))
1089 (cond ((and (use-region-p)
1090 delete-active-region
1091 (= n 1))
1092 ;; If a region is active, kill or delete it.
1093 (if (eq delete-active-region 'kill)
1094 (kill-region (region-beginning) (region-end) 'region)
1095 (funcall region-extract-function 'delete-only)))
1097 ;; Otherwise, do simple deletion.
1098 (t (delete-char n killflag))))
1100 (defun mark-whole-buffer ()
1101 "Put point at beginning and mark at end of buffer.
1102 If narrowing is in effect, only uses the accessible part of the buffer.
1103 You probably should not use this function in Lisp programs;
1104 it is usually a mistake for a Lisp function to use any subroutine
1105 that uses or sets the mark."
1106 (declare (interactive-only t))
1107 (interactive)
1108 (push-mark (point))
1109 (push-mark (point-max) nil t)
1110 ;; This is really `point-min' in most cases, but if we're in the
1111 ;; minibuffer, this is at the end of the prompt.
1112 (goto-char (minibuffer-prompt-end)))
1115 ;; Counting lines, one way or another.
1117 (defun goto-line (line &optional buffer)
1118 "Go to LINE, counting from line 1 at beginning of buffer.
1119 If called interactively, a numeric prefix argument specifies
1120 LINE; without a numeric prefix argument, read LINE from the
1121 minibuffer.
1123 If optional argument BUFFER is non-nil, switch to that buffer and
1124 move to line LINE there. If called interactively with \\[universal-argument]
1125 as argument, BUFFER is the most recently selected other buffer.
1127 Prior to moving point, this function sets the mark (without
1128 activating it), unless Transient Mark mode is enabled and the
1129 mark is already active.
1131 This function is usually the wrong thing to use in a Lisp program.
1132 What you probably want instead is something like:
1133 (goto-char (point-min))
1134 (forward-line (1- N))
1135 If at all possible, an even better solution is to use char counts
1136 rather than line counts."
1137 (declare (interactive-only forward-line))
1138 (interactive
1139 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1140 (list (prefix-numeric-value current-prefix-arg))
1141 ;; Look for a default, a number in the buffer at point.
1142 (let* ((default
1143 (save-excursion
1144 (skip-chars-backward "0-9")
1145 (if (looking-at "[0-9]")
1146 (string-to-number
1147 (buffer-substring-no-properties
1148 (point)
1149 (progn (skip-chars-forward "0-9")
1150 (point)))))))
1151 ;; Decide if we're switching buffers.
1152 (buffer
1153 (if (consp current-prefix-arg)
1154 (other-buffer (current-buffer) t)))
1155 (buffer-prompt
1156 (if buffer
1157 (concat " in " (buffer-name buffer))
1158 "")))
1159 ;; Read the argument, offering that number (if any) as default.
1160 (list (read-number (format "Goto line%s: " buffer-prompt)
1161 (list default (line-number-at-pos)))
1162 buffer))))
1163 ;; Switch to the desired buffer, one way or another.
1164 (if buffer
1165 (let ((window (get-buffer-window buffer)))
1166 (if window (select-window window)
1167 (switch-to-buffer-other-window buffer))))
1168 ;; Leave mark at previous position
1169 (or (region-active-p) (push-mark))
1170 ;; Move to the specified line number in that buffer.
1171 (save-restriction
1172 (widen)
1173 (goto-char (point-min))
1174 (if (eq selective-display t)
1175 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1176 (forward-line (1- line)))))
1178 (defun count-words-region (start end &optional arg)
1179 "Count the number of words in the region.
1180 If called interactively, print a message reporting the number of
1181 lines, words, and characters in the region (whether or not the
1182 region is active); with prefix ARG, report for the entire buffer
1183 rather than the region.
1185 If called from Lisp, return the number of words between positions
1186 START and END."
1187 (interactive (if current-prefix-arg
1188 (list nil nil current-prefix-arg)
1189 (list (region-beginning) (region-end) nil)))
1190 (cond ((not (called-interactively-p 'any))
1191 (count-words start end))
1192 (arg
1193 (count-words--buffer-message))
1195 (count-words--message "Region" start end))))
1197 (defun count-words (start end)
1198 "Count words between START and END.
1199 If called interactively, START and END are normally the start and
1200 end of the buffer; but if the region is active, START and END are
1201 the start and end of the region. Print a message reporting the
1202 number of lines, words, and chars.
1204 If called from Lisp, return the number of words between START and
1205 END, without printing any message."
1206 (interactive (list nil nil))
1207 (cond ((not (called-interactively-p 'any))
1208 (let ((words 0))
1209 (save-excursion
1210 (save-restriction
1211 (narrow-to-region start end)
1212 (goto-char (point-min))
1213 (while (forward-word-strictly 1)
1214 (setq words (1+ words)))))
1215 words))
1216 ((use-region-p)
1217 (call-interactively 'count-words-region))
1219 (count-words--buffer-message))))
1221 (defun count-words--buffer-message ()
1222 (count-words--message
1223 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1224 (point-min) (point-max)))
1226 (defun count-words--message (str start end)
1227 (let ((lines (count-lines start end))
1228 (words (count-words start end))
1229 (chars (- end start)))
1230 (message "%s has %d line%s, %d word%s, and %d character%s."
1232 lines (if (= lines 1) "" "s")
1233 words (if (= words 1) "" "s")
1234 chars (if (= chars 1) "" "s"))))
1236 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1238 (defun what-line ()
1239 "Print the current buffer line number and narrowed line number of point."
1240 (interactive)
1241 (let ((start (point-min))
1242 (n (line-number-at-pos)))
1243 (if (= start 1)
1244 (message "Line %d" n)
1245 (save-excursion
1246 (save-restriction
1247 (widen)
1248 (message "line %d (narrowed line %d)"
1249 (+ n (line-number-at-pos start) -1) n))))))
1251 (defun count-lines (start end)
1252 "Return number of lines between START and END.
1253 This is usually the number of newlines between them,
1254 but can be one more if START is not equal to END
1255 and the greater of them is not at the start of a line."
1256 (save-excursion
1257 (save-restriction
1258 (narrow-to-region start end)
1259 (goto-char (point-min))
1260 (if (eq selective-display t)
1261 (save-match-data
1262 (let ((done 0))
1263 (while (re-search-forward "[\n\C-m]" nil t 40)
1264 (setq done (+ 40 done)))
1265 (while (re-search-forward "[\n\C-m]" nil t 1)
1266 (setq done (+ 1 done)))
1267 (goto-char (point-max))
1268 (if (and (/= start end)
1269 (not (bolp)))
1270 (1+ done)
1271 done)))
1272 (- (buffer-size) (forward-line (buffer-size)))))))
1274 (defun line-number-at-pos (&optional pos)
1275 "Return (narrowed) buffer line number at position POS.
1276 If POS is nil, use current buffer location.
1277 Counting starts at (point-min), so the value refers
1278 to the contents of the accessible portion of the buffer."
1279 (let ((opoint (or pos (point))) start)
1280 (save-excursion
1281 (goto-char (point-min))
1282 (setq start (point))
1283 (goto-char opoint)
1284 (forward-line 0)
1285 (1+ (count-lines start (point))))))
1287 (defun what-cursor-position (&optional detail)
1288 "Print info on cursor position (on screen and within buffer).
1289 Also describe the character after point, and give its character code
1290 in octal, decimal and hex.
1292 For a non-ASCII multibyte character, also give its encoding in the
1293 buffer's selected coding system if the coding system encodes the
1294 character safely. If the character is encoded into one byte, that
1295 code is shown in hex. If the character is encoded into more than one
1296 byte, just \"...\" is shown.
1298 In addition, with prefix argument, show details about that character
1299 in *Help* buffer. See also the command `describe-char'."
1300 (interactive "P")
1301 (let* ((char (following-char))
1302 (bidi-fixer
1303 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1304 ;; start a directional embedding, which could completely
1305 ;; disrupt the rest of the line (e.g., RLO will display the
1306 ;; rest of the line right-to-left). So we put an invisible
1307 ;; PDF character after these characters, to end the
1308 ;; embedding, which eliminates any effects on the rest of
1309 ;; the line. For RLE and RLO we also append an invisible
1310 ;; LRM, to avoid reordering the following numerical
1311 ;; characters. For LRI/RLI/FSI we append a PDI.
1312 (cond ((memq char '(?\x202a ?\x202d))
1313 (propertize (string ?\x202c) 'invisible t))
1314 ((memq char '(?\x202b ?\x202e))
1315 (propertize (string ?\x202c ?\x200e) 'invisible t))
1316 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1317 (propertize (string ?\x2069) 'invisible t))
1318 ;; Strong right-to-left characters cause reordering of
1319 ;; the following numerical characters which show the
1320 ;; codepoint, so append LRM to countermand that.
1321 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1322 (propertize (string ?\x200e) 'invisible t))
1324 "")))
1325 (beg (point-min))
1326 (end (point-max))
1327 (pos (point))
1328 (total (buffer-size))
1329 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1330 (hscroll (if (= (window-hscroll) 0)
1332 (format " Hscroll=%d" (window-hscroll))))
1333 (col (current-column)))
1334 (if (= pos end)
1335 (if (or (/= beg 1) (/= end (1+ total)))
1336 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1337 pos total percent beg end col hscroll)
1338 (message "point=%d of %d (EOB) column=%d%s"
1339 pos total col hscroll))
1340 (let ((coding buffer-file-coding-system)
1341 encoded encoding-msg display-prop under-display)
1342 (if (or (not coding)
1343 (eq (coding-system-type coding) t))
1344 (setq coding (default-value 'buffer-file-coding-system)))
1345 (if (eq (char-charset char) 'eight-bit)
1346 (setq encoding-msg
1347 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1348 ;; Check if the character is displayed with some `display'
1349 ;; text property. In that case, set under-display to the
1350 ;; buffer substring covered by that property.
1351 (setq display-prop (get-char-property pos 'display))
1352 (if display-prop
1353 (let ((to (or (next-single-char-property-change pos 'display)
1354 (point-max))))
1355 (if (< to (+ pos 4))
1356 (setq under-display "")
1357 (setq under-display "..."
1358 to (+ pos 4)))
1359 (setq under-display
1360 (concat (buffer-substring-no-properties pos to)
1361 under-display)))
1362 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1363 (setq encoding-msg
1364 (if display-prop
1365 (if (not (stringp display-prop))
1366 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1367 char char char under-display)
1368 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1369 char char char under-display display-prop))
1370 (if encoded
1371 (format "(%d, #o%o, #x%x, file %s)"
1372 char char char
1373 (if (> (length encoded) 1)
1374 "..."
1375 (encoded-string-description encoded coding)))
1376 (format "(%d, #o%o, #x%x)" char char char)))))
1377 (if detail
1378 ;; We show the detailed information about CHAR.
1379 (describe-char (point)))
1380 (if (or (/= beg 1) (/= end (1+ total)))
1381 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1382 (if (< char 256)
1383 (single-key-description char)
1384 (buffer-substring-no-properties (point) (1+ (point))))
1385 bidi-fixer
1386 encoding-msg pos total percent beg end col hscroll)
1387 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1388 (if enable-multibyte-characters
1389 (if (< char 128)
1390 (single-key-description char)
1391 (buffer-substring-no-properties (point) (1+ (point))))
1392 (single-key-description char))
1393 bidi-fixer encoding-msg pos total percent col hscroll))))))
1395 ;; Initialize read-expression-map. It is defined at C level.
1396 (defvar read-expression-map
1397 (let ((m (make-sparse-keymap)))
1398 (define-key m "\M-\t" 'completion-at-point)
1399 ;; Might as well bind TAB to completion, since inserting a TAB char is
1400 ;; much too rarely useful.
1401 (define-key m "\t" 'completion-at-point)
1402 (set-keymap-parent m minibuffer-local-map)
1405 (defun read-minibuffer (prompt &optional initial-contents)
1406 "Return a Lisp object read using the minibuffer, unevaluated.
1407 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1408 is a string to insert in the minibuffer before reading.
1409 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1410 Such arguments are used as in `read-from-minibuffer'.)"
1411 ;; Used for interactive spec `x'.
1412 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1413 t 'minibuffer-history))
1415 (defun eval-minibuffer (prompt &optional initial-contents)
1416 "Return value of Lisp expression read using the minibuffer.
1417 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1418 is a string to insert in the minibuffer before reading.
1419 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1420 Such arguments are used as in `read-from-minibuffer'.)"
1421 ;; Used for interactive spec `X'.
1422 (eval (read--expression prompt initial-contents)))
1424 (defvar minibuffer-completing-symbol nil
1425 "Non-nil means completing a Lisp symbol in the minibuffer.")
1426 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1428 (defvar minibuffer-default nil
1429 "The current default value or list of default values in the minibuffer.
1430 The functions `read-from-minibuffer' and `completing-read' bind
1431 this variable locally.")
1433 (defcustom eval-expression-print-level 4
1434 "Value for `print-level' while printing value in `eval-expression'.
1435 A value of nil means no limit."
1436 :group 'lisp
1437 :type '(choice (const :tag "No Limit" nil) integer)
1438 :version "21.1")
1440 (defcustom eval-expression-print-length 12
1441 "Value for `print-length' while printing value in `eval-expression'.
1442 A value of nil means no limit."
1443 :group 'lisp
1444 :type '(choice (const :tag "No Limit" nil) integer)
1445 :version "21.1")
1447 (defcustom eval-expression-debug-on-error t
1448 "If non-nil set `debug-on-error' to t in `eval-expression'.
1449 If nil, don't change the value of `debug-on-error'."
1450 :group 'lisp
1451 :type 'boolean
1452 :version "21.1")
1454 (defun eval-expression-print-format (value)
1455 "If VALUE in an integer, return a specially formatted string.
1456 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1457 If VALUE is not an integer, nil is returned.
1458 This function is used by functions like `prin1' that display the
1459 result of expression evaluation."
1460 (if (and (integerp value)
1461 (or (eq standard-output t)
1462 (zerop (prefix-numeric-value current-prefix-arg))))
1463 (let ((char-string
1464 (if (and (characterp value)
1465 (char-displayable-p value))
1466 (prin1-char value))))
1467 (if char-string
1468 (format " (#o%o, #x%x, %s)" value value char-string)
1469 (format " (#o%o, #x%x)" value value)))))
1471 (defvar eval-expression-minibuffer-setup-hook nil
1472 "Hook run by `eval-expression' when entering the minibuffer.")
1474 (defun read--expression (prompt &optional initial-contents)
1475 (let ((minibuffer-completing-symbol t))
1476 (minibuffer-with-setup-hook
1477 (lambda ()
1478 ;; FIXME: call emacs-lisp-mode?
1479 (add-function :before-until (local 'eldoc-documentation-function)
1480 #'elisp-eldoc-documentation-function)
1481 (add-hook 'completion-at-point-functions
1482 #'elisp-completion-at-point nil t)
1483 (run-hooks 'eval-expression-minibuffer-setup-hook))
1484 (read-from-minibuffer prompt initial-contents
1485 read-expression-map t
1486 'read-expression-history))))
1488 ;; We define this, rather than making `eval' interactive,
1489 ;; for the sake of completion of names like eval-region, eval-buffer.
1490 (defun eval-expression (exp &optional insert-value)
1491 "Evaluate EXP and print value in the echo area.
1492 When called interactively, read an Emacs Lisp expression and evaluate it.
1493 Value is also consed on to front of the variable `values'.
1494 If the resulting value is an integer, it will be printed in
1495 several additional formats (octal, hexadecimal, and character).
1496 Optional argument INSERT-VALUE non-nil (interactively, with
1497 prefix argument) means insert the result into the current buffer
1498 instead of printing it in the echo area.
1500 Normally, this function truncates long output according to the value
1501 of the variables `eval-expression-print-length' and
1502 `eval-expression-print-level'. With a prefix argument of zero,
1503 however, there is no such truncation.
1505 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1506 minibuffer.
1508 If `eval-expression-debug-on-error' is non-nil, which is the default,
1509 this command arranges for all errors to enter the debugger."
1510 (interactive
1511 (list (read--expression "Eval: ")
1512 current-prefix-arg))
1514 (if (null eval-expression-debug-on-error)
1515 (push (eval exp lexical-binding) values)
1516 (let ((old-value (make-symbol "t")) new-value)
1517 ;; Bind debug-on-error to something unique so that we can
1518 ;; detect when evalled code changes it.
1519 (let ((debug-on-error old-value))
1520 (push (eval (macroexpand-all exp) lexical-binding) values)
1521 (setq new-value debug-on-error))
1522 ;; If evalled code has changed the value of debug-on-error,
1523 ;; propagate that change to the global binding.
1524 (unless (eq old-value new-value)
1525 (setq debug-on-error new-value))))
1527 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
1528 eval-expression-print-length))
1529 (print-level (and (not (zerop (prefix-numeric-value insert-value)))
1530 eval-expression-print-level))
1531 (deactivate-mark))
1532 (if insert-value
1533 (with-no-warnings
1534 (let ((standard-output (current-buffer)))
1535 (prog1
1536 (prin1 (car values))
1537 (when (zerop (prefix-numeric-value insert-value))
1538 (let ((str (eval-expression-print-format (car values))))
1539 (if str (princ str)))))))
1540 (prog1
1541 (prin1 (car values) t)
1542 (let ((str (eval-expression-print-format (car values))))
1543 (if str (princ str t)))))))
1545 (defun edit-and-eval-command (prompt command)
1546 "Prompting with PROMPT, let user edit COMMAND and eval result.
1547 COMMAND is a Lisp expression. Let user edit that expression in
1548 the minibuffer, then read and evaluate the result."
1549 (let ((command
1550 (let ((print-level nil)
1551 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1552 (unwind-protect
1553 (read-from-minibuffer prompt
1554 (prin1-to-string command)
1555 read-expression-map t
1556 'command-history)
1557 ;; If command was added to command-history as a string,
1558 ;; get rid of that. We want only evaluable expressions there.
1559 (if (stringp (car command-history))
1560 (setq command-history (cdr command-history)))))))
1562 ;; If command to be redone does not match front of history,
1563 ;; add it to the history.
1564 (or (equal command (car command-history))
1565 (setq command-history (cons command command-history)))
1566 (eval command)))
1568 (defun repeat-complex-command (arg)
1569 "Edit and re-evaluate last complex command, or ARGth from last.
1570 A complex command is one which used the minibuffer.
1571 The command is placed in the minibuffer as a Lisp form for editing.
1572 The result is executed, repeating the command as changed.
1573 If the command has been changed or is not the most recent previous
1574 command it is added to the front of the command history.
1575 You can use the minibuffer history commands \
1576 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1577 to get different commands to edit and resubmit."
1578 (interactive "p")
1579 (let ((elt (nth (1- arg) command-history))
1580 newcmd)
1581 (if elt
1582 (progn
1583 (setq newcmd
1584 (let ((print-level nil)
1585 (minibuffer-history-position arg)
1586 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1587 (unwind-protect
1588 (read-from-minibuffer
1589 "Redo: " (prin1-to-string elt) read-expression-map t
1590 (cons 'command-history arg))
1592 ;; If command was added to command-history as a
1593 ;; string, get rid of that. We want only
1594 ;; evaluable expressions there.
1595 (if (stringp (car command-history))
1596 (setq command-history (cdr command-history))))))
1598 ;; If command to be redone does not match front of history,
1599 ;; add it to the history.
1600 (or (equal newcmd (car command-history))
1601 (setq command-history (cons newcmd command-history)))
1602 (apply #'funcall-interactively
1603 (car newcmd)
1604 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1605 (if command-history
1606 (error "Argument %d is beyond length of command history" arg)
1607 (error "There are no previous complex commands to repeat")))))
1610 (defvar extended-command-history nil)
1611 (defvar execute-extended-command--last-typed nil)
1613 (defun read-extended-command ()
1614 "Read command name to invoke in `execute-extended-command'."
1615 (minibuffer-with-setup-hook
1616 (lambda ()
1617 (add-hook 'post-self-insert-hook
1618 (lambda ()
1619 (setq execute-extended-command--last-typed
1620 (minibuffer-contents)))
1621 nil 'local)
1622 (set (make-local-variable 'minibuffer-default-add-function)
1623 (lambda ()
1624 ;; Get a command name at point in the original buffer
1625 ;; to propose it after M-n.
1626 (with-current-buffer (window-buffer (minibuffer-selected-window))
1627 (and (commandp (function-called-at-point))
1628 (format "%S" (function-called-at-point)))))))
1629 ;; Read a string, completing from and restricting to the set of
1630 ;; all defined commands. Don't provide any initial input.
1631 ;; Save the command read on the extended-command history list.
1632 (completing-read
1633 (concat (cond
1634 ((eq current-prefix-arg '-) "- ")
1635 ((and (consp current-prefix-arg)
1636 (eq (car current-prefix-arg) 4)) "C-u ")
1637 ((and (consp current-prefix-arg)
1638 (integerp (car current-prefix-arg)))
1639 (format "%d " (car current-prefix-arg)))
1640 ((integerp current-prefix-arg)
1641 (format "%d " current-prefix-arg)))
1642 ;; This isn't strictly correct if `execute-extended-command'
1643 ;; is bound to anything else (e.g. [menu]).
1644 ;; It could use (key-description (this-single-command-keys)),
1645 ;; but actually a prompt other than "M-x" would be confusing,
1646 ;; because "M-x" is a well-known prompt to read a command
1647 ;; and it serves as a shorthand for "Extended command: ".
1648 "M-x ")
1649 (lambda (string pred action)
1650 (let ((pred
1651 (if (memq action '(nil t))
1652 ;; Exclude obsolete commands from completions.
1653 (lambda (sym)
1654 (and (funcall pred sym)
1655 (or (equal string (symbol-name sym))
1656 (not (get sym 'byte-obsolete-info)))))
1657 pred)))
1658 (complete-with-action action obarray string pred)))
1659 #'commandp t nil 'extended-command-history)))
1661 (defcustom suggest-key-bindings t
1662 "Non-nil means show the equivalent key-binding when M-x command has one.
1663 The value can be a length of time to show the message for.
1664 If the value is non-nil and not a number, we wait 2 seconds."
1665 :group 'keyboard
1666 :type '(choice (const :tag "off" nil)
1667 (integer :tag "time" 2)
1668 (other :tag "on")))
1670 (defcustom extended-command-suggest-shorter t
1671 "If non-nil, show a shorter M-x invocation when there is one."
1672 :group 'keyboard
1673 :type 'boolean
1674 :version "26.1")
1676 (defun execute-extended-command--shorter-1 (name length)
1677 (cond
1678 ((zerop length) (list ""))
1679 ((equal name "") nil)
1681 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1682 (execute-extended-command--shorter-1
1683 (substring name 1) (1- length)))
1684 (when (string-match "\\`\\(-\\)?[^-]*" name)
1685 (execute-extended-command--shorter-1
1686 (substring name (match-end 0)) length))))))
1688 (defun execute-extended-command--shorter (name typed)
1689 (let ((candidates '())
1690 (max (length typed))
1691 (len 1)
1692 binding)
1693 (while (and (not binding)
1694 (progn
1695 (unless candidates
1696 (setq len (1+ len))
1697 (setq candidates (execute-extended-command--shorter-1
1698 name len)))
1699 ;; Don't show the help message if the binding isn't
1700 ;; significantly shorter than the M-x command the user typed.
1701 (< len (- max 5))))
1702 (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
1703 (let ((candidate (pop candidates)))
1704 (when (equal name
1705 (car-safe (completion-try-completion
1706 candidate obarray 'commandp len)))
1707 (setq binding candidate))))
1708 binding))
1710 (defun execute-extended-command (prefixarg &optional command-name typed)
1711 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1712 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1713 "Read a command name, then read the arguments and call the command.
1714 To pass a prefix argument to the command you are
1715 invoking, give a prefix argument to `execute-extended-command'."
1716 (declare (interactive-only command-execute))
1717 ;; FIXME: Remember the actual text typed by the user before completion,
1718 ;; so that we don't later on suggest the same shortening.
1719 (interactive
1720 (let ((execute-extended-command--last-typed nil))
1721 (list current-prefix-arg
1722 (read-extended-command)
1723 execute-extended-command--last-typed)))
1724 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1725 (unless command-name
1726 (let ((current-prefix-arg prefixarg) ; for prompt
1727 (execute-extended-command--last-typed nil))
1728 (setq command-name (read-extended-command))
1729 (setq typed execute-extended-command--last-typed)))
1730 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1731 (binding (and suggest-key-bindings
1732 (not executing-kbd-macro)
1733 (where-is-internal function overriding-local-map t))))
1734 (unless (commandp function)
1735 (error "`%s' is not a valid command name" command-name))
1736 ;; Some features, such as novice.el, rely on this-command-keys
1737 ;; including M-x COMMAND-NAME RET.
1738 (set--this-command-keys (concat "\M-x" (symbol-name function) "\r"))
1739 (setq this-command function)
1740 ;; Normally `real-this-command' should never be changed, but here we really
1741 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1742 ;; binding" for <cmd>, so the command the user really wanted to run is
1743 ;; `function' and not `execute-extended-command'. The difference is
1744 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1745 (setq real-this-command function)
1746 (let ((prefix-arg prefixarg))
1747 (command-execute function 'record))
1748 ;; If enabled, show which key runs this command.
1749 ;; But first wait, and skip the message if there is input.
1750 (let* ((waited
1751 ;; If this command displayed something in the echo area;
1752 ;; wait a few seconds, then display our suggestion message.
1753 ;; FIXME: Wait *after* running post-command-hook!
1754 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1755 ;; find a better answer anyway!
1756 (when suggest-key-bindings
1757 (sit-for (cond
1758 ((zerop (length (current-message))) 0)
1759 ((numberp suggest-key-bindings) suggest-key-bindings)
1760 (t 2))))))
1761 (when (and waited (not (consp unread-command-events)))
1762 (unless (or (not extended-command-suggest-shorter)
1763 binding executing-kbd-macro (not (symbolp function))
1764 (<= (length (symbol-name function)) 2))
1765 ;; There's no binding for CMD. Let's try and find the shortest
1766 ;; string to use in M-x.
1767 ;; FIXME: Can be slow. Cache it maybe?
1768 (while-no-input
1769 (setq binding (execute-extended-command--shorter
1770 (symbol-name function) typed))))
1771 (when binding
1772 (with-temp-message
1773 (format-message "You can run the command `%s' with %s"
1774 function
1775 (if (stringp binding)
1776 (concat "M-x " binding " RET")
1777 (key-description binding)))
1778 (sit-for (if (numberp suggest-key-bindings)
1779 suggest-key-bindings
1780 2))))))))
1782 (defun command-execute (cmd &optional record-flag keys special)
1783 ;; BEWARE: Called directly from the C code.
1784 "Execute CMD as an editor command.
1785 CMD must be a symbol that satisfies the `commandp' predicate.
1786 Optional second arg RECORD-FLAG non-nil
1787 means unconditionally put this command in the variable `command-history'.
1788 Otherwise, that is done only if an arg is read using the minibuffer.
1789 The argument KEYS specifies the value to use instead of (this-command-keys)
1790 when reading the arguments; if it is nil, (this-command-keys) is used.
1791 The argument SPECIAL, if non-nil, means that this command is executing
1792 a special event, so ignore the prefix argument and don't clear it."
1793 (setq debug-on-next-call nil)
1794 (let ((prefixarg (unless special
1795 ;; FIXME: This should probably be done around
1796 ;; pre-command-hook rather than here!
1797 (prog1 prefix-arg
1798 (setq current-prefix-arg prefix-arg)
1799 (setq prefix-arg nil)
1800 (when current-prefix-arg
1801 (prefix-command-update))))))
1802 (if (and (symbolp cmd)
1803 (get cmd 'disabled)
1804 disabled-command-function)
1805 ;; FIXME: Weird calling convention!
1806 (run-hooks 'disabled-command-function)
1807 (let ((final cmd))
1808 (while
1809 (progn
1810 (setq final (indirect-function final))
1811 (if (autoloadp final)
1812 (setq final (autoload-do-load final cmd)))))
1813 (cond
1814 ((arrayp final)
1815 ;; If requested, place the macro in the command history. For
1816 ;; other sorts of commands, call-interactively takes care of this.
1817 (when record-flag
1818 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1819 ;; Don't keep command history around forever.
1820 (when (and (numberp history-length) (> history-length 0))
1821 (let ((cell (nthcdr history-length command-history)))
1822 (if (consp cell) (setcdr cell nil)))))
1823 (execute-kbd-macro final prefixarg))
1825 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1826 (prog1 (call-interactively cmd record-flag keys)
1827 (when (and (symbolp cmd)
1828 (get cmd 'byte-obsolete-info)
1829 (not (get cmd 'command-execute-obsolete-warned)))
1830 (put cmd 'command-execute-obsolete-warned t)
1831 (message "%s" (macroexp--obsolete-warning
1832 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1834 (defvar minibuffer-history nil
1835 "Default minibuffer history list.
1836 This is used for all minibuffer input
1837 except when an alternate history list is specified.
1839 Maximum length of the history list is determined by the value
1840 of `history-length', which see.")
1841 (defvar minibuffer-history-sexp-flag nil
1842 "Control whether history list elements are expressions or strings.
1843 If the value of this variable equals current minibuffer depth,
1844 they are expressions; otherwise they are strings.
1845 \(That convention is designed to do the right thing for
1846 recursive uses of the minibuffer.)")
1847 (setq minibuffer-history-variable 'minibuffer-history)
1848 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1849 (defvar minibuffer-history-search-history nil)
1851 (defvar minibuffer-text-before-history nil
1852 "Text that was in this minibuffer before any history commands.
1853 This is nil if there have not yet been any history commands
1854 in this use of the minibuffer.")
1856 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1858 (defun minibuffer-history-initialize ()
1859 (setq minibuffer-text-before-history nil))
1861 (defun minibuffer-avoid-prompt (_new _old)
1862 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1863 (declare (obsolete cursor-intangible-mode "25.1"))
1864 (constrain-to-field nil (point-max)))
1866 (defcustom minibuffer-history-case-insensitive-variables nil
1867 "Minibuffer history variables for which matching should ignore case.
1868 If a history variable is a member of this list, then the
1869 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1870 commands ignore case when searching it, regardless of `case-fold-search'."
1871 :type '(repeat variable)
1872 :group 'minibuffer)
1874 (defun previous-matching-history-element (regexp n)
1875 "Find the previous history element that matches REGEXP.
1876 \(Previous history elements refer to earlier actions.)
1877 With prefix argument N, search for Nth previous match.
1878 If N is negative, find the next or Nth next match.
1879 Normally, history elements are matched case-insensitively if
1880 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1881 makes the search case-sensitive.
1882 See also `minibuffer-history-case-insensitive-variables'."
1883 (interactive
1884 (let* ((enable-recursive-minibuffers t)
1885 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1887 minibuffer-local-map
1889 'minibuffer-history-search-history
1890 (car minibuffer-history-search-history))))
1891 ;; Use the last regexp specified, by default, if input is empty.
1892 (list (if (string= regexp "")
1893 (if minibuffer-history-search-history
1894 (car minibuffer-history-search-history)
1895 (user-error "No previous history search regexp"))
1896 regexp)
1897 (prefix-numeric-value current-prefix-arg))))
1898 (unless (zerop n)
1899 (if (and (zerop minibuffer-history-position)
1900 (null minibuffer-text-before-history))
1901 (setq minibuffer-text-before-history
1902 (minibuffer-contents-no-properties)))
1903 (let ((history (symbol-value minibuffer-history-variable))
1904 (case-fold-search
1905 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1906 ;; On some systems, ignore case for file names.
1907 (if (memq minibuffer-history-variable
1908 minibuffer-history-case-insensitive-variables)
1910 ;; Respect the user's setting for case-fold-search:
1911 case-fold-search)
1912 nil))
1913 prevpos
1914 match-string
1915 match-offset
1916 (pos minibuffer-history-position))
1917 (while (/= n 0)
1918 (setq prevpos pos)
1919 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1920 (when (= pos prevpos)
1921 (user-error (if (= pos 1)
1922 "No later matching history item"
1923 "No earlier matching history item")))
1924 (setq match-string
1925 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1926 (let ((print-level nil))
1927 (prin1-to-string (nth (1- pos) history)))
1928 (nth (1- pos) history)))
1929 (setq match-offset
1930 (if (< n 0)
1931 (and (string-match regexp match-string)
1932 (match-end 0))
1933 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1934 (match-beginning 1))))
1935 (when match-offset
1936 (setq n (+ n (if (< n 0) 1 -1)))))
1937 (setq minibuffer-history-position pos)
1938 (goto-char (point-max))
1939 (delete-minibuffer-contents)
1940 (insert match-string)
1941 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1942 (if (memq (car (car command-history)) '(previous-matching-history-element
1943 next-matching-history-element))
1944 (setq command-history (cdr command-history))))
1946 (defun next-matching-history-element (regexp n)
1947 "Find the next history element that matches REGEXP.
1948 \(The next history element refers to a more recent action.)
1949 With prefix argument N, search for Nth next match.
1950 If N is negative, find the previous or Nth previous match.
1951 Normally, history elements are matched case-insensitively if
1952 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1953 makes the search case-sensitive."
1954 (interactive
1955 (let* ((enable-recursive-minibuffers t)
1956 (regexp (read-from-minibuffer "Next element matching (regexp): "
1958 minibuffer-local-map
1960 'minibuffer-history-search-history
1961 (car minibuffer-history-search-history))))
1962 ;; Use the last regexp specified, by default, if input is empty.
1963 (list (if (string= regexp "")
1964 (if minibuffer-history-search-history
1965 (car minibuffer-history-search-history)
1966 (user-error "No previous history search regexp"))
1967 regexp)
1968 (prefix-numeric-value current-prefix-arg))))
1969 (previous-matching-history-element regexp (- n)))
1971 (defvar minibuffer-temporary-goal-position nil)
1973 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1974 "Function run by `goto-history-element' before consuming default values.
1975 This is useful to dynamically add more elements to the list of default values
1976 when `goto-history-element' reaches the end of this list.
1977 Before calling this function `goto-history-element' sets the variable
1978 `minibuffer-default-add-done' to t, so it will call this function only
1979 once. In special cases, when this function needs to be called more
1980 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1981 overriding the setting of this variable to t in `goto-history-element'.")
1983 (defvar minibuffer-default-add-done nil
1984 "When nil, add more elements to the end of the list of default values.
1985 The value nil causes `goto-history-element' to add more elements to
1986 the list of defaults when it reaches the end of this list. It does
1987 this by calling a function defined by `minibuffer-default-add-function'.")
1989 (make-variable-buffer-local 'minibuffer-default-add-done)
1991 (defun minibuffer-default-add-completions ()
1992 "Return a list of all completions without the default value.
1993 This function is used to add all elements of the completion table to
1994 the end of the list of defaults just after the default value."
1995 (let ((def minibuffer-default)
1996 (all (all-completions ""
1997 minibuffer-completion-table
1998 minibuffer-completion-predicate)))
1999 (if (listp def)
2000 (append def all)
2001 (cons def (delete def all)))))
2003 (defun goto-history-element (nabs)
2004 "Puts element of the minibuffer history in the minibuffer.
2005 The argument NABS specifies the absolute history position."
2006 (interactive "p")
2007 (when (and (not minibuffer-default-add-done)
2008 (functionp minibuffer-default-add-function)
2009 (< nabs (- (if (listp minibuffer-default)
2010 (length minibuffer-default)
2011 1))))
2012 (setq minibuffer-default-add-done t
2013 minibuffer-default (funcall minibuffer-default-add-function)))
2014 (let ((minimum (if minibuffer-default
2015 (- (if (listp minibuffer-default)
2016 (length minibuffer-default)
2019 elt minibuffer-returned-to-present)
2020 (if (and (zerop minibuffer-history-position)
2021 (null minibuffer-text-before-history))
2022 (setq minibuffer-text-before-history
2023 (minibuffer-contents-no-properties)))
2024 (if (< nabs minimum)
2025 (user-error (if minibuffer-default
2026 "End of defaults; no next item"
2027 "End of history; no default available")))
2028 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
2029 (length (symbol-value minibuffer-history-variable))
2031 (user-error "Beginning of history; no preceding item"))
2032 (unless (memq last-command '(next-history-element
2033 previous-history-element))
2034 (let ((prompt-end (minibuffer-prompt-end)))
2035 (set (make-local-variable 'minibuffer-temporary-goal-position)
2036 (cond ((<= (point) prompt-end) prompt-end)
2037 ((eobp) nil)
2038 (t (point))))))
2039 (goto-char (point-max))
2040 (delete-minibuffer-contents)
2041 (setq minibuffer-history-position nabs)
2042 (cond ((< nabs 0)
2043 (setq elt (if (listp minibuffer-default)
2044 (nth (1- (abs nabs)) minibuffer-default)
2045 minibuffer-default)))
2046 ((= nabs 0)
2047 (setq elt (or minibuffer-text-before-history ""))
2048 (setq minibuffer-returned-to-present t)
2049 (setq minibuffer-text-before-history nil))
2050 (t (setq elt (nth (1- minibuffer-history-position)
2051 (symbol-value minibuffer-history-variable)))))
2052 (insert
2053 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2054 (not minibuffer-returned-to-present))
2055 (let ((print-level nil))
2056 (prin1-to-string elt))
2057 elt))
2058 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2060 (defun next-history-element (n)
2061 "Puts next element of the minibuffer history in the minibuffer.
2062 With argument N, it uses the Nth following element."
2063 (interactive "p")
2064 (or (zerop n)
2065 (goto-history-element (- minibuffer-history-position n))))
2067 (defun previous-history-element (n)
2068 "Puts previous element of the minibuffer history in the minibuffer.
2069 With argument N, it uses the Nth previous element."
2070 (interactive "p")
2071 (or (zerop n)
2072 (goto-history-element (+ minibuffer-history-position n))))
2074 (defun next-line-or-history-element (&optional arg)
2075 "Move cursor vertically down ARG lines, or to the next history element.
2076 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2077 next element of the minibuffer history in the minibuffer."
2078 (interactive "^p")
2079 (or arg (setq arg 1))
2080 (let* ((old-point (point))
2081 ;; Remember the original goal column of possibly multi-line input
2082 ;; excluding the length of the prompt on the first line.
2083 (prompt-end (minibuffer-prompt-end))
2084 (old-column (unless (and (eolp) (> (point) prompt-end))
2085 (if (= (line-number-at-pos) 1)
2086 (max (- (current-column) (1- prompt-end)) 0)
2087 (current-column)))))
2088 (condition-case nil
2089 (with-no-warnings
2090 (next-line arg))
2091 (end-of-buffer
2092 ;; Restore old position since `line-move-visual' moves point to
2093 ;; the end of the line when it fails to go to the next line.
2094 (goto-char old-point)
2095 (next-history-element arg)
2096 ;; Reset `temporary-goal-column' because a correct value is not
2097 ;; calculated when `next-line' above fails by bumping against
2098 ;; the bottom of the minibuffer (bug#22544).
2099 (setq temporary-goal-column 0)
2100 ;; Restore the original goal column on the last line
2101 ;; of possibly multi-line input.
2102 (goto-char (point-max))
2103 (when old-column
2104 (if (= (line-number-at-pos) 1)
2105 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2106 (move-to-column old-column)))))))
2108 (defun previous-line-or-history-element (&optional arg)
2109 "Move cursor vertically up ARG lines, or to the previous history element.
2110 When point moves over the top line of multi-line minibuffer, puts ARGth
2111 previous element of the minibuffer history in the minibuffer."
2112 (interactive "^p")
2113 (or arg (setq arg 1))
2114 (let* ((old-point (point))
2115 ;; Remember the original goal column of possibly multi-line input
2116 ;; excluding the length of the prompt on the first line.
2117 (prompt-end (minibuffer-prompt-end))
2118 (old-column (unless (and (eolp) (> (point) prompt-end))
2119 (if (= (line-number-at-pos) 1)
2120 (max (- (current-column) (1- prompt-end)) 0)
2121 (current-column)))))
2122 (condition-case nil
2123 (with-no-warnings
2124 (previous-line arg))
2125 (beginning-of-buffer
2126 ;; Restore old position since `line-move-visual' moves point to
2127 ;; the beginning of the line when it fails to go to the previous line.
2128 (goto-char old-point)
2129 (previous-history-element arg)
2130 ;; Reset `temporary-goal-column' because a correct value is not
2131 ;; calculated when `previous-line' above fails by bumping against
2132 ;; the top of the minibuffer (bug#22544).
2133 (setq temporary-goal-column 0)
2134 ;; Restore the original goal column on the first line
2135 ;; of possibly multi-line input.
2136 (goto-char (minibuffer-prompt-end))
2137 (if old-column
2138 (if (= (line-number-at-pos) 1)
2139 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2140 (move-to-column old-column))
2141 ;; Put the cursor at the end of the visual line instead of the
2142 ;; logical line, so the next `previous-line-or-history-element'
2143 ;; would move to the previous history element, not to a possible upper
2144 ;; visual line from the end of logical line in `line-move-visual' mode.
2145 (end-of-visual-line)
2146 ;; Since `end-of-visual-line' puts the cursor at the beginning
2147 ;; of the next visual line, move it one char back to the end
2148 ;; of the first visual line (bug#22544).
2149 (unless (eolp) (backward-char 1)))))))
2151 (defun next-complete-history-element (n)
2152 "Get next history element which completes the minibuffer before the point.
2153 The contents of the minibuffer after the point are deleted, and replaced
2154 by the new completion."
2155 (interactive "p")
2156 (let ((point-at-start (point)))
2157 (next-matching-history-element
2158 (concat
2159 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2161 ;; next-matching-history-element always puts us at (point-min).
2162 ;; Move to the position we were at before changing the buffer contents.
2163 ;; This is still sensible, because the text before point has not changed.
2164 (goto-char point-at-start)))
2166 (defun previous-complete-history-element (n)
2168 Get previous history element which completes the minibuffer before the point.
2169 The contents of the minibuffer after the point are deleted, and replaced
2170 by the new completion."
2171 (interactive "p")
2172 (next-complete-history-element (- n)))
2174 ;; For compatibility with the old subr of the same name.
2175 (defun minibuffer-prompt-width ()
2176 "Return the display width of the minibuffer prompt.
2177 Return 0 if current buffer is not a minibuffer."
2178 ;; Return the width of everything before the field at the end of
2179 ;; the buffer; this should be 0 for normal buffers.
2180 (1- (minibuffer-prompt-end)))
2182 ;; isearch minibuffer history
2183 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2185 (defvar minibuffer-history-isearch-message-overlay)
2186 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2188 (defun minibuffer-history-isearch-setup ()
2189 "Set up a minibuffer for using isearch to search the minibuffer history.
2190 Intended to be added to `minibuffer-setup-hook'."
2191 (set (make-local-variable 'isearch-search-fun-function)
2192 'minibuffer-history-isearch-search)
2193 (set (make-local-variable 'isearch-message-function)
2194 'minibuffer-history-isearch-message)
2195 (set (make-local-variable 'isearch-wrap-function)
2196 'minibuffer-history-isearch-wrap)
2197 (set (make-local-variable 'isearch-push-state-function)
2198 'minibuffer-history-isearch-push-state)
2199 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2201 (defun minibuffer-history-isearch-end ()
2202 "Clean up the minibuffer after terminating isearch in the minibuffer."
2203 (if minibuffer-history-isearch-message-overlay
2204 (delete-overlay minibuffer-history-isearch-message-overlay)))
2206 (defun minibuffer-history-isearch-search ()
2207 "Return the proper search function, for isearch in minibuffer history."
2208 (lambda (string bound noerror)
2209 (let ((search-fun
2210 ;; Use standard functions to search within minibuffer text
2211 (isearch-search-fun-default))
2212 found)
2213 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2214 ;; searching forward. Lazy-highlight calls this lambda with the
2215 ;; bound arg, so skip the minibuffer prompt.
2216 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2217 (goto-char (minibuffer-prompt-end)))
2219 ;; 1. First try searching in the initial minibuffer text
2220 (funcall search-fun string
2221 (if isearch-forward bound (minibuffer-prompt-end))
2222 noerror)
2223 ;; 2. If the above search fails, start putting next/prev history
2224 ;; elements in the minibuffer successively, and search the string
2225 ;; in them. Do this only when bound is nil (i.e. not while
2226 ;; lazy-highlighting search strings in the current minibuffer text).
2227 (unless bound
2228 (condition-case nil
2229 (progn
2230 (while (not found)
2231 (cond (isearch-forward
2232 (next-history-element 1)
2233 (goto-char (minibuffer-prompt-end)))
2235 (previous-history-element 1)
2236 (goto-char (point-max))))
2237 (setq isearch-barrier (point) isearch-opoint (point))
2238 ;; After putting the next/prev history element, search
2239 ;; the string in them again, until next-history-element
2240 ;; or previous-history-element raises an error at the
2241 ;; beginning/end of history.
2242 (setq found (funcall search-fun string
2243 (unless isearch-forward
2244 ;; For backward search, don't search
2245 ;; in the minibuffer prompt
2246 (minibuffer-prompt-end))
2247 noerror)))
2248 ;; Return point of the new search result
2249 (point))
2250 ;; Return nil when next(prev)-history-element fails
2251 (error nil)))))))
2253 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2254 "Display the minibuffer history search prompt.
2255 If there are no search errors, this function displays an overlay with
2256 the isearch prompt which replaces the original minibuffer prompt.
2257 Otherwise, it displays the standard isearch message returned from
2258 the function `isearch-message'."
2259 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2260 ;; Use standard function `isearch-message' when not in the minibuffer,
2261 ;; or search fails, or has an error (like incomplete regexp).
2262 ;; This function overwrites minibuffer text with isearch message,
2263 ;; so it's possible to see what is wrong in the search string.
2264 (isearch-message c-q-hack ellipsis)
2265 ;; Otherwise, put the overlay with the standard isearch prompt over
2266 ;; the initial minibuffer prompt.
2267 (if (overlayp minibuffer-history-isearch-message-overlay)
2268 (move-overlay minibuffer-history-isearch-message-overlay
2269 (point-min) (minibuffer-prompt-end))
2270 (setq minibuffer-history-isearch-message-overlay
2271 (make-overlay (point-min) (minibuffer-prompt-end)))
2272 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2273 (overlay-put minibuffer-history-isearch-message-overlay
2274 'display (isearch-message-prefix c-q-hack ellipsis))
2275 ;; And clear any previous isearch message.
2276 (message "")))
2278 (defun minibuffer-history-isearch-wrap ()
2279 "Wrap the minibuffer history search when search fails.
2280 Move point to the first history element for a forward search,
2281 or to the last history element for a backward search."
2282 ;; When `minibuffer-history-isearch-search' fails on reaching the
2283 ;; beginning/end of the history, wrap the search to the first/last
2284 ;; minibuffer history element.
2285 (if isearch-forward
2286 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2287 (goto-history-element 0))
2288 (setq isearch-success t)
2289 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2291 (defun minibuffer-history-isearch-push-state ()
2292 "Save a function restoring the state of minibuffer history search.
2293 Save `minibuffer-history-position' to the additional state parameter
2294 in the search status stack."
2295 (let ((pos minibuffer-history-position))
2296 (lambda (cmd)
2297 (minibuffer-history-isearch-pop-state cmd pos))))
2299 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2300 "Restore the minibuffer history search state.
2301 Go to the history element by the absolute history position HIST-POS."
2302 (goto-history-element hist-pos))
2305 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2306 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2308 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2309 "Table mapping redo records to the corresponding undo one.
2310 A redo record for undo-in-region maps to t.
2311 A redo record for ordinary undo maps to the following (earlier) undo.")
2313 (defvar undo-in-region nil
2314 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2316 (defvar undo-no-redo nil
2317 "If t, `undo' doesn't go through redo entries.")
2319 (defvar pending-undo-list nil
2320 "Within a run of consecutive undo commands, list remaining to be undone.
2321 If t, we undid all the way to the end of it.")
2323 (defun undo (&optional arg)
2324 "Undo some previous changes.
2325 Repeat this command to undo more changes.
2326 A numeric ARG serves as a repeat count.
2328 In Transient Mark mode when the mark is active, only undo changes within
2329 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2330 as an argument limits undo to changes within the current region."
2331 (interactive "*P")
2332 ;; Make last-command indicate for the next command that this was an undo.
2333 ;; That way, another undo will undo more.
2334 ;; If we get to the end of the undo history and get an error,
2335 ;; another undo command will find the undo history empty
2336 ;; and will get another error. To begin undoing the undos,
2337 ;; you must type some other command.
2338 (let* ((modified (buffer-modified-p))
2339 ;; For an indirect buffer, look in the base buffer for the
2340 ;; auto-save data.
2341 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2342 (recent-save (with-current-buffer base-buffer
2343 (recent-auto-save-p)))
2344 message)
2345 ;; If we get an error in undo-start,
2346 ;; the next command should not be a "consecutive undo".
2347 ;; So set `this-command' to something other than `undo'.
2348 (setq this-command 'undo-start)
2350 (unless (and (eq last-command 'undo)
2351 (or (eq pending-undo-list t)
2352 ;; If something (a timer or filter?) changed the buffer
2353 ;; since the previous command, don't continue the undo seq.
2354 (let ((list buffer-undo-list))
2355 (while (eq (car list) nil)
2356 (setq list (cdr list)))
2357 ;; If the last undo record made was made by undo
2358 ;; it shows nothing else happened in between.
2359 (gethash list undo-equiv-table))))
2360 (setq undo-in-region
2361 (or (region-active-p) (and arg (not (numberp arg)))))
2362 (if undo-in-region
2363 (undo-start (region-beginning) (region-end))
2364 (undo-start))
2365 ;; get rid of initial undo boundary
2366 (undo-more 1))
2367 ;; If we got this far, the next command should be a consecutive undo.
2368 (setq this-command 'undo)
2369 ;; Check to see whether we're hitting a redo record, and if
2370 ;; so, ask the user whether she wants to skip the redo/undo pair.
2371 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2372 (or (eq (selected-window) (minibuffer-window))
2373 (setq message (format "%s%s!"
2374 (if (or undo-no-redo (not equiv))
2375 "Undo" "Redo")
2376 (if undo-in-region " in region" ""))))
2377 (when (and (consp equiv) undo-no-redo)
2378 ;; The equiv entry might point to another redo record if we have done
2379 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2380 (while (let ((next (gethash equiv undo-equiv-table)))
2381 (if next (setq equiv next))))
2382 (setq pending-undo-list equiv)))
2383 (undo-more
2384 (if (numberp arg)
2385 (prefix-numeric-value arg)
2387 ;; Record the fact that the just-generated undo records come from an
2388 ;; undo operation--that is, they are redo records.
2389 ;; In the ordinary case (not within a region), map the redo
2390 ;; record to the following undos.
2391 ;; I don't know how to do that in the undo-in-region case.
2392 (let ((list buffer-undo-list))
2393 ;; Strip any leading undo boundaries there might be, like we do
2394 ;; above when checking.
2395 (while (eq (car list) nil)
2396 (setq list (cdr list)))
2397 (puthash list
2398 ;; Prevent identity mapping. This can happen if
2399 ;; consecutive nils are erroneously in undo list.
2400 (if (or undo-in-region (eq list pending-undo-list))
2402 pending-undo-list)
2403 undo-equiv-table))
2404 ;; Don't specify a position in the undo record for the undo command.
2405 ;; Instead, undoing this should move point to where the change is.
2406 (let ((tail buffer-undo-list)
2407 (prev nil))
2408 (while (car tail)
2409 (when (integerp (car tail))
2410 (let ((pos (car tail)))
2411 (if prev
2412 (setcdr prev (cdr tail))
2413 (setq buffer-undo-list (cdr tail)))
2414 (setq tail (cdr tail))
2415 (while (car tail)
2416 (if (eq pos (car tail))
2417 (if prev
2418 (setcdr prev (cdr tail))
2419 (setq buffer-undo-list (cdr tail)))
2420 (setq prev tail))
2421 (setq tail (cdr tail)))
2422 (setq tail nil)))
2423 (setq prev tail tail (cdr tail))))
2424 ;; Record what the current undo list says,
2425 ;; so the next command can tell if the buffer was modified in between.
2426 (and modified (not (buffer-modified-p))
2427 (with-current-buffer base-buffer
2428 (delete-auto-save-file-if-necessary recent-save)))
2429 ;; Display a message announcing success.
2430 (if message
2431 (message "%s" message))))
2433 (defun buffer-disable-undo (&optional buffer)
2434 "Make BUFFER stop keeping undo information.
2435 No argument or nil as argument means do this for the current buffer."
2436 (interactive)
2437 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2438 (setq buffer-undo-list t)))
2440 (defun undo-only (&optional arg)
2441 "Undo some previous changes.
2442 Repeat this command to undo more changes.
2443 A numeric ARG serves as a repeat count.
2444 Contrary to `undo', this will not redo a previous undo."
2445 (interactive "*p")
2446 (let ((undo-no-redo t)) (undo arg)))
2448 (defvar undo-in-progress nil
2449 "Non-nil while performing an undo.
2450 Some change-hooks test this variable to do something different.")
2452 (defun undo-more (n)
2453 "Undo back N undo-boundaries beyond what was already undone recently.
2454 Call `undo-start' to get ready to undo recent changes,
2455 then call `undo-more' one or more times to undo them."
2456 (or (listp pending-undo-list)
2457 (user-error (concat "No further undo information"
2458 (and undo-in-region " for region"))))
2459 (let ((undo-in-progress t))
2460 ;; Note: The following, while pulling elements off
2461 ;; `pending-undo-list' will call primitive change functions which
2462 ;; will push more elements onto `buffer-undo-list'.
2463 (setq pending-undo-list (primitive-undo n pending-undo-list))
2464 (if (null pending-undo-list)
2465 (setq pending-undo-list t))))
2467 (defun primitive-undo (n list)
2468 "Undo N records from the front of the list LIST.
2469 Return what remains of the list."
2471 ;; This is a good feature, but would make undo-start
2472 ;; unable to do what is expected.
2473 ;;(when (null (car (list)))
2474 ;; ;; If the head of the list is a boundary, it is the boundary
2475 ;; ;; preceding this command. Get rid of it and don't count it.
2476 ;; (setq list (cdr list))))
2478 (let ((arg n)
2479 ;; In a writable buffer, enable undoing read-only text that is
2480 ;; so because of text properties.
2481 (inhibit-read-only t)
2482 ;; Don't let `intangible' properties interfere with undo.
2483 (inhibit-point-motion-hooks t)
2484 ;; We use oldlist only to check for EQ. ++kfs
2485 (oldlist buffer-undo-list)
2486 (did-apply nil)
2487 (next nil))
2488 (while (> arg 0)
2489 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2490 ;; Handle an integer by setting point to that value.
2491 (pcase next
2492 ((pred integerp) (goto-char next))
2493 ;; Element (t . TIME) records previous modtime.
2494 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2495 ;; UNKNOWN_MODTIME_NSECS.
2496 (`(t . ,time)
2497 ;; If this records an obsolete save
2498 ;; (not matching the actual disk file)
2499 ;; then don't mark unmodified.
2500 (when (or (equal time (visited-file-modtime))
2501 (and (consp time)
2502 (equal (list (car time) (cdr time))
2503 (visited-file-modtime))))
2504 (when (fboundp 'unlock-buffer)
2505 (unlock-buffer))
2506 (set-buffer-modified-p nil)))
2507 ;; Element (nil PROP VAL BEG . END) is property change.
2508 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2509 (when (or (> (point-min) beg) (< (point-max) end))
2510 (error "Changes to be undone are outside visible portion of buffer"))
2511 (put-text-property beg end prop val))
2512 ;; Element (BEG . END) means range was inserted.
2513 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2514 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2515 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2516 (when (or (> (point-min) beg) (< (point-max) end))
2517 (error "Changes to be undone are outside visible portion of buffer"))
2518 ;; Set point first thing, so that undoing this undo
2519 ;; does not send point back to where it is now.
2520 (goto-char beg)
2521 (delete-region beg end))
2522 ;; Element (apply FUN . ARGS) means call FUN to undo.
2523 (`(apply . ,fun-args)
2524 (let ((currbuff (current-buffer)))
2525 (if (integerp (car fun-args))
2526 ;; Long format: (apply DELTA START END FUN . ARGS).
2527 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2528 (start-mark (copy-marker start nil))
2529 (end-mark (copy-marker end t)))
2530 (when (or (> (point-min) start) (< (point-max) end))
2531 (error "Changes to be undone are outside visible portion of buffer"))
2532 (apply fun args) ;; Use `save-current-buffer'?
2533 ;; Check that the function did what the entry
2534 ;; said it would do.
2535 (unless (and (= start start-mark)
2536 (= (+ delta end) end-mark))
2537 (error "Changes to be undone by function different than announced"))
2538 (set-marker start-mark nil)
2539 (set-marker end-mark nil))
2540 (apply fun-args))
2541 (unless (eq currbuff (current-buffer))
2542 (error "Undo function switched buffer"))
2543 (setq did-apply t)))
2544 ;; Element (STRING . POS) means STRING was deleted.
2545 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2546 (when (let ((apos (abs pos)))
2547 (or (< apos (point-min)) (> apos (point-max))))
2548 (error "Changes to be undone are outside visible portion of buffer"))
2549 (let (valid-marker-adjustments)
2550 ;; Check that marker adjustments which were recorded
2551 ;; with the (STRING . POS) record are still valid, ie
2552 ;; the markers haven't moved. We check their validity
2553 ;; before reinserting the string so as we don't need to
2554 ;; mind marker insertion-type.
2555 (while (and (markerp (car-safe (car list)))
2556 (integerp (cdr-safe (car list))))
2557 (let* ((marker-adj (pop list))
2558 (m (car marker-adj)))
2559 (and (eq (marker-buffer m) (current-buffer))
2560 (= pos m)
2561 (push marker-adj valid-marker-adjustments))))
2562 ;; Insert string and adjust point
2563 (if (< pos 0)
2564 (progn
2565 (goto-char (- pos))
2566 (insert string))
2567 (goto-char pos)
2568 (insert string)
2569 (goto-char pos))
2570 ;; Adjust the valid marker adjustments
2571 (dolist (adj valid-marker-adjustments)
2572 (set-marker (car adj)
2573 (- (car adj) (cdr adj))))))
2574 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2575 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2576 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2577 next)
2578 ;; Even though these elements are not expected in the undo
2579 ;; list, adjust them to be conservative for the 24.4
2580 ;; release. (Bug#16818)
2581 (when (marker-buffer marker)
2582 (set-marker marker
2583 (- marker offset)
2584 (marker-buffer marker))))
2585 (_ (error "Unrecognized entry in undo list %S" next))))
2586 (setq arg (1- arg)))
2587 ;; Make sure an apply entry produces at least one undo entry,
2588 ;; so the test in `undo' for continuing an undo series
2589 ;; will work right.
2590 (if (and did-apply
2591 (eq oldlist buffer-undo-list))
2592 (setq buffer-undo-list
2593 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2594 list)
2596 ;; Deep copy of a list
2597 (defun undo-copy-list (list)
2598 "Make a copy of undo list LIST."
2599 (mapcar 'undo-copy-list-1 list))
2601 (defun undo-copy-list-1 (elt)
2602 (if (consp elt)
2603 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2604 elt))
2606 (defun undo-start (&optional beg end)
2607 "Set `pending-undo-list' to the front of the undo list.
2608 The next call to `undo-more' will undo the most recently made change.
2609 If BEG and END are specified, then only undo elements
2610 that apply to text between BEG and END are used; other undo elements
2611 are ignored. If BEG and END are nil, all undo elements are used."
2612 (if (eq buffer-undo-list t)
2613 (user-error "No undo information in this buffer"))
2614 (setq pending-undo-list
2615 (if (and beg end (not (= beg end)))
2616 (undo-make-selective-list (min beg end) (max beg end))
2617 buffer-undo-list)))
2619 ;; The positions given in elements of the undo list are the positions
2620 ;; as of the time that element was recorded to undo history. In
2621 ;; general, subsequent buffer edits render those positions invalid in
2622 ;; the current buffer, unless adjusted according to the intervening
2623 ;; undo elements.
2625 ;; Undo in region is a use case that requires adjustments to undo
2626 ;; elements. It must adjust positions of elements in the region based
2627 ;; on newer elements not in the region so as they may be correctly
2628 ;; applied in the current buffer. undo-make-selective-list
2629 ;; accomplishes this with its undo-deltas list of adjustments. An
2630 ;; example undo history from oldest to newest:
2632 ;; buf pos:
2633 ;; 123456789 buffer-undo-list undo-deltas
2634 ;; --------- ---------------- -----------
2635 ;; aaa (1 . 4) (1 . -3)
2636 ;; aaba (3 . 4) N/A (in region)
2637 ;; ccaaba (1 . 3) (1 . -2)
2638 ;; ccaabaddd (7 . 10) (7 . -3)
2639 ;; ccaabdd ("ad" . 6) (6 . 2)
2640 ;; ccaabaddd (6 . 8) (6 . -2)
2641 ;; | |<-- region: "caab", from 2 to 6
2643 ;; When the user starts a run of undos in region,
2644 ;; undo-make-selective-list is called to create the full list of in
2645 ;; region elements. Each element is adjusted forward chronologically
2646 ;; through undo-deltas to determine if it is in the region.
2648 ;; In the above example, the insertion of "b" is (3 . 4) in the
2649 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2650 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2651 ;; . 6) is assessed as in the region and placed in the selective list.
2652 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2653 ;; due to the selected element. The "b" insertion is the only element
2654 ;; fully in the region, so in this example undo-make-selective-list
2655 ;; returns (nil (5 . 6)).
2657 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2658 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2659 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2660 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2661 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2663 ;; More interesting is how to adjust the "ddd" insertion due to the
2664 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2665 ;; If the reinsertion was a manual retyping of "ad", then the total
2666 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2667 ;; the reinsertion was due to undo, one might expect the first "d"
2668 ;; character would again be a part of the "ddd" text, meaning its
2669 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2671 ;; undo-make-selective-list assumes in this situation that "ad" was a
2672 ;; new edit, even if it was inserted because of an undo.
2673 ;; Consequently, if the user undos in region "8 to 10" of the
2674 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2675 ;; "ccaabad", as though the first "d" became detached from the
2676 ;; original "ddd" insertion. This quirk is a FIXME.
2678 (defun undo-make-selective-list (start end)
2679 "Return a list of undo elements for the region START to END.
2680 The elements come from `buffer-undo-list', but we keep only the
2681 elements inside this region, and discard those outside this
2682 region. The elements' positions are adjusted so as the returned
2683 list can be applied to the current buffer."
2684 (let ((ulist buffer-undo-list)
2685 ;; A list of position adjusted undo elements in the region.
2686 (selective-list (list nil))
2687 ;; A list of undo-deltas for out of region undo elements.
2688 undo-deltas
2689 undo-elt)
2690 (while ulist
2691 (when undo-no-redo
2692 (while (gethash ulist undo-equiv-table)
2693 (setq ulist (gethash ulist undo-equiv-table))))
2694 (setq undo-elt (car ulist))
2695 (cond
2696 ((null undo-elt)
2697 ;; Don't put two nils together in the list
2698 (when (car selective-list)
2699 (push nil selective-list)))
2700 ((and (consp undo-elt) (eq (car undo-elt) t))
2701 ;; This is a "was unmodified" element. Keep it
2702 ;; if we have kept everything thus far.
2703 (when (not undo-deltas)
2704 (push undo-elt selective-list)))
2705 ;; Skip over marker adjustments, instead relying
2706 ;; on finding them after (TEXT . POS) elements
2707 ((markerp (car-safe undo-elt))
2708 nil)
2710 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2711 undo-deltas)))
2712 (if (undo-elt-in-region adjusted-undo-elt start end)
2713 (progn
2714 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2715 (push adjusted-undo-elt selective-list)
2716 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2717 ;; kept. primitive-undo may discard them later.
2718 (when (and (stringp (car-safe adjusted-undo-elt))
2719 (integerp (cdr-safe adjusted-undo-elt)))
2720 (let ((list-i (cdr ulist)))
2721 (while (markerp (car-safe (car list-i)))
2722 (push (pop list-i) selective-list)))))
2723 (let ((delta (undo-delta undo-elt)))
2724 (when (/= 0 (cdr delta))
2725 (push delta undo-deltas)))))))
2726 (pop ulist))
2727 (nreverse selective-list)))
2729 (defun undo-elt-in-region (undo-elt start end)
2730 "Determine whether UNDO-ELT falls inside the region START ... END.
2731 If it crosses the edge, we return nil.
2733 Generally this function is not useful for determining
2734 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2735 because markers can be arbitrarily relocated. Instead, pass the
2736 marker adjustment's corresponding (TEXT . POS) element."
2737 (cond ((integerp undo-elt)
2738 (and (>= undo-elt start)
2739 (<= undo-elt end)))
2740 ((eq undo-elt nil)
2742 ((atom undo-elt)
2743 nil)
2744 ((stringp (car undo-elt))
2745 ;; (TEXT . POSITION)
2746 (and (>= (abs (cdr undo-elt)) start)
2747 (<= (abs (cdr undo-elt)) end)))
2748 ((and (consp undo-elt) (markerp (car undo-elt)))
2749 ;; (MARKER . ADJUSTMENT)
2750 (<= start (car undo-elt) end))
2751 ((null (car undo-elt))
2752 ;; (nil PROPERTY VALUE BEG . END)
2753 (let ((tail (nthcdr 3 undo-elt)))
2754 (and (>= (car tail) start)
2755 (<= (cdr tail) end))))
2756 ((integerp (car undo-elt))
2757 ;; (BEGIN . END)
2758 (and (>= (car undo-elt) start)
2759 (<= (cdr undo-elt) end)))))
2761 (defun undo-elt-crosses-region (undo-elt start end)
2762 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2763 This assumes we have already decided that UNDO-ELT
2764 is not *inside* the region START...END."
2765 (declare (obsolete nil "25.1"))
2766 (cond ((atom undo-elt) nil)
2767 ((null (car undo-elt))
2768 ;; (nil PROPERTY VALUE BEG . END)
2769 (let ((tail (nthcdr 3 undo-elt)))
2770 (and (< (car tail) end)
2771 (> (cdr tail) start))))
2772 ((integerp (car undo-elt))
2773 ;; (BEGIN . END)
2774 (and (< (car undo-elt) end)
2775 (> (cdr undo-elt) start)))))
2777 (defun undo-adjust-elt (elt deltas)
2778 "Return adjustment of undo element ELT by the undo DELTAS
2779 list."
2780 (pcase elt
2781 ;; POSITION
2782 ((pred integerp)
2783 (undo-adjust-pos elt deltas))
2784 ;; (BEG . END)
2785 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2786 (undo-adjust-beg-end beg end deltas))
2787 ;; (TEXT . POSITION)
2788 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2789 (cons text (* (if (< pos 0) -1 1)
2790 (undo-adjust-pos (abs pos) deltas))))
2791 ;; (nil PROPERTY VALUE BEG . END)
2792 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2793 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2794 ;; (apply DELTA START END FUN . ARGS)
2795 ;; FIXME
2796 ;; All others return same elt
2797 (_ elt)))
2799 ;; (BEG . END) can adjust to the same positions, commonly when an
2800 ;; insertion was undone and they are out of region, for example:
2802 ;; buf pos:
2803 ;; 123456789 buffer-undo-list undo-deltas
2804 ;; --------- ---------------- -----------
2805 ;; [...]
2806 ;; abbaa (2 . 4) (2 . -2)
2807 ;; aaa ("bb" . 2) (2 . 2)
2808 ;; [...]
2810 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2811 ;; undo. Further adjustments to such an element should be the same as
2812 ;; for (TEXT . POSITION) elements. The options are:
2814 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2815 ;; analogous to marker insertion-type t.
2817 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2818 ;; marker insertion-type nil.
2820 ;; There was no strong reason to prefer one or the other, except that
2821 ;; the first is more consistent with prior undo in region behavior.
2822 (defun undo-adjust-beg-end (beg end deltas)
2823 "Return cons of adjustments to BEG and END by the undo DELTAS
2824 list."
2825 (let ((adj-beg (undo-adjust-pos beg deltas)))
2826 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2827 (cons adj-beg
2828 (max adj-beg (undo-adjust-pos end deltas t)))))
2830 (defun undo-adjust-pos (pos deltas &optional use-<)
2831 "Return adjustment of POS by the undo DELTAS list, comparing
2832 with < or <= based on USE-<."
2833 (dolist (d deltas pos)
2834 (when (if use-<
2835 (< (car d) pos)
2836 (<= (car d) pos))
2837 (setq pos
2838 ;; Don't allow pos to become less than the undo-delta
2839 ;; position. This edge case is described in the overview
2840 ;; comments.
2841 (max (car d) (- pos (cdr d)))))))
2843 ;; Return the first affected buffer position and the delta for an undo element
2844 ;; delta is defined as the change in subsequent buffer positions if we *did*
2845 ;; the undo.
2846 (defun undo-delta (undo-elt)
2847 (if (consp undo-elt)
2848 (cond ((stringp (car undo-elt))
2849 ;; (TEXT . POSITION)
2850 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2851 ((integerp (car undo-elt))
2852 ;; (BEGIN . END)
2853 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2855 '(0 . 0)))
2856 '(0 . 0)))
2858 ;;; Default undo-boundary addition
2860 ;; This section adds a new undo-boundary at either after a command is
2861 ;; called or in some cases on a timer called after a change is made in
2862 ;; any buffer.
2863 (defvar-local undo-auto--last-boundary-cause nil
2864 "Describe the cause of the last undo-boundary.
2866 If `explicit', the last boundary was caused by an explicit call to
2867 `undo-boundary', that is one not called by the code in this
2868 section.
2870 If it is equal to `timer', then the last boundary was inserted
2871 by `undo-auto--boundary-timer'.
2873 If it is equal to `command', then the last boundary was inserted
2874 automatically after a command, that is by the code defined in
2875 this section.
2877 If it is equal to a list, then the last boundary was inserted by
2878 an amalgamating command. The car of the list is the number of
2879 times an amalgamating command has been called, and the cdr are the
2880 buffers that were changed during the last command.")
2882 (defvar undo-auto-current-boundary-timer nil
2883 "Current timer which will run `undo-auto--boundary-timer' or nil.
2885 If set to non-nil, this will effectively disable the timer.")
2887 (defvar undo-auto--this-command-amalgamating nil
2888 "Non-nil if `this-command' should be amalgamated.
2889 This variable is set to nil by `undo-auto--boundaries' and is set
2890 by `undo-auto-amalgamate'." )
2892 (defun undo-auto--needs-boundary-p ()
2893 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2894 (car-safe buffer-undo-list))
2896 (defun undo-auto--last-boundary-amalgamating-number ()
2897 "Return the number of amalgamating last commands or nil.
2898 Amalgamating commands are, by default, either
2899 `self-insert-command' and `delete-char', but can be any command
2900 that calls `undo-auto-amalgamate'."
2901 (car-safe undo-auto--last-boundary-cause))
2903 (defun undo-auto--ensure-boundary (cause)
2904 "Add an `undo-boundary' to the current buffer if needed.
2905 REASON describes the reason that the boundary is being added; see
2906 `undo-auto--last-boundary' for more information."
2907 (when (and
2908 (undo-auto--needs-boundary-p))
2909 (let ((last-amalgamating
2910 (undo-auto--last-boundary-amalgamating-number)))
2911 (undo-boundary)
2912 (setq undo-auto--last-boundary-cause
2913 (if (eq 'amalgamate cause)
2914 (cons
2915 (if last-amalgamating (1+ last-amalgamating) 0)
2916 undo-auto--undoably-changed-buffers)
2917 cause)))))
2919 (defun undo-auto--boundaries (cause)
2920 "Check recently changed buffers and add a boundary if necessary.
2921 REASON describes the reason that the boundary is being added; see
2922 `undo-last-boundary' for more information."
2923 ;; (Bug #23785) All commands should ensure that there is an undo
2924 ;; boundary whether they have changed the current buffer or not.
2925 (when (eq cause 'command)
2926 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2927 (dolist (b undo-auto--undoably-changed-buffers)
2928 (when (buffer-live-p b)
2929 (with-current-buffer b
2930 (undo-auto--ensure-boundary cause))))
2931 (setq undo-auto--undoably-changed-buffers nil))
2933 (defun undo-auto--boundary-timer ()
2934 "Timer which will run `undo--auto-boundary-timer'."
2935 (setq undo-auto-current-boundary-timer nil)
2936 (undo-auto--boundaries 'timer))
2938 (defun undo-auto--boundary-ensure-timer ()
2939 "Ensure that the `undo-auto-boundary-timer' is set."
2940 (unless undo-auto-current-boundary-timer
2941 (setq undo-auto-current-boundary-timer
2942 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2944 (defvar undo-auto--undoably-changed-buffers nil
2945 "List of buffers that have changed recently.
2947 This list is maintained by `undo-auto--undoable-change' and
2948 `undo-auto--boundaries' and can be affected by changes to their
2949 default values.")
2951 (defun undo-auto--add-boundary ()
2952 "Add an `undo-boundary' in appropriate buffers."
2953 (undo-auto--boundaries
2954 (let ((amal undo-auto--this-command-amalgamating))
2955 (setq undo-auto--this-command-amalgamating nil)
2956 (if amal
2957 'amalgamate
2958 'command))))
2960 (defun undo-auto-amalgamate ()
2961 "Amalgamate undo if necessary.
2962 This function can be called before an amalgamating command. It
2963 removes the previous `undo-boundary' if a series of such calls
2964 have been made. By default `self-insert-command' and
2965 `delete-char' are the only amalgamating commands, although this
2966 function could be called by any command wishing to have this
2967 behavior."
2968 (let ((last-amalgamating-count
2969 (undo-auto--last-boundary-amalgamating-number)))
2970 (setq undo-auto--this-command-amalgamating t)
2971 (when
2972 last-amalgamating-count
2974 (and
2975 (< last-amalgamating-count 20)
2976 (eq this-command last-command))
2977 ;; Amalgamate all buffers that have changed.
2978 (dolist (b (cdr undo-auto--last-boundary-cause))
2979 (when (buffer-live-p b)
2980 (with-current-buffer
2982 (when
2983 ;; The head of `buffer-undo-list' is nil.
2984 ;; `car-safe' doesn't work because
2985 ;; `buffer-undo-list' need not be a list!
2986 (and (listp buffer-undo-list)
2987 (not (car buffer-undo-list)))
2988 (setq buffer-undo-list
2989 (cdr buffer-undo-list))))))
2990 (setq undo-auto--last-boundary-cause 0)))))
2992 (defun undo-auto--undoable-change ()
2993 "Called after every undoable buffer change."
2994 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
2995 (undo-auto--boundary-ensure-timer))
2996 ;; End auto-boundary section
2998 (defun undo-amalgamate-change-group (handle)
2999 "Amalgamate changes in change-group since HANDLE.
3000 Remove all undo boundaries between the state of HANDLE and now.
3001 HANDLE is as returned by `prepare-change-group'."
3002 (dolist (elt handle)
3003 (with-current-buffer (car elt)
3004 (setq elt (cdr elt))
3005 (when (consp buffer-undo-list)
3006 (let ((old-car (car-safe elt))
3007 (old-cdr (cdr-safe elt)))
3008 (unwind-protect
3009 (progn
3010 ;; Temporarily truncate the undo log at ELT.
3011 (when (consp elt)
3012 (setcar elt t) (setcdr elt nil))
3013 (when
3014 (or (null elt) ;The undo-log was empty.
3015 ;; `elt' is still in the log: normal case.
3016 (eq elt (last buffer-undo-list))
3017 ;; `elt' is not in the log any more, but that's because
3018 ;; the log is "all new", so we should remove all
3019 ;; boundaries from it.
3020 (not (eq (last buffer-undo-list) (last old-cdr))))
3021 (cl-callf (lambda (x) (delq nil x))
3022 (if (car buffer-undo-list)
3023 buffer-undo-list
3024 ;; Preserve the undo-boundaries at either ends of the
3025 ;; change-groups.
3026 (cdr buffer-undo-list)))))
3027 ;; Reset the modified cons cell ELT to its original content.
3028 (when (consp elt)
3029 (setcar elt old-car)
3030 (setcdr elt old-cdr))))))))
3033 (defcustom undo-ask-before-discard nil
3034 "If non-nil ask about discarding undo info for the current command.
3035 Normally, Emacs discards the undo info for the current command if
3036 it exceeds `undo-outer-limit'. But if you set this option
3037 non-nil, it asks in the echo area whether to discard the info.
3038 If you answer no, there is a slight risk that Emacs might crash, so
3039 only do it if you really want to undo the command.
3041 This option is mainly intended for debugging. You have to be
3042 careful if you use it for other purposes. Garbage collection is
3043 inhibited while the question is asked, meaning that Emacs might
3044 leak memory. So you should make sure that you do not wait
3045 excessively long before answering the question."
3046 :type 'boolean
3047 :group 'undo
3048 :version "22.1")
3050 (defvar undo-extra-outer-limit nil
3051 "If non-nil, an extra level of size that's ok in an undo item.
3052 We don't ask the user about truncating the undo list until the
3053 current item gets bigger than this amount.
3055 This variable only matters if `undo-ask-before-discard' is non-nil.")
3056 (make-variable-buffer-local 'undo-extra-outer-limit)
3058 ;; When the first undo batch in an undo list is longer than
3059 ;; undo-outer-limit, this function gets called to warn the user that
3060 ;; the undo info for the current command was discarded. Garbage
3061 ;; collection is inhibited around the call, so it had better not do a
3062 ;; lot of consing.
3063 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3064 (defun undo-outer-limit-truncate (size)
3065 (if undo-ask-before-discard
3066 (when (or (null undo-extra-outer-limit)
3067 (> size undo-extra-outer-limit))
3068 ;; Don't ask the question again unless it gets even bigger.
3069 ;; This applies, in particular, if the user quits from the question.
3070 ;; Such a quit quits out of GC, but something else will call GC
3071 ;; again momentarily. It will call this function again,
3072 ;; but we don't want to ask the question again.
3073 (setq undo-extra-outer-limit (+ size 50000))
3074 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3075 (yes-or-no-p (format-message
3076 "Buffer `%s' undo info is %d bytes long; discard it? "
3077 (buffer-name) size)))
3078 (progn (setq buffer-undo-list nil)
3079 (setq undo-extra-outer-limit nil)
3081 nil))
3082 (display-warning '(undo discard-info)
3083 (concat
3084 (format-message
3085 "Buffer `%s' undo info was %d bytes long.\n"
3086 (buffer-name) size)
3087 "The undo info was discarded because it exceeded \
3088 `undo-outer-limit'.
3090 This is normal if you executed a command that made a huge change
3091 to the buffer. In that case, to prevent similar problems in the
3092 future, set `undo-outer-limit' to a value that is large enough to
3093 cover the maximum size of normal changes you expect a single
3094 command to make, but not so large that it might exceed the
3095 maximum memory allotted to Emacs.
3097 If you did not execute any such command, the situation is
3098 probably due to a bug and you should report it.
3100 You can disable the popping up of this buffer by adding the entry
3101 \(undo discard-info) to the user option `warning-suppress-types',
3102 which is defined in the `warnings' library.\n")
3103 :warning)
3104 (setq buffer-undo-list nil)
3107 (defcustom password-word-equivalents
3108 '("password" "passcode" "passphrase" "pass phrase"
3109 ; These are sorted according to the GNU en_US locale.
3110 "암호" ; ko
3111 "パスワード" ; ja
3112 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3113 "ពាក្យសម្ងាត់" ; km
3114 "adgangskode" ; da
3115 "contraseña" ; es
3116 "contrasenya" ; ca
3117 "geslo" ; sl
3118 "hasło" ; pl
3119 "heslo" ; cs, sk
3120 "iphasiwedi" ; zu
3121 "jelszó" ; hu
3122 "lösenord" ; sv
3123 "lozinka" ; hr, sr
3124 "mật khẩu" ; vi
3125 "mot de passe" ; fr
3126 "parola" ; tr
3127 "pasahitza" ; eu
3128 "passord" ; nb
3129 "passwort" ; de
3130 "pasvorto" ; eo
3131 "salasana" ; fi
3132 "senha" ; pt
3133 "slaptažodis" ; lt
3134 "wachtwoord" ; nl
3135 "كلمة السر" ; ar
3136 "ססמה" ; he
3137 "лозинка" ; sr
3138 "пароль" ; kk, ru, uk
3139 "गुप्तशब्द" ; mr
3140 "शब्दकूट" ; hi
3141 "પાસવર્ડ" ; gu
3142 "సంకేతపదము" ; te
3143 "ਪਾਸਵਰਡ" ; pa
3144 "ಗುಪ್ತಪದ" ; kn
3145 "கடவுச்சொல்" ; ta
3146 "അടയാളവാക്ക്" ; ml
3147 "গুপ্তশব্দ" ; as
3148 "পাসওয়ার্ড" ; bn_IN
3149 "රහස්පදය" ; si
3150 "密码" ; zh_CN
3151 "密碼" ; zh_TW
3153 "List of words equivalent to \"password\".
3154 This is used by Shell mode and other parts of Emacs to recognize
3155 password prompts, including prompts in languages other than
3156 English. Different case choices should not be assumed to be
3157 included; callers should bind `case-fold-search' to t."
3158 :type '(repeat string)
3159 :version "24.4"
3160 :group 'processes)
3162 (defvar shell-command-history nil
3163 "History list for some commands that read shell commands.
3165 Maximum length of the history list is determined by the value
3166 of `history-length', which see.")
3168 (defvar shell-command-switch (purecopy "-c")
3169 "Switch used to have the shell execute its command line argument.")
3171 (defvar shell-command-default-error-buffer nil
3172 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3173 This buffer is used when `shell-command' or `shell-command-on-region'
3174 is run interactively. A value of nil means that output to stderr and
3175 stdout will be intermixed in the output stream.")
3177 (declare-function mailcap-file-default-commands "mailcap" (files))
3178 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3180 (defun minibuffer-default-add-shell-commands ()
3181 "Return a list of all commands associated with the current file.
3182 This function is used to add all related commands retrieved by `mailcap'
3183 to the end of the list of defaults just after the default value."
3184 (interactive)
3185 (let* ((filename (if (listp minibuffer-default)
3186 (car minibuffer-default)
3187 minibuffer-default))
3188 (commands (and filename (require 'mailcap nil t)
3189 (mailcap-file-default-commands (list filename)))))
3190 (setq commands (mapcar (lambda (command)
3191 (concat command " " filename))
3192 commands))
3193 (if (listp minibuffer-default)
3194 (append minibuffer-default commands)
3195 (cons minibuffer-default commands))))
3197 (declare-function shell-completion-vars "shell" ())
3199 (defvar minibuffer-local-shell-command-map
3200 (let ((map (make-sparse-keymap)))
3201 (set-keymap-parent map minibuffer-local-map)
3202 (define-key map "\t" 'completion-at-point)
3203 map)
3204 "Keymap used for completing shell commands in minibuffer.")
3206 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3207 "Read a shell command from the minibuffer.
3208 The arguments are the same as the ones of `read-from-minibuffer',
3209 except READ and KEYMAP are missing and HIST defaults
3210 to `shell-command-history'."
3211 (require 'shell)
3212 (minibuffer-with-setup-hook
3213 (lambda ()
3214 (shell-completion-vars)
3215 (set (make-local-variable 'minibuffer-default-add-function)
3216 'minibuffer-default-add-shell-commands))
3217 (apply 'read-from-minibuffer prompt initial-contents
3218 minibuffer-local-shell-command-map
3220 (or hist 'shell-command-history)
3221 args)))
3223 (defcustom async-shell-command-buffer 'confirm-new-buffer
3224 "What to do when the output buffer is used by another shell command.
3225 This option specifies how to resolve the conflict where a new command
3226 wants to direct its output to the buffer `*Async Shell Command*',
3227 but this buffer is already taken by another running shell command.
3229 The value `confirm-kill-process' is used to ask for confirmation before
3230 killing the already running process and running a new process
3231 in the same buffer, `confirm-new-buffer' for confirmation before running
3232 the command in a new buffer with a name other than the default buffer name,
3233 `new-buffer' for doing the same without confirmation,
3234 `confirm-rename-buffer' for confirmation before renaming the existing
3235 output buffer and running a new command in the default buffer,
3236 `rename-buffer' for doing the same without confirmation."
3237 :type '(choice (const :tag "Confirm killing of running command"
3238 confirm-kill-process)
3239 (const :tag "Confirm creation of a new buffer"
3240 confirm-new-buffer)
3241 (const :tag "Create a new buffer"
3242 new-buffer)
3243 (const :tag "Confirm renaming of existing buffer"
3244 confirm-rename-buffer)
3245 (const :tag "Rename the existing buffer"
3246 rename-buffer))
3247 :group 'shell
3248 :version "24.3")
3250 (defun shell-command--save-pos-or-erase ()
3251 "Store a buffer position or erase the buffer.
3252 See `shell-command-dont-erase-buffer'."
3253 (let ((sym shell-command-dont-erase-buffer)
3254 pos)
3255 (setq buffer-read-only nil)
3256 ;; Setting buffer-read-only to nil doesn't suffice
3257 ;; if some text has a non-nil read-only property,
3258 ;; which comint sometimes adds for prompts.
3259 (setq pos
3260 (cond ((eq sym 'save-point) (point))
3261 ((eq sym 'beg-last-out) (point-max))
3262 ((not sym)
3263 (let ((inhibit-read-only t))
3264 (erase-buffer) nil))))
3265 (when pos
3266 (goto-char (point-max))
3267 (push (cons (current-buffer) pos)
3268 shell-command-saved-pos))))
3270 (defun shell-command--set-point-after-cmd (&optional buffer)
3271 "Set point in BUFFER after command complete.
3272 BUFFER is the output buffer of the command; if nil, then defaults
3273 to the current BUFFER.
3274 Set point to the `cdr' of the element in `shell-command-saved-pos'
3275 whose `car' is BUFFER."
3276 (when shell-command-dont-erase-buffer
3277 (let* ((sym shell-command-dont-erase-buffer)
3278 (buf (or buffer (current-buffer)))
3279 (pos (alist-get buf shell-command-saved-pos)))
3280 (setq shell-command-saved-pos
3281 (assq-delete-all buf shell-command-saved-pos))
3282 (when (buffer-live-p buf)
3283 (let ((win (car (get-buffer-window-list buf)))
3284 (pmax (with-current-buffer buf (point-max))))
3285 (unless (and pos (memq sym '(save-point beg-last-out)))
3286 (setq pos pmax))
3287 ;; Set point in the window displaying buf, if any; otherwise
3288 ;; display buf temporary in selected frame and set the point.
3289 (if win
3290 (set-window-point win pos)
3291 (save-window-excursion
3292 (let ((win (display-buffer
3294 '(nil (inhibit-switch-frame . t)))))
3295 (set-window-point win pos)))))))))
3297 (defun async-shell-command (command &optional output-buffer error-buffer)
3298 "Execute string COMMAND asynchronously in background.
3300 Like `shell-command', but adds `&' at the end of COMMAND
3301 to execute it asynchronously.
3303 The output appears in the buffer `*Async Shell Command*'.
3304 That buffer is in shell mode.
3306 You can configure `async-shell-command-buffer' to specify what to do in
3307 case when `*Async Shell Command*' buffer is already taken by another
3308 running shell command. To run COMMAND without displaying the output
3309 in a window you can configure `display-buffer-alist' to use the action
3310 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3312 In Elisp, you will often be better served by calling `start-process'
3313 directly, since it offers more control and does not impose the use of a
3314 shell (with its need to quote arguments)."
3315 (interactive
3316 (list
3317 (read-shell-command "Async shell command: " nil nil
3318 (let ((filename
3319 (cond
3320 (buffer-file-name)
3321 ((eq major-mode 'dired-mode)
3322 (dired-get-filename nil t)))))
3323 (and filename (file-relative-name filename))))
3324 current-prefix-arg
3325 shell-command-default-error-buffer))
3326 (unless (string-match "&[ \t]*\\'" command)
3327 (setq command (concat command " &")))
3328 (shell-command command output-buffer error-buffer))
3330 (defun shell-command (command &optional output-buffer error-buffer)
3331 "Execute string COMMAND in inferior shell; display output, if any.
3332 With prefix argument, insert the COMMAND's output at point.
3334 Interactively, prompt for COMMAND in the minibuffer.
3336 If COMMAND ends in `&', execute it asynchronously.
3337 The output appears in the buffer `*Async Shell Command*'.
3338 That buffer is in shell mode. You can also use
3339 `async-shell-command' that automatically adds `&'.
3341 Otherwise, COMMAND is executed synchronously. The output appears in
3342 the buffer `*Shell Command Output*'. If the output is short enough to
3343 display in the echo area (which is determined by the variables
3344 `resize-mini-windows' and `max-mini-window-height'), it is shown
3345 there, but it is nonetheless available in buffer `*Shell Command
3346 Output*' even though that buffer is not automatically displayed.
3348 To specify a coding system for converting non-ASCII characters
3349 in the shell command output, use \\[universal-coding-system-argument] \
3350 before this command.
3352 Noninteractive callers can specify coding systems by binding
3353 `coding-system-for-read' and `coding-system-for-write'.
3355 The optional second argument OUTPUT-BUFFER, if non-nil,
3356 says to put the output in some other buffer.
3357 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3358 and insert the output there; a non-nil value of
3359 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3360 If OUTPUT-BUFFER is not a buffer and not nil, insert the output
3361 in current buffer after point leaving mark after it.
3362 This cannot be done asynchronously.
3364 If the command terminates without error, but generates output,
3365 and you did not specify \"insert it in the current buffer\",
3366 the output can be displayed in the echo area or in its buffer.
3367 If the output is short enough to display in the echo area
3368 \(determined by the variable `max-mini-window-height' if
3369 `resize-mini-windows' is non-nil), it is shown there.
3370 Otherwise,the buffer containing the output is displayed.
3372 If there is output and an error, and you did not specify \"insert it
3373 in the current buffer\", a message about the error goes at the end
3374 of the output.
3376 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3377 or buffer name to which to direct the command's standard error output.
3378 If it is nil, error output is mingled with regular output.
3379 In an interactive call, the variable `shell-command-default-error-buffer'
3380 specifies the value of ERROR-BUFFER.
3382 In Elisp, you will often be better served by calling `call-process' or
3383 `start-process' directly, since it offers more control and does not impose
3384 the use of a shell (with its need to quote arguments)."
3386 (interactive
3387 (list
3388 (read-shell-command "Shell command: " nil nil
3389 (let ((filename
3390 (cond
3391 (buffer-file-name)
3392 ((eq major-mode 'dired-mode)
3393 (dired-get-filename nil t)))))
3394 (and filename (file-relative-name filename))))
3395 current-prefix-arg
3396 shell-command-default-error-buffer))
3397 ;; Look for a handler in case default-directory is a remote file name.
3398 (let ((handler
3399 (find-file-name-handler (directory-file-name default-directory)
3400 'shell-command)))
3401 (if handler
3402 (funcall handler 'shell-command command output-buffer error-buffer)
3403 (if (and output-buffer
3404 (not (or (bufferp output-buffer) (stringp output-buffer))))
3405 ;; Output goes in current buffer.
3406 (let ((error-file
3407 (if error-buffer
3408 (make-temp-file
3409 (expand-file-name "scor"
3410 (or small-temporary-file-directory
3411 temporary-file-directory)))
3412 nil)))
3413 (barf-if-buffer-read-only)
3414 (push-mark nil t)
3415 ;; We do not use -f for csh; we will not support broken use of
3416 ;; .cshrcs. Even the BSD csh manual says to use
3417 ;; "if ($?prompt) exit" before things which are not useful
3418 ;; non-interactively. Besides, if someone wants their other
3419 ;; aliases for shell commands then they can still have them.
3420 (call-process shell-file-name nil
3421 (if error-file
3422 (list t error-file)
3424 nil shell-command-switch command)
3425 (when (and error-file (file-exists-p error-file))
3426 (if (< 0 (nth 7 (file-attributes error-file)))
3427 (with-current-buffer (get-buffer-create error-buffer)
3428 (let ((pos-from-end (- (point-max) (point))))
3429 (or (bobp)
3430 (insert "\f\n"))
3431 ;; Do no formatting while reading error file,
3432 ;; because that can run a shell command, and we
3433 ;; don't want that to cause an infinite recursion.
3434 (format-insert-file error-file nil)
3435 ;; Put point after the inserted errors.
3436 (goto-char (- (point-max) pos-from-end)))
3437 (display-buffer (current-buffer))))
3438 (delete-file error-file))
3439 ;; This is like exchange-point-and-mark, but doesn't
3440 ;; activate the mark. It is cleaner to avoid activation,
3441 ;; even though the command loop would deactivate the mark
3442 ;; because we inserted text.
3443 (goto-char (prog1 (mark t)
3444 (set-marker (mark-marker) (point)
3445 (current-buffer)))))
3446 ;; Output goes in a separate buffer.
3447 ;; Preserve the match data in case called from a program.
3448 ;; FIXME: It'd be ridiculous for an Elisp function to call
3449 ;; shell-command and assume that it won't mess the match-data!
3450 (save-match-data
3451 (if (string-match "[ \t]*&[ \t]*\\'" command)
3452 ;; Command ending with ampersand means asynchronous.
3453 (let ((buffer (get-buffer-create
3454 (or output-buffer "*Async Shell Command*")))
3455 (directory default-directory)
3456 proc)
3457 ;; Remove the ampersand.
3458 (setq command (substring command 0 (match-beginning 0)))
3459 ;; Ask the user what to do with already running process.
3460 (setq proc (get-buffer-process buffer))
3461 (when proc
3462 (cond
3463 ((eq async-shell-command-buffer 'confirm-kill-process)
3464 ;; If will kill a process, query first.
3465 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3466 (kill-process proc)
3467 (error "Shell command in progress")))
3468 ((eq async-shell-command-buffer 'confirm-new-buffer)
3469 ;; If will create a new buffer, query first.
3470 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3471 (setq buffer (generate-new-buffer
3472 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3473 output-buffer "*Async Shell Command*")))
3474 (error "Shell command in progress")))
3475 ((eq async-shell-command-buffer 'new-buffer)
3476 ;; It will create a new buffer.
3477 (setq buffer (generate-new-buffer
3478 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3479 output-buffer "*Async Shell Command*"))))
3480 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3481 ;; If will rename the buffer, query first.
3482 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3483 (progn
3484 (with-current-buffer buffer
3485 (rename-uniquely))
3486 (setq buffer (get-buffer-create
3487 (or output-buffer "*Async Shell Command*"))))
3488 (error "Shell command in progress")))
3489 ((eq async-shell-command-buffer 'rename-buffer)
3490 ;; It will rename the buffer.
3491 (with-current-buffer buffer
3492 (rename-uniquely))
3493 (setq buffer (get-buffer-create
3494 (or output-buffer "*Async Shell Command*"))))))
3495 (with-current-buffer buffer
3496 (display-buffer buffer '(nil (allow-no-window . t)))
3497 (shell-command--save-pos-or-erase)
3498 (setq default-directory directory)
3499 (setq proc (start-process "Shell" buffer shell-file-name
3500 shell-command-switch command))
3501 (setq mode-line-process '(":%s"))
3502 (require 'shell) (shell-mode)
3503 (set-process-sentinel proc 'shell-command-sentinel)
3504 ;; Use the comint filter for proper handling of carriage motion
3505 ;; (see `comint-inhibit-carriage-motion'),.
3506 (set-process-filter proc 'comint-output-filter)
3508 ;; Otherwise, command is executed synchronously.
3509 (shell-command-on-region (point) (point) command
3510 output-buffer nil error-buffer)))))))
3512 (defun display-message-or-buffer (message &optional buffer-name action frame)
3513 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3514 MESSAGE may be either a string or a buffer.
3516 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3517 for maximum height of the echo area, as defined by `max-mini-window-height'
3518 if `resize-mini-windows' is non-nil.
3520 Returns either the string shown in the echo area, or when a pop-up
3521 buffer is used, the window used to display it.
3523 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3524 name of the buffer used to display it in the case where a pop-up buffer
3525 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3526 string and it is displayed in the echo area, it is not specified whether
3527 the contents are inserted into the buffer anyway.
3529 Optional arguments ACTION and FRAME are as for `display-buffer',
3530 and are only used if a pop-up buffer is displayed."
3531 (cond ((and (stringp message) (not (string-match "\n" message)))
3532 ;; Trivial case where we can use the echo area
3533 (message "%s" message))
3534 ((and (stringp message)
3535 (= (string-match "\n" message) (1- (length message))))
3536 ;; Trivial case where we can just remove single trailing newline
3537 (message "%s" (substring message 0 (1- (length message)))))
3539 ;; General case
3540 (with-current-buffer
3541 (if (bufferp message)
3542 message
3543 (get-buffer-create (or buffer-name "*Message*")))
3545 (unless (bufferp message)
3546 (erase-buffer)
3547 (insert message))
3549 (let ((lines
3550 (if (= (buffer-size) 0)
3552 (count-screen-lines nil nil nil (minibuffer-window)))))
3553 (cond ((= lines 0))
3554 ((and (or (<= lines 1)
3555 (<= lines
3556 (if resize-mini-windows
3557 (cond ((floatp max-mini-window-height)
3558 (* (frame-height)
3559 max-mini-window-height))
3560 ((integerp max-mini-window-height)
3561 max-mini-window-height)
3564 1)))
3565 ;; Don't use the echo area if the output buffer is
3566 ;; already displayed in the selected frame.
3567 (not (get-buffer-window (current-buffer))))
3568 ;; Echo area
3569 (goto-char (point-max))
3570 (when (bolp)
3571 (backward-char 1))
3572 (message "%s" (buffer-substring (point-min) (point))))
3574 ;; Buffer
3575 (goto-char (point-min))
3576 (display-buffer (current-buffer) action frame))))))))
3579 ;; We have a sentinel to prevent insertion of a termination message
3580 ;; in the buffer itself, and to set the point in the buffer when
3581 ;; `shell-command-dont-erase-buffer' is non-nil.
3582 (defun shell-command-sentinel (process signal)
3583 (when (memq (process-status process) '(exit signal))
3584 (shell-command--set-point-after-cmd (process-buffer process))
3585 (message "%s: %s."
3586 (car (cdr (cdr (process-command process))))
3587 (substring signal 0 -1))))
3589 (defun shell-command-on-region (start end command
3590 &optional output-buffer replace
3591 error-buffer display-error-buffer
3592 region-noncontiguous-p)
3593 "Execute string COMMAND in inferior shell with region as input.
3594 Normally display output (if any) in temp buffer `*Shell Command Output*';
3595 Prefix arg means replace the region with it. Return the exit code of
3596 COMMAND.
3598 To specify a coding system for converting non-ASCII characters
3599 in the input and output to the shell command, use \\[universal-coding-system-argument]
3600 before this command. By default, the input (from the current buffer)
3601 is encoded using coding-system specified by `process-coding-system-alist',
3602 falling back to `default-process-coding-system' if no match for COMMAND
3603 is found in `process-coding-system-alist'.
3605 Noninteractive callers can specify coding systems by binding
3606 `coding-system-for-read' and `coding-system-for-write'.
3608 If the command generates output, the output may be displayed
3609 in the echo area or in a buffer.
3610 If the output is short enough to display in the echo area
3611 \(determined by the variable `max-mini-window-height' if
3612 `resize-mini-windows' is non-nil), it is shown there.
3613 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3614 The output is available in that buffer in both cases.
3616 If there is output and an error, a message about the error
3617 appears at the end of the output.
3619 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3620 command's output. If the value is a buffer or buffer name,
3621 erase that buffer and insert the output there; a non-nil value of
3622 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3623 If the value is nil, use the buffer `*Shell Command Output*'.
3624 Any other non-nil value means to insert the output in the
3625 current buffer after START.
3627 Optional fifth arg REPLACE, if non-nil, means to insert the
3628 output in place of text from START to END, putting point and mark
3629 around it.
3631 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3632 or buffer name to which to direct the command's standard error
3633 output. If nil, error output is mingled with regular output.
3634 When called interactively, `shell-command-default-error-buffer'
3635 is used for ERROR-BUFFER.
3637 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3638 display the error buffer if there were any errors. When called
3639 interactively, this is t."
3640 (interactive (let (string)
3641 (unless (mark)
3642 (user-error "The mark is not set now, so there is no region"))
3643 ;; Do this before calling region-beginning
3644 ;; and region-end, in case subprocess output
3645 ;; relocates them while we are in the minibuffer.
3646 (setq string (read-shell-command "Shell command on region: "))
3647 ;; call-interactively recognizes region-beginning and
3648 ;; region-end specially, leaving them in the history.
3649 (list (region-beginning) (region-end)
3650 string
3651 current-prefix-arg
3652 current-prefix-arg
3653 shell-command-default-error-buffer
3655 (region-noncontiguous-p))))
3656 (let ((error-file
3657 (if error-buffer
3658 (make-temp-file
3659 (expand-file-name "scor"
3660 (or small-temporary-file-directory
3661 temporary-file-directory)))
3662 nil))
3663 exit-status)
3664 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3665 (if region-noncontiguous-p
3666 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3667 output)
3668 (with-temp-buffer
3669 (insert input)
3670 (call-process-region (point-min) (point-max)
3671 shell-file-name t t
3672 nil shell-command-switch
3673 command)
3674 (setq output (split-string (buffer-string) "\n")))
3675 (goto-char start)
3676 (funcall region-insert-function output))
3677 (if (or replace
3678 (and output-buffer
3679 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3680 ;; Replace specified region with output from command.
3681 (let ((swap (and replace (< start end))))
3682 ;; Don't muck with mark unless REPLACE says we should.
3683 (goto-char start)
3684 (and replace (push-mark (point) 'nomsg))
3685 (setq exit-status
3686 (call-shell-region start end command replace
3687 (if error-file
3688 (list t error-file)
3689 t)))
3690 ;; It is rude to delete a buffer which the command is not using.
3691 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3692 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3693 ;; (kill-buffer shell-buffer)))
3694 ;; Don't muck with mark unless REPLACE says we should.
3695 (and replace swap (exchange-point-and-mark)))
3696 ;; No prefix argument: put the output in a temp buffer,
3697 ;; replacing its entire contents.
3698 (let ((buffer (get-buffer-create
3699 (or output-buffer "*Shell Command Output*"))))
3700 (unwind-protect
3701 (if (and (eq buffer (current-buffer))
3702 (or (not shell-command-dont-erase-buffer)
3703 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3704 (not (region-active-p)))))
3705 ;; If the input is the same buffer as the output,
3706 ;; delete everything but the specified region,
3707 ;; then replace that region with the output.
3708 (progn (setq buffer-read-only nil)
3709 (delete-region (max start end) (point-max))
3710 (delete-region (point-min) (min start end))
3711 (setq exit-status
3712 (call-process-region (point-min) (point-max)
3713 shell-file-name t
3714 (if error-file
3715 (list t error-file)
3717 nil shell-command-switch
3718 command)))
3719 ;; Clear the output buffer, then run the command with
3720 ;; output there.
3721 (let ((directory default-directory))
3722 (with-current-buffer buffer
3723 (if (not output-buffer)
3724 (setq default-directory directory))
3725 (shell-command--save-pos-or-erase)))
3726 (setq exit-status
3727 (call-shell-region start end command nil
3728 (if error-file
3729 (list buffer error-file)
3730 buffer))))
3731 ;; Report the output.
3732 (with-current-buffer buffer
3733 (setq mode-line-process
3734 (cond ((null exit-status)
3735 " - Error")
3736 ((stringp exit-status)
3737 (format " - Signal [%s]" exit-status))
3738 ((not (equal 0 exit-status))
3739 (format " - Exit [%d]" exit-status)))))
3740 (if (with-current-buffer buffer (> (point-max) (point-min)))
3741 ;; There's some output, display it
3742 (progn
3743 (display-message-or-buffer buffer)
3744 (shell-command--set-point-after-cmd buffer))
3745 ;; No output; error?
3746 (let ((output
3747 (if (and error-file
3748 (< 0 (nth 7 (file-attributes error-file))))
3749 (format "some error output%s"
3750 (if shell-command-default-error-buffer
3751 (format " to the \"%s\" buffer"
3752 shell-command-default-error-buffer)
3753 ""))
3754 "no output")))
3755 (cond ((null exit-status)
3756 (message "(Shell command failed with error)"))
3757 ((equal 0 exit-status)
3758 (message "(Shell command succeeded with %s)"
3759 output))
3760 ((stringp exit-status)
3761 (message "(Shell command killed by signal %s)"
3762 exit-status))
3764 (message "(Shell command failed with code %d and %s)"
3765 exit-status output))))
3766 ;; Don't kill: there might be useful info in the undo-log.
3767 ;; (kill-buffer buffer)
3768 )))))
3770 (when (and error-file (file-exists-p error-file))
3771 (if (< 0 (nth 7 (file-attributes error-file)))
3772 (with-current-buffer (get-buffer-create error-buffer)
3773 (let ((pos-from-end (- (point-max) (point))))
3774 (or (bobp)
3775 (insert "\f\n"))
3776 ;; Do no formatting while reading error file,
3777 ;; because that can run a shell command, and we
3778 ;; don't want that to cause an infinite recursion.
3779 (format-insert-file error-file nil)
3780 ;; Put point after the inserted errors.
3781 (goto-char (- (point-max) pos-from-end)))
3782 (and display-error-buffer
3783 (display-buffer (current-buffer)))))
3784 (delete-file error-file))
3785 exit-status))
3787 (defun shell-command-to-string (command)
3788 "Execute shell command COMMAND and return its output as a string."
3789 (with-output-to-string
3790 (with-current-buffer
3791 standard-output
3792 (process-file shell-file-name nil t nil shell-command-switch command))))
3794 (defun process-file (program &optional infile buffer display &rest args)
3795 "Process files synchronously in a separate process.
3796 Similar to `call-process', but may invoke a file handler based on
3797 `default-directory'. The current working directory of the
3798 subprocess is `default-directory'.
3800 File names in INFILE and BUFFER are handled normally, but file
3801 names in ARGS should be relative to `default-directory', as they
3802 are passed to the process verbatim. (This is a difference to
3803 `call-process' which does not support file handlers for INFILE
3804 and BUFFER.)
3806 Some file handlers might not support all variants, for example
3807 they might behave as if DISPLAY was nil, regardless of the actual
3808 value passed."
3809 (let ((fh (find-file-name-handler default-directory 'process-file))
3810 lc stderr-file)
3811 (unwind-protect
3812 (if fh (apply fh 'process-file program infile buffer display args)
3813 (when infile (setq lc (file-local-copy infile)))
3814 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3815 (make-temp-file "emacs")))
3816 (prog1
3817 (apply 'call-process program
3818 (or lc infile)
3819 (if stderr-file (list (car buffer) stderr-file) buffer)
3820 display args)
3821 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3822 (when stderr-file (delete-file stderr-file))
3823 (when lc (delete-file lc)))))
3825 (defvar process-file-side-effects t
3826 "Whether a call of `process-file' changes remote files.
3828 By default, this variable is always set to t, meaning that a
3829 call of `process-file' could potentially change any file on a
3830 remote host. When set to nil, a file handler could optimize
3831 its behavior with respect to remote file attribute caching.
3833 You should only ever change this variable with a let-binding;
3834 never with `setq'.")
3836 (defun start-file-process (name buffer program &rest program-args)
3837 "Start a program in a subprocess. Return the process object for it.
3839 Similar to `start-process', but may invoke a file handler based on
3840 `default-directory'. See Info node `(elisp)Magic File Names'.
3842 This handler ought to run PROGRAM, perhaps on the local host,
3843 perhaps on a remote host that corresponds to `default-directory'.
3844 In the latter case, the local part of `default-directory' becomes
3845 the working directory of the process.
3847 PROGRAM and PROGRAM-ARGS might be file names. They are not
3848 objects of file handler invocation. File handlers might not
3849 support pty association, if PROGRAM is nil."
3850 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3851 (if fh (apply fh 'start-file-process name buffer program program-args)
3852 (apply 'start-process name buffer program program-args))))
3854 ;;;; Process menu
3856 (defvar tabulated-list-format)
3857 (defvar tabulated-list-entries)
3858 (defvar tabulated-list-sort-key)
3859 (declare-function tabulated-list-init-header "tabulated-list" ())
3860 (declare-function tabulated-list-print "tabulated-list"
3861 (&optional remember-pos update))
3863 (defvar process-menu-query-only nil)
3865 (defvar process-menu-mode-map
3866 (let ((map (make-sparse-keymap)))
3867 (define-key map [?d] 'process-menu-delete-process)
3868 map))
3870 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3871 "Major mode for listing the processes called by Emacs."
3872 (setq tabulated-list-format [("Process" 15 t)
3873 ("PID" 7 t)
3874 ("Status" 7 t)
3875 ("Buffer" 15 t)
3876 ("TTY" 12 t)
3877 ("Command" 0 t)])
3878 (make-local-variable 'process-menu-query-only)
3879 (setq tabulated-list-sort-key (cons "Process" nil))
3880 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3881 (tabulated-list-init-header))
3883 (defun process-menu-delete-process ()
3884 "Kill process at point in a `list-processes' buffer."
3885 (interactive)
3886 (let ((pos (point)))
3887 (delete-process (tabulated-list-get-id))
3888 (revert-buffer)
3889 (goto-char (min pos (point-max)))
3890 (if (eobp)
3891 (forward-line -1)
3892 (beginning-of-line))))
3894 (defun list-processes--refresh ()
3895 "Recompute the list of processes for the Process List buffer.
3896 Also, delete any process that is exited or signaled."
3897 (setq tabulated-list-entries nil)
3898 (dolist (p (process-list))
3899 (cond ((memq (process-status p) '(exit signal closed))
3900 (delete-process p))
3901 ((or (not process-menu-query-only)
3902 (process-query-on-exit-flag p))
3903 (let* ((buf (process-buffer p))
3904 (type (process-type p))
3905 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
3906 (name (process-name p))
3907 (status (symbol-name (process-status p)))
3908 (buf-label (if (buffer-live-p buf)
3909 `(,(buffer-name buf)
3910 face link
3911 help-echo ,(format-message
3912 "Visit buffer `%s'"
3913 (buffer-name buf))
3914 follow-link t
3915 process-buffer ,buf
3916 action process-menu-visit-buffer)
3917 "--"))
3918 (tty (or (process-tty-name p) "--"))
3919 (cmd
3920 (if (memq type '(network serial))
3921 (let ((contact (process-contact p t)))
3922 (if (eq type 'network)
3923 (format "(%s %s)"
3924 (if (plist-get contact :type)
3925 "datagram"
3926 "network")
3927 (if (plist-get contact :server)
3928 (format "server on %s"
3930 (plist-get contact :host)
3931 (plist-get contact :local)))
3932 (format "connection to %s"
3933 (plist-get contact :host))))
3934 (format "(serial port %s%s)"
3935 (or (plist-get contact :port) "?")
3936 (let ((speed (plist-get contact :speed)))
3937 (if speed
3938 (format " at %s b/s" speed)
3939 "")))))
3940 (mapconcat 'identity (process-command p) " "))))
3941 (push (list p (vector name pid status buf-label tty cmd))
3942 tabulated-list-entries))))))
3944 (defun process-menu-visit-buffer (button)
3945 (display-buffer (button-get button 'process-buffer)))
3947 (defun list-processes (&optional query-only buffer)
3948 "Display a list of all processes that are Emacs sub-processes.
3949 If optional argument QUERY-ONLY is non-nil, only processes with
3950 the query-on-exit flag set are listed.
3951 Any process listed as exited or signaled is actually eliminated
3952 after the listing is made.
3953 Optional argument BUFFER specifies a buffer to use, instead of
3954 \"*Process List*\".
3955 The return value is always nil.
3957 This function lists only processes that were launched by Emacs. To
3958 see other processes running on the system, use `list-system-processes'."
3959 (interactive)
3960 (or (fboundp 'process-list)
3961 (error "Asynchronous subprocesses are not supported on this system"))
3962 (unless (bufferp buffer)
3963 (setq buffer (get-buffer-create "*Process List*")))
3964 (with-current-buffer buffer
3965 (process-menu-mode)
3966 (setq process-menu-query-only query-only)
3967 (list-processes--refresh)
3968 (tabulated-list-print))
3969 (display-buffer buffer)
3970 nil)
3972 ;;;; Prefix commands
3974 (setq prefix-command--needs-update nil)
3975 (setq prefix-command--last-echo nil)
3977 (defun internal-echo-keystrokes-prefix ()
3978 ;; BEWARE: Called directly from C code.
3979 ;; If the return value is non-nil, it means we are in the middle of
3980 ;; a command with prefix, such as a command invoked with prefix-arg.
3981 (if (not prefix-command--needs-update)
3982 prefix-command--last-echo
3983 (setq prefix-command--last-echo
3984 (let ((strs nil))
3985 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
3986 (lambda (fun) (push (funcall fun) strs)))
3987 (setq strs (delq nil strs))
3988 (when strs (mapconcat #'identity strs " "))))))
3990 (defvar prefix-command-echo-keystrokes-functions nil
3991 "Abnormal hook which constructs the description of the current prefix state.
3992 Each function is called with no argument, should return a string or nil.")
3994 (defun prefix-command-update ()
3995 "Update state of prefix commands.
3996 Call it whenever you change the \"prefix command state\"."
3997 (setq prefix-command--needs-update t))
3999 (defvar prefix-command-preserve-state-hook nil
4000 "Normal hook run when a command needs to preserve the prefix.")
4002 (defun prefix-command-preserve-state ()
4003 "Pass the current prefix command state to the next command.
4004 Should be called by all prefix commands.
4005 Runs `prefix-command-preserve-state-hook'."
4006 (run-hooks 'prefix-command-preserve-state-hook)
4007 ;; If the current command is a prefix command, we don't want the next (real)
4008 ;; command to have `last-command' set to, say, `universal-argument'.
4009 (setq this-command last-command)
4010 (setq real-this-command real-last-command)
4011 (prefix-command-update))
4013 (defun reset-this-command-lengths ()
4014 (declare (obsolete prefix-command-preserve-state "25.1"))
4015 nil)
4017 ;;;;; The main prefix command.
4019 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4021 (add-hook 'prefix-command-echo-keystrokes-functions
4022 #'universal-argument--description)
4023 (defun universal-argument--description ()
4024 (when prefix-arg
4025 (concat "C-u"
4026 (pcase prefix-arg
4027 (`(-) " -")
4028 (`(,(and (pred integerp) n))
4029 (let ((str ""))
4030 (while (and (> n 4) (= (mod n 4) 0))
4031 (setq str (concat str " C-u"))
4032 (setq n (/ n 4)))
4033 (if (= n 4) str (format " %s" prefix-arg))))
4034 (_ (format " %s" prefix-arg))))))
4036 (add-hook 'prefix-command-preserve-state-hook
4037 #'universal-argument--preserve)
4038 (defun universal-argument--preserve ()
4039 (setq prefix-arg current-prefix-arg))
4041 (defvar universal-argument-map
4042 (let ((map (make-sparse-keymap))
4043 (universal-argument-minus
4044 ;; For backward compatibility, minus with no modifiers is an ordinary
4045 ;; command if digits have already been entered.
4046 `(menu-item "" negative-argument
4047 :filter ,(lambda (cmd)
4048 (if (integerp prefix-arg) nil cmd)))))
4049 (define-key map [switch-frame]
4050 (lambda (e) (interactive "e")
4051 (handle-switch-frame e) (universal-argument--mode)))
4052 (define-key map [?\C-u] 'universal-argument-more)
4053 (define-key map [?-] universal-argument-minus)
4054 (define-key map [?0] 'digit-argument)
4055 (define-key map [?1] 'digit-argument)
4056 (define-key map [?2] 'digit-argument)
4057 (define-key map [?3] 'digit-argument)
4058 (define-key map [?4] 'digit-argument)
4059 (define-key map [?5] 'digit-argument)
4060 (define-key map [?6] 'digit-argument)
4061 (define-key map [?7] 'digit-argument)
4062 (define-key map [?8] 'digit-argument)
4063 (define-key map [?9] 'digit-argument)
4064 (define-key map [kp-0] 'digit-argument)
4065 (define-key map [kp-1] 'digit-argument)
4066 (define-key map [kp-2] 'digit-argument)
4067 (define-key map [kp-3] 'digit-argument)
4068 (define-key map [kp-4] 'digit-argument)
4069 (define-key map [kp-5] 'digit-argument)
4070 (define-key map [kp-6] 'digit-argument)
4071 (define-key map [kp-7] 'digit-argument)
4072 (define-key map [kp-8] 'digit-argument)
4073 (define-key map [kp-9] 'digit-argument)
4074 (define-key map [kp-subtract] universal-argument-minus)
4075 map)
4076 "Keymap used while processing \\[universal-argument].")
4078 (defun universal-argument--mode ()
4079 (prefix-command-update)
4080 (set-transient-map universal-argument-map nil))
4082 (defun universal-argument ()
4083 "Begin a numeric argument for the following command.
4084 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4085 \\[universal-argument] following the digits or minus sign ends the argument.
4086 \\[universal-argument] without digits or minus sign provides 4 as argument.
4087 Repeating \\[universal-argument] without digits or minus sign
4088 multiplies the argument by 4 each time.
4089 For some commands, just \\[universal-argument] by itself serves as a flag
4090 which is different in effect from any particular numeric argument.
4091 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4092 (interactive)
4093 (prefix-command-preserve-state)
4094 (setq prefix-arg (list 4))
4095 (universal-argument--mode))
4097 (defun universal-argument-more (arg)
4098 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4099 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4100 (interactive "P")
4101 (prefix-command-preserve-state)
4102 (setq prefix-arg (if (consp arg)
4103 (list (* 4 (car arg)))
4104 (if (eq arg '-)
4105 (list -4)
4106 arg)))
4107 (when (consp prefix-arg) (universal-argument--mode)))
4109 (defun negative-argument (arg)
4110 "Begin a negative numeric argument for the next command.
4111 \\[universal-argument] following digits or minus sign ends the argument."
4112 (interactive "P")
4113 (prefix-command-preserve-state)
4114 (setq prefix-arg (cond ((integerp arg) (- arg))
4115 ((eq arg '-) nil)
4116 (t '-)))
4117 (universal-argument--mode))
4119 (defun digit-argument (arg)
4120 "Part of the numeric argument for the next command.
4121 \\[universal-argument] following digits or minus sign ends the argument."
4122 (interactive "P")
4123 (prefix-command-preserve-state)
4124 (let* ((char (if (integerp last-command-event)
4125 last-command-event
4126 (get last-command-event 'ascii-character)))
4127 (digit (- (logand char ?\177) ?0)))
4128 (setq prefix-arg (cond ((integerp arg)
4129 (+ (* arg 10)
4130 (if (< arg 0) (- digit) digit)))
4131 ((eq arg '-)
4132 ;; Treat -0 as just -, so that -01 will work.
4133 (if (zerop digit) '- (- digit)))
4135 digit))))
4136 (universal-argument--mode))
4139 (defvar filter-buffer-substring-functions nil
4140 "This variable is a wrapper hook around `buffer-substring--filter'.
4141 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4142 (make-obsolete-variable 'filter-buffer-substring-functions
4143 'filter-buffer-substring-function "24.4")
4145 (defvar filter-buffer-substring-function #'buffer-substring--filter
4146 "Function to perform the filtering in `filter-buffer-substring'.
4147 The function is called with the same 3 arguments (BEG END DELETE)
4148 that `filter-buffer-substring' received. It should return the
4149 buffer substring between BEG and END, after filtering. If DELETE is
4150 non-nil, it should delete the text between BEG and END from the buffer.")
4152 (defvar buffer-substring-filters nil
4153 "List of filter functions for `buffer-substring--filter'.
4154 Each function must accept a single argument, a string, and return a string.
4155 The buffer substring is passed to the first function in the list,
4156 and the return value of each function is passed to the next.
4157 As a special convention, point is set to the start of the buffer text
4158 being operated on (i.e., the first argument of `buffer-substring--filter')
4159 before these functions are called.")
4160 (make-obsolete-variable 'buffer-substring-filters
4161 'filter-buffer-substring-function "24.1")
4163 (defun filter-buffer-substring (beg end &optional delete)
4164 "Return the buffer substring between BEG and END, after filtering.
4165 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4167 This calls the function that `filter-buffer-substring-function' specifies
4168 \(passing the same three arguments that it received) to do the work,
4169 and returns whatever it does. The default function does no filtering,
4170 unless a hook has been set.
4172 Use `filter-buffer-substring' instead of `buffer-substring',
4173 `buffer-substring-no-properties', or `delete-and-extract-region' when
4174 you want to allow filtering to take place. For example, major or minor
4175 modes can use `filter-buffer-substring-function' to extract characters
4176 that are special to a buffer, and should not be copied into other buffers."
4177 (funcall filter-buffer-substring-function beg end delete))
4179 (defun buffer-substring--filter (beg end &optional delete)
4180 "Default function to use for `filter-buffer-substring-function'.
4181 Its arguments and return value are as specified for `filter-buffer-substring'.
4182 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4183 \(see `with-wrapper-hook' for details about wrapper hooks),
4184 and the abnormal hook `buffer-substring-filters'.
4185 No filtering is done unless a hook says to."
4186 (subr--with-wrapper-hook-no-warnings
4187 filter-buffer-substring-functions (beg end delete)
4188 (cond
4189 ((or delete buffer-substring-filters)
4190 (save-excursion
4191 (goto-char beg)
4192 (let ((string (if delete (delete-and-extract-region beg end)
4193 (buffer-substring beg end))))
4194 (dolist (filter buffer-substring-filters)
4195 (setq string (funcall filter string)))
4196 string)))
4198 (buffer-substring beg end)))))
4201 ;;;; Window system cut and paste hooks.
4203 (defvar interprogram-cut-function #'gui-select-text
4204 "Function to call to make a killed region available to other programs.
4205 Most window systems provide a facility for cutting and pasting
4206 text between different programs, such as the clipboard on X and
4207 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4209 This variable holds a function that Emacs calls whenever text is
4210 put in the kill ring, to make the new kill available to other
4211 programs. The function takes one argument, TEXT, which is a
4212 string containing the text which should be made available.")
4214 (defvar interprogram-paste-function #'gui-selection-value
4215 "Function to call to get text cut from other programs.
4216 Most window systems provide a facility for cutting and pasting
4217 text between different programs, such as the clipboard on X and
4218 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4220 This variable holds a function that Emacs calls to obtain text
4221 that other programs have provided for pasting. The function is
4222 called with no arguments. If no other program has provided text
4223 to paste, the function should return nil (in which case the
4224 caller, usually `current-kill', should use the top of the Emacs
4225 kill ring). If another program has provided text to paste, the
4226 function should return that text as a string (in which case the
4227 caller should put this string in the kill ring as the latest
4228 kill).
4230 The function may also return a list of strings if the window
4231 system supports multiple selections. The first string will be
4232 used as the pasted text, but the other will be placed in the kill
4233 ring for easy access via `yank-pop'.
4235 Note that the function should return a string only if a program
4236 other than Emacs has provided a string for pasting; if Emacs
4237 provided the most recent string, the function should return nil.
4238 If it is difficult to tell whether Emacs or some other program
4239 provided the current string, it is probably good enough to return
4240 nil if the string is equal (according to `string=') to the last
4241 text Emacs provided.")
4245 ;;;; The kill ring data structure.
4247 (defvar kill-ring nil
4248 "List of killed text sequences.
4249 Since the kill ring is supposed to interact nicely with cut-and-paste
4250 facilities offered by window systems, use of this variable should
4251 interact nicely with `interprogram-cut-function' and
4252 `interprogram-paste-function'. The functions `kill-new',
4253 `kill-append', and `current-kill' are supposed to implement this
4254 interaction; you may want to use them instead of manipulating the kill
4255 ring directly.")
4257 (defcustom kill-ring-max 60
4258 "Maximum length of kill ring before oldest elements are thrown away."
4259 :type 'integer
4260 :group 'killing)
4262 (defvar kill-ring-yank-pointer nil
4263 "The tail of the kill ring whose car is the last thing yanked.")
4265 (defcustom save-interprogram-paste-before-kill nil
4266 "Save clipboard strings into kill ring before replacing them.
4267 When one selects something in another program to paste it into Emacs,
4268 but kills something in Emacs before actually pasting it,
4269 this selection is gone unless this variable is non-nil,
4270 in which case the other program's selection is saved in the `kill-ring'
4271 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4272 :type 'boolean
4273 :group 'killing
4274 :version "23.2")
4276 (defcustom kill-do-not-save-duplicates nil
4277 "Do not add a new string to `kill-ring' if it duplicates the last one.
4278 The comparison is done using `equal-including-properties'."
4279 :type 'boolean
4280 :group 'killing
4281 :version "23.2")
4283 (defun kill-new (string &optional replace)
4284 "Make STRING the latest kill in the kill ring.
4285 Set `kill-ring-yank-pointer' to point to it.
4286 If `interprogram-cut-function' is non-nil, apply it to STRING.
4287 Optional second argument REPLACE non-nil means that STRING will replace
4288 the front of the kill ring, rather than being added to the list.
4290 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4291 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4292 STRING.
4294 When the yank handler has a non-nil PARAM element, the original STRING
4295 argument is not used by `insert-for-yank'. However, since Lisp code
4296 may access and use elements from the kill ring directly, the STRING
4297 argument should still be a \"useful\" string for such uses."
4298 (unless (and kill-do-not-save-duplicates
4299 ;; Due to text properties such as 'yank-handler that
4300 ;; can alter the contents to yank, comparison using
4301 ;; `equal' is unsafe.
4302 (equal-including-properties string (car kill-ring)))
4303 (if (fboundp 'menu-bar-update-yank-menu)
4304 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4305 (when save-interprogram-paste-before-kill
4306 (let ((interprogram-paste (and interprogram-paste-function
4307 (funcall interprogram-paste-function))))
4308 (when interprogram-paste
4309 (dolist (s (if (listp interprogram-paste)
4310 (nreverse interprogram-paste)
4311 (list interprogram-paste)))
4312 (unless (and kill-do-not-save-duplicates
4313 (equal-including-properties s (car kill-ring)))
4314 (push s kill-ring))))))
4315 (unless (and kill-do-not-save-duplicates
4316 (equal-including-properties string (car kill-ring)))
4317 (if (and replace kill-ring)
4318 (setcar kill-ring string)
4319 (push string kill-ring)
4320 (if (> (length kill-ring) kill-ring-max)
4321 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4322 (setq kill-ring-yank-pointer kill-ring)
4323 (if interprogram-cut-function
4324 (funcall interprogram-cut-function string)))
4326 ;; It has been argued that this should work similar to `self-insert-command'
4327 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4328 (defcustom kill-append-merge-undo nil
4329 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4330 :type 'boolean
4331 :group 'killing
4332 :version "25.1")
4334 (defun kill-append (string before-p)
4335 "Append STRING to the end of the latest kill in the kill ring.
4336 If BEFORE-P is non-nil, prepend STRING to the kill.
4337 Also removes the last undo boundary in the current buffer,
4338 depending on `kill-append-merge-undo'.
4339 If `interprogram-cut-function' is set, pass the resulting kill to it."
4340 (let* ((cur (car kill-ring)))
4341 (kill-new (if before-p (concat string cur) (concat cur string))
4342 (or (= (length cur) 0)
4343 (equal nil (get-text-property 0 'yank-handler cur))))
4344 (when (and kill-append-merge-undo (not buffer-read-only))
4345 (let ((prev buffer-undo-list)
4346 (next (cdr buffer-undo-list)))
4347 ;; find the next undo boundary
4348 (while (car next)
4349 (pop next)
4350 (pop prev))
4351 ;; remove this undo boundary
4352 (when prev
4353 (setcdr prev (cdr next)))))))
4355 (defcustom yank-pop-change-selection nil
4356 "Whether rotating the kill ring changes the window system selection.
4357 If non-nil, whenever the kill ring is rotated (usually via the
4358 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4359 to copy the new kill to the window system selection."
4360 :type 'boolean
4361 :group 'killing
4362 :version "23.1")
4364 (defun current-kill (n &optional do-not-move)
4365 "Rotate the yanking point by N places, and then return that kill.
4366 If N is zero and `interprogram-paste-function' is set to a
4367 function that returns a string or a list of strings, and if that
4368 function doesn't return nil, then that string (or list) is added
4369 to the front of the kill ring and the string (or first string in
4370 the list) is returned as the latest kill.
4372 If N is not zero, and if `yank-pop-change-selection' is
4373 non-nil, use `interprogram-cut-function' to transfer the
4374 kill at the new yank point into the window system selection.
4376 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4377 move the yanking point; just return the Nth kill forward."
4379 (let ((interprogram-paste (and (= n 0)
4380 interprogram-paste-function
4381 (funcall interprogram-paste-function))))
4382 (if interprogram-paste
4383 (progn
4384 ;; Disable the interprogram cut function when we add the new
4385 ;; text to the kill ring, so Emacs doesn't try to own the
4386 ;; selection, with identical text.
4387 (let ((interprogram-cut-function nil))
4388 (if (listp interprogram-paste)
4389 (mapc 'kill-new (nreverse interprogram-paste))
4390 (kill-new interprogram-paste)))
4391 (car kill-ring))
4392 (or kill-ring (error "Kill ring is empty"))
4393 (let ((ARGth-kill-element
4394 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4395 (length kill-ring))
4396 kill-ring)))
4397 (unless do-not-move
4398 (setq kill-ring-yank-pointer ARGth-kill-element)
4399 (when (and yank-pop-change-selection
4400 (> n 0)
4401 interprogram-cut-function)
4402 (funcall interprogram-cut-function (car ARGth-kill-element))))
4403 (car ARGth-kill-element)))))
4407 ;;;; Commands for manipulating the kill ring.
4409 (defcustom kill-read-only-ok nil
4410 "Non-nil means don't signal an error for killing read-only text."
4411 :type 'boolean
4412 :group 'killing)
4414 (defun kill-region (beg end &optional region)
4415 "Kill (\"cut\") text between point and mark.
4416 This deletes the text from the buffer and saves it in the kill ring.
4417 The command \\[yank] can retrieve it from there.
4418 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4420 If you want to append the killed region to the last killed text,
4421 use \\[append-next-kill] before \\[kill-region].
4423 Any command that calls this function is a \"kill command\".
4424 If the previous command was also a kill command,
4425 the text killed this time appends to the text killed last time
4426 to make one entry in the kill ring.
4428 The killed text is filtered by `filter-buffer-substring' before it is
4429 saved in the kill ring, so the actual saved text might be different
4430 from what was killed.
4432 If the buffer is read-only, Emacs will beep and refrain from deleting
4433 the text, but put the text in the kill ring anyway. This means that
4434 you can use the killing commands to copy text from a read-only buffer.
4436 Lisp programs should use this function for killing text.
4437 (To delete text, use `delete-region'.)
4438 Supply two arguments, character positions BEG and END indicating the
4439 stretch of text to be killed. If the optional argument REGION is
4440 non-nil, the function ignores BEG and END, and kills the current
4441 region instead."
4442 ;; Pass mark first, then point, because the order matters when
4443 ;; calling `kill-append'.
4444 (interactive (list (mark) (point) 'region))
4445 (unless (and beg end)
4446 (user-error "The mark is not set now, so there is no region"))
4447 (condition-case nil
4448 (let ((string (if region
4449 (funcall region-extract-function 'delete)
4450 (filter-buffer-substring beg end 'delete))))
4451 (when string ;STRING is nil if BEG = END
4452 ;; Add that string to the kill ring, one way or another.
4453 (if (eq last-command 'kill-region)
4454 (kill-append string (< end beg))
4455 (kill-new string)))
4456 (when (or string (eq last-command 'kill-region))
4457 (setq this-command 'kill-region))
4458 (setq deactivate-mark t)
4459 nil)
4460 ((buffer-read-only text-read-only)
4461 ;; The code above failed because the buffer, or some of the characters
4462 ;; in the region, are read-only.
4463 ;; We should beep, in case the user just isn't aware of this.
4464 ;; However, there's no harm in putting
4465 ;; the region's text in the kill ring, anyway.
4466 (copy-region-as-kill beg end region)
4467 ;; Set this-command now, so it will be set even if we get an error.
4468 (setq this-command 'kill-region)
4469 ;; This should barf, if appropriate, and give us the correct error.
4470 (if kill-read-only-ok
4471 (progn (message "Read only text copied to kill ring") nil)
4472 ;; Signal an error if the buffer is read-only.
4473 (barf-if-buffer-read-only)
4474 ;; If the buffer isn't read-only, the text is.
4475 (signal 'text-read-only (list (current-buffer)))))))
4477 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4478 ;; to get two copies of the text when the user accidentally types M-w and
4479 ;; then corrects it with the intended C-w.
4480 (defun copy-region-as-kill (beg end &optional region)
4481 "Save the region as if killed, but don't kill it.
4482 In Transient Mark mode, deactivate the mark.
4483 If `interprogram-cut-function' is non-nil, also save the text for a window
4484 system cut and paste.
4486 The copied text is filtered by `filter-buffer-substring' before it is
4487 saved in the kill ring, so the actual saved text might be different
4488 from what was in the buffer.
4490 When called from Lisp, save in the kill ring the stretch of text
4491 between BEG and END, unless the optional argument REGION is
4492 non-nil, in which case ignore BEG and END, and save the current
4493 region instead.
4495 This command's old key binding has been given to `kill-ring-save'."
4496 ;; Pass mark first, then point, because the order matters when
4497 ;; calling `kill-append'.
4498 (interactive (list (mark) (point)
4499 (prefix-numeric-value current-prefix-arg)))
4500 (let ((str (if region
4501 (funcall region-extract-function nil)
4502 (filter-buffer-substring beg end))))
4503 (if (eq last-command 'kill-region)
4504 (kill-append str (< end beg))
4505 (kill-new str)))
4506 (setq deactivate-mark t)
4507 nil)
4509 (defun kill-ring-save (beg end &optional region)
4510 "Save the region as if killed, but don't kill it.
4511 In Transient Mark mode, deactivate the mark.
4512 If `interprogram-cut-function' is non-nil, also save the text for a window
4513 system cut and paste.
4515 If you want to append the killed line to the last killed text,
4516 use \\[append-next-kill] before \\[kill-ring-save].
4518 The copied text is filtered by `filter-buffer-substring' before it is
4519 saved in the kill ring, so the actual saved text might be different
4520 from what was in the buffer.
4522 When called from Lisp, save in the kill ring the stretch of text
4523 between BEG and END, unless the optional argument REGION is
4524 non-nil, in which case ignore BEG and END, and save the current
4525 region instead.
4527 This command is similar to `copy-region-as-kill', except that it gives
4528 visual feedback indicating the extent of the region being copied."
4529 ;; Pass mark first, then point, because the order matters when
4530 ;; calling `kill-append'.
4531 (interactive (list (mark) (point)
4532 (prefix-numeric-value current-prefix-arg)))
4533 (copy-region-as-kill beg end region)
4534 ;; This use of called-interactively-p is correct because the code it
4535 ;; controls just gives the user visual feedback.
4536 (if (called-interactively-p 'interactive)
4537 (indicate-copied-region)))
4539 (defun indicate-copied-region (&optional message-len)
4540 "Indicate that the region text has been copied interactively.
4541 If the mark is visible in the selected window, blink the cursor
4542 between point and mark if there is currently no active region
4543 highlighting.
4545 If the mark lies outside the selected window, display an
4546 informative message containing a sample of the copied text. The
4547 optional argument MESSAGE-LEN, if non-nil, specifies the length
4548 of this sample text; it defaults to 40."
4549 (let ((mark (mark t))
4550 (point (point))
4551 ;; Inhibit quitting so we can make a quit here
4552 ;; look like a C-g typed as a command.
4553 (inhibit-quit t))
4554 (if (pos-visible-in-window-p mark (selected-window))
4555 ;; Swap point-and-mark quickly so as to show the region that
4556 ;; was selected. Don't do it if the region is highlighted.
4557 (unless (and (region-active-p)
4558 (face-background 'region))
4559 ;; Swap point and mark.
4560 (set-marker (mark-marker) (point) (current-buffer))
4561 (goto-char mark)
4562 (sit-for blink-matching-delay)
4563 ;; Swap back.
4564 (set-marker (mark-marker) mark (current-buffer))
4565 (goto-char point)
4566 ;; If user quit, deactivate the mark
4567 ;; as C-g would as a command.
4568 (and quit-flag (region-active-p)
4569 (deactivate-mark)))
4570 (let ((len (min (abs (- mark point))
4571 (or message-len 40))))
4572 (if (< point mark)
4573 ;; Don't say "killed"; that is misleading.
4574 (message "Saved text until \"%s\""
4575 (buffer-substring-no-properties (- mark len) mark))
4576 (message "Saved text from \"%s\""
4577 (buffer-substring-no-properties mark (+ mark len))))))))
4579 (defun append-next-kill (&optional interactive)
4580 "Cause following command, if it kills, to add to previous kill.
4581 If the next command kills forward from point, the kill is
4582 appended to the previous killed text. If the command kills
4583 backward, the kill is prepended. Kill commands that act on the
4584 region, such as `kill-region', are regarded as killing forward if
4585 point is after mark, and killing backward if point is before
4586 mark.
4588 If the next command is not a kill command, `append-next-kill' has
4589 no effect.
4591 The argument is used for internal purposes; do not supply one."
4592 (interactive "p")
4593 ;; We don't use (interactive-p), since that breaks kbd macros.
4594 (if interactive
4595 (progn
4596 (setq this-command 'kill-region)
4597 (message "If the next command is a kill, it will append"))
4598 (setq last-command 'kill-region)))
4600 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4601 "Character set that matches bidirectional formatting control characters.")
4603 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4604 "Character set that matches any character except bidirectional controls.")
4606 (defun squeeze-bidi-context-1 (from to category replacement)
4607 "A subroutine of `squeeze-bidi-context'.
4608 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4609 (let ((pt (copy-marker from))
4610 (limit (copy-marker to))
4611 (old-pt 0)
4612 lim1)
4613 (setq lim1 limit)
4614 (goto-char pt)
4615 (while (< pt limit)
4616 (if (> pt old-pt)
4617 (move-marker lim1
4618 (save-excursion
4619 ;; L and R categories include embedding and
4620 ;; override controls, but we don't want to
4621 ;; replace them, because that might change
4622 ;; the visual order. Likewise with PDF and
4623 ;; isolate controls.
4624 (+ pt (skip-chars-forward
4625 bidi-directional-non-controls-chars
4626 limit)))))
4627 ;; Replace any run of non-RTL characters by a single LRM.
4628 (if (null (re-search-forward category lim1 t))
4629 ;; No more characters of CATEGORY, we are done.
4630 (setq pt limit)
4631 (replace-match replacement nil t)
4632 (move-marker pt (point)))
4633 (setq old-pt pt)
4634 ;; Skip directional controls, if any.
4635 (move-marker
4636 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4638 (defun squeeze-bidi-context (from to)
4639 "Replace characters between FROM and TO while keeping bidi context.
4641 This function replaces the region of text with as few characters
4642 as possible, while preserving the effect that region will have on
4643 bidirectional display before and after the region."
4644 (let ((start (set-marker (make-marker)
4645 (if (> from 0) from (+ (point-max) from))))
4646 (end (set-marker (make-marker) to))
4647 ;; This is for when they copy text with read-only text
4648 ;; properties.
4649 (inhibit-read-only t))
4650 (if (null (marker-position end))
4651 (setq end (point-max-marker)))
4652 ;; Replace each run of non-RTL characters with a single LRM.
4653 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4654 ;; Replace each run of non-LTR characters with a single RLM. Note
4655 ;; that the \cR category includes both the Arabic Letter (AL) and
4656 ;; R characters; here we ignore the distinction between them,
4657 ;; because that distinction only affects Arabic Number (AN)
4658 ;; characters, which are weak and don't affect the reordering.
4659 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4661 (defun line-substring-with-bidi-context (start end &optional no-properties)
4662 "Return buffer text between START and END with its bidi context.
4664 START and END are assumed to belong to the same physical line
4665 of buffer text. This function prepends and appends to the text
4666 between START and END bidi control characters that preserve the
4667 visual order of that text when it is inserted at some other place."
4668 (if (or (< start (point-min))
4669 (> end (point-max)))
4670 (signal 'args-out-of-range (list (current-buffer) start end)))
4671 (let ((buf (current-buffer))
4672 substr para-dir from to)
4673 (save-excursion
4674 (goto-char start)
4675 (setq para-dir (current-bidi-paragraph-direction))
4676 (setq from (line-beginning-position)
4677 to (line-end-position))
4678 (goto-char from)
4679 ;; If we don't have any mixed directional characters in the
4680 ;; entire line, we can just copy the substring without adding
4681 ;; any context.
4682 (if (or (looking-at-p "\\CR*$")
4683 (looking-at-p "\\CL*$"))
4684 (setq substr (if no-properties
4685 (buffer-substring-no-properties start end)
4686 (buffer-substring start end)))
4687 (setq substr
4688 (with-temp-buffer
4689 (if no-properties
4690 (insert-buffer-substring-no-properties buf from to)
4691 (insert-buffer-substring buf from to))
4692 (squeeze-bidi-context 1 (1+ (- start from)))
4693 (squeeze-bidi-context (- end to) nil)
4694 (buffer-substring 1 (point-max)))))
4696 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4697 ;; (1) force the string to have the same base embedding
4698 ;; direction as the paragraph direction at the source, no matter
4699 ;; what is the paragraph direction at destination; and (2) avoid
4700 ;; affecting the visual order of the surrounding text at
4701 ;; destination if there are characters of different
4702 ;; directionality there.
4703 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4704 substr "\x2069"))))
4706 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4707 "Return portion of current buffer between START and END with bidi context.
4709 This function works similar to `buffer-substring', but it prepends and
4710 appends to the text bidi directional control characters necessary to
4711 preserve the visual appearance of the text if it is inserted at another
4712 place. This is useful when the buffer substring includes bidirectional
4713 text and control characters that cause non-trivial reordering on display.
4714 If copied verbatim, such text can have a very different visual appearance,
4715 and can also change the visual appearance of the surrounding text at the
4716 destination of the copy.
4718 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4719 the text properties."
4720 (let (line-end substr)
4721 (if (or (< start (point-min))
4722 (> end (point-max)))
4723 (signal 'args-out-of-range (list (current-buffer) start end)))
4724 (save-excursion
4725 (goto-char start)
4726 (setq line-end (min end (line-end-position)))
4727 (while (< start end)
4728 (setq substr
4729 (concat substr
4730 (if substr "\n" "")
4731 (line-substring-with-bidi-context start line-end
4732 no-properties)))
4733 (forward-line 1)
4734 (setq start (point))
4735 (setq line-end (min end (line-end-position))))
4736 substr)))
4738 ;; Yanking.
4740 (defcustom yank-handled-properties
4741 '((font-lock-face . yank-handle-font-lock-face-property)
4742 (category . yank-handle-category-property))
4743 "List of special text property handling conditions for yanking.
4744 Each element should have the form (PROP . FUN), where PROP is a
4745 property symbol and FUN is a function. When the `yank' command
4746 inserts text into the buffer, it scans the inserted text for
4747 stretches of text that have `eq' values of the text property
4748 PROP; for each such stretch of text, FUN is called with three
4749 arguments: the property's value in that text, and the start and
4750 end positions of the text.
4752 This is done prior to removing the properties specified by
4753 `yank-excluded-properties'."
4754 :group 'killing
4755 :type '(repeat (cons (symbol :tag "property symbol")
4756 function))
4757 :version "24.3")
4759 ;; This is actually used in subr.el but defcustom does not work there.
4760 (defcustom yank-excluded-properties
4761 '(category field follow-link fontified font-lock-face help-echo
4762 intangible invisible keymap local-map mouse-face read-only
4763 yank-handler)
4764 "Text properties to discard when yanking.
4765 The value should be a list of text properties to discard or t,
4766 which means to discard all text properties.
4768 See also `yank-handled-properties'."
4769 :type '(choice (const :tag "All" t) (repeat symbol))
4770 :group 'killing
4771 :version "24.3")
4773 (defvar yank-window-start nil)
4774 (defvar yank-undo-function nil
4775 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4776 Function is called with two parameters, START and END corresponding to
4777 the value of the mark and point; it is guaranteed that START <= END.
4778 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4780 (defun yank-pop (&optional arg)
4781 "Replace just-yanked stretch of killed text with a different stretch.
4782 This command is allowed only immediately after a `yank' or a `yank-pop'.
4783 At such a time, the region contains a stretch of reinserted
4784 previously-killed text. `yank-pop' deletes that text and inserts in its
4785 place a different stretch of killed text.
4787 With no argument, the previous kill is inserted.
4788 With argument N, insert the Nth previous kill.
4789 If N is negative, this is a more recent kill.
4791 The sequence of kills wraps around, so that after the oldest one
4792 comes the newest one.
4794 This command honors the `yank-handled-properties' and
4795 `yank-excluded-properties' variables, and the `yank-handler' text
4796 property, in the way that `yank' does."
4797 (interactive "*p")
4798 (if (not (eq last-command 'yank))
4799 (user-error "Previous command was not a yank"))
4800 (setq this-command 'yank)
4801 (unless arg (setq arg 1))
4802 (let ((inhibit-read-only t)
4803 (before (< (point) (mark t))))
4804 (if before
4805 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4806 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4807 (setq yank-undo-function nil)
4808 (set-marker (mark-marker) (point) (current-buffer))
4809 (insert-for-yank (current-kill arg))
4810 ;; Set the window start back where it was in the yank command,
4811 ;; if possible.
4812 (set-window-start (selected-window) yank-window-start t)
4813 (if before
4814 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4815 ;; It is cleaner to avoid activation, even though the command
4816 ;; loop would deactivate the mark because we inserted text.
4817 (goto-char (prog1 (mark t)
4818 (set-marker (mark-marker) (point) (current-buffer))))))
4819 nil)
4821 (defun yank (&optional arg)
4822 "Reinsert (\"paste\") the last stretch of killed text.
4823 More precisely, reinsert the most recent kill, which is the
4824 stretch of killed text most recently killed OR yanked. Put point
4825 at the end, and set mark at the beginning without activating it.
4826 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4827 With argument N, reinsert the Nth most recent kill.
4829 This command honors the `yank-handled-properties' and
4830 `yank-excluded-properties' variables, and the `yank-handler' text
4831 property, as described below.
4833 Properties listed in `yank-handled-properties' are processed,
4834 then those listed in `yank-excluded-properties' are discarded.
4836 If STRING has a non-nil `yank-handler' property anywhere, the
4837 normal insert behavior is altered, and instead, for each contiguous
4838 segment of STRING that has a given value of the `yank-handler'
4839 property, that value is used as follows:
4841 The value of a `yank-handler' property must be a list of one to four
4842 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4843 FUNCTION, if non-nil, should be a function of one argument (the
4844 object to insert); FUNCTION is called instead of `insert'.
4845 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4846 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4847 PARAM may be a list of strings to insert as a rectangle). If PARAM
4848 is nil, then the current segment of STRING is used.
4849 If NOEXCLUDE is present and non-nil, the normal removal of
4850 `yank-excluded-properties' is not performed; instead FUNCTION is
4851 responsible for the removal. This may be necessary if FUNCTION
4852 adjusts point before or after inserting the object.
4853 UNDO, if present and non-nil, should be a function to be called
4854 by `yank-pop' to undo the insertion of the current PARAM. It is
4855 given two arguments, the start and end of the region. FUNCTION
4856 may set `yank-undo-function' to override UNDO.
4858 See also the command `yank-pop' (\\[yank-pop])."
4859 (interactive "*P")
4860 (setq yank-window-start (window-start))
4861 ;; If we don't get all the way thru, make last-command indicate that
4862 ;; for the following command.
4863 (setq this-command t)
4864 (push-mark (point))
4865 (insert-for-yank (current-kill (cond
4866 ((listp arg) 0)
4867 ((eq arg '-) -2)
4868 (t (1- arg)))))
4869 (if (consp arg)
4870 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4871 ;; It is cleaner to avoid activation, even though the command
4872 ;; loop would deactivate the mark because we inserted text.
4873 (goto-char (prog1 (mark t)
4874 (set-marker (mark-marker) (point) (current-buffer)))))
4875 ;; If we do get all the way thru, make this-command indicate that.
4876 (if (eq this-command t)
4877 (setq this-command 'yank))
4878 nil)
4880 (defun rotate-yank-pointer (arg)
4881 "Rotate the yanking point in the kill ring.
4882 With ARG, rotate that many kills forward (or backward, if negative)."
4883 (interactive "p")
4884 (current-kill arg))
4886 ;; Some kill commands.
4888 ;; Internal subroutine of delete-char
4889 (defun kill-forward-chars (arg)
4890 (if (listp arg) (setq arg (car arg)))
4891 (if (eq arg '-) (setq arg -1))
4892 (kill-region (point) (+ (point) arg)))
4894 ;; Internal subroutine of backward-delete-char
4895 (defun kill-backward-chars (arg)
4896 (if (listp arg) (setq arg (car arg)))
4897 (if (eq arg '-) (setq arg -1))
4898 (kill-region (point) (- (point) arg)))
4900 (defcustom backward-delete-char-untabify-method 'untabify
4901 "The method for untabifying when deleting backward.
4902 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4903 `hungry' -- delete all whitespace, both tabs and spaces;
4904 `all' -- delete all whitespace, including tabs, spaces and newlines;
4905 nil -- just delete one character."
4906 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4907 :version "20.3"
4908 :group 'killing)
4910 (defun backward-delete-char-untabify (arg &optional killp)
4911 "Delete characters backward, changing tabs into spaces.
4912 The exact behavior depends on `backward-delete-char-untabify-method'.
4913 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4914 Interactively, ARG is the prefix arg (default 1)
4915 and KILLP is t if a prefix arg was specified."
4916 (interactive "*p\nP")
4917 (when (eq backward-delete-char-untabify-method 'untabify)
4918 (let ((count arg))
4919 (save-excursion
4920 (while (and (> count 0) (not (bobp)))
4921 (if (= (preceding-char) ?\t)
4922 (let ((col (current-column)))
4923 (forward-char -1)
4924 (setq col (- col (current-column)))
4925 (insert-char ?\s col)
4926 (delete-char 1)))
4927 (forward-char -1)
4928 (setq count (1- count))))))
4929 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4930 ((eq backward-delete-char-untabify-method 'all)
4931 " \t\n\r")))
4932 (n (if skip
4933 (let* ((oldpt (point))
4934 (wh (- oldpt (save-excursion
4935 (skip-chars-backward skip)
4936 (constrain-to-field nil oldpt)))))
4937 (+ arg (if (zerop wh) 0 (1- wh))))
4938 arg)))
4939 ;; Avoid warning about delete-backward-char
4940 (with-no-warnings (delete-backward-char n killp))))
4942 (defun zap-to-char (arg char)
4943 "Kill up to and including ARGth occurrence of CHAR.
4944 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4945 Goes backward if ARG is negative; error if CHAR not found."
4946 (interactive (list (prefix-numeric-value current-prefix-arg)
4947 (read-char "Zap to char: " t)))
4948 ;; Avoid "obsolete" warnings for translation-table-for-input.
4949 (with-no-warnings
4950 (if (char-table-p translation-table-for-input)
4951 (setq char (or (aref translation-table-for-input char) char))))
4952 (kill-region (point) (progn
4953 (search-forward (char-to-string char) nil nil arg)
4954 (point))))
4956 ;; kill-line and its subroutines.
4958 (defcustom kill-whole-line nil
4959 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4960 :type 'boolean
4961 :group 'killing)
4963 (defun kill-line (&optional arg)
4964 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4965 With prefix argument ARG, kill that many lines from point.
4966 Negative arguments kill lines backward.
4967 With zero argument, kills the text before point on the current line.
4969 When calling from a program, nil means \"no arg\",
4970 a number counts as a prefix arg.
4972 To kill a whole line, when point is not at the beginning, type \
4973 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4975 If `show-trailing-whitespace' is non-nil, this command will just
4976 kill the rest of the current line, even if there are no nonblanks
4977 there.
4979 If option `kill-whole-line' is non-nil, then this command kills the whole line
4980 including its terminating newline, when used at the beginning of a line
4981 with no argument. As a consequence, you can always kill a whole line
4982 by typing \\[move-beginning-of-line] \\[kill-line].
4984 If you want to append the killed line to the last killed text,
4985 use \\[append-next-kill] before \\[kill-line].
4987 If the buffer is read-only, Emacs will beep and refrain from deleting
4988 the line, but put the line in the kill ring anyway. This means that
4989 you can use this command to copy text from a read-only buffer.
4990 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4991 even beep.)"
4992 (interactive "P")
4993 (kill-region (point)
4994 ;; It is better to move point to the other end of the kill
4995 ;; before killing. That way, in a read-only buffer, point
4996 ;; moves across the text that is copied to the kill ring.
4997 ;; The choice has no effect on undo now that undo records
4998 ;; the value of point from before the command was run.
4999 (progn
5000 (if arg
5001 (forward-visible-line (prefix-numeric-value arg))
5002 (if (eobp)
5003 (signal 'end-of-buffer nil))
5004 (let ((end
5005 (save-excursion
5006 (end-of-visible-line) (point))))
5007 (if (or (save-excursion
5008 ;; If trailing whitespace is visible,
5009 ;; don't treat it as nothing.
5010 (unless show-trailing-whitespace
5011 (skip-chars-forward " \t" end))
5012 (= (point) end))
5013 (and kill-whole-line (bolp)))
5014 (forward-visible-line 1)
5015 (goto-char end))))
5016 (point))))
5018 (defun kill-whole-line (&optional arg)
5019 "Kill current line.
5020 With prefix ARG, kill that many lines starting from the current line.
5021 If ARG is negative, kill backward. Also kill the preceding newline.
5022 \(This is meant to make \\[repeat] work well with negative arguments.)
5023 If ARG is zero, kill current line but exclude the trailing newline."
5024 (interactive "p")
5025 (or arg (setq arg 1))
5026 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5027 (signal 'end-of-buffer nil))
5028 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5029 (signal 'beginning-of-buffer nil))
5030 (unless (eq last-command 'kill-region)
5031 (kill-new "")
5032 (setq last-command 'kill-region))
5033 (cond ((zerop arg)
5034 ;; We need to kill in two steps, because the previous command
5035 ;; could have been a kill command, in which case the text
5036 ;; before point needs to be prepended to the current kill
5037 ;; ring entry and the text after point appended. Also, we
5038 ;; need to use save-excursion to avoid copying the same text
5039 ;; twice to the kill ring in read-only buffers.
5040 (save-excursion
5041 (kill-region (point) (progn (forward-visible-line 0) (point))))
5042 (kill-region (point) (progn (end-of-visible-line) (point))))
5043 ((< arg 0)
5044 (save-excursion
5045 (kill-region (point) (progn (end-of-visible-line) (point))))
5046 (kill-region (point)
5047 (progn (forward-visible-line (1+ arg))
5048 (unless (bobp) (backward-char))
5049 (point))))
5051 (save-excursion
5052 (kill-region (point) (progn (forward-visible-line 0) (point))))
5053 (kill-region (point)
5054 (progn (forward-visible-line arg) (point))))))
5056 (defun forward-visible-line (arg)
5057 "Move forward by ARG lines, ignoring currently invisible newlines only.
5058 If ARG is negative, move backward -ARG lines.
5059 If ARG is zero, move to the beginning of the current line."
5060 (condition-case nil
5061 (if (> arg 0)
5062 (progn
5063 (while (> arg 0)
5064 (or (zerop (forward-line 1))
5065 (signal 'end-of-buffer nil))
5066 ;; If the newline we just skipped is invisible,
5067 ;; don't count it.
5068 (let ((prop
5069 (get-char-property (1- (point)) 'invisible)))
5070 (if (if (eq buffer-invisibility-spec t)
5071 prop
5072 (or (memq prop buffer-invisibility-spec)
5073 (assq prop buffer-invisibility-spec)))
5074 (setq arg (1+ arg))))
5075 (setq arg (1- arg)))
5076 ;; If invisible text follows, and it is a number of complete lines,
5077 ;; skip it.
5078 (let ((opoint (point)))
5079 (while (and (not (eobp))
5080 (let ((prop
5081 (get-char-property (point) 'invisible)))
5082 (if (eq buffer-invisibility-spec t)
5083 prop
5084 (or (memq prop buffer-invisibility-spec)
5085 (assq prop buffer-invisibility-spec)))))
5086 (goto-char
5087 (if (get-text-property (point) 'invisible)
5088 (or (next-single-property-change (point) 'invisible)
5089 (point-max))
5090 (next-overlay-change (point)))))
5091 (unless (bolp)
5092 (goto-char opoint))))
5093 (let ((first t))
5094 (while (or first (<= arg 0))
5095 (if first
5096 (beginning-of-line)
5097 (or (zerop (forward-line -1))
5098 (signal 'beginning-of-buffer nil)))
5099 ;; If the newline we just moved to is invisible,
5100 ;; don't count it.
5101 (unless (bobp)
5102 (let ((prop
5103 (get-char-property (1- (point)) 'invisible)))
5104 (unless (if (eq buffer-invisibility-spec t)
5105 prop
5106 (or (memq prop buffer-invisibility-spec)
5107 (assq prop buffer-invisibility-spec)))
5108 (setq arg (1+ arg)))))
5109 (setq first nil))
5110 ;; If invisible text follows, and it is a number of complete lines,
5111 ;; skip it.
5112 (let ((opoint (point)))
5113 (while (and (not (bobp))
5114 (let ((prop
5115 (get-char-property (1- (point)) 'invisible)))
5116 (if (eq buffer-invisibility-spec t)
5117 prop
5118 (or (memq prop buffer-invisibility-spec)
5119 (assq prop buffer-invisibility-spec)))))
5120 (goto-char
5121 (if (get-text-property (1- (point)) 'invisible)
5122 (or (previous-single-property-change (point) 'invisible)
5123 (point-min))
5124 (previous-overlay-change (point)))))
5125 (unless (bolp)
5126 (goto-char opoint)))))
5127 ((beginning-of-buffer end-of-buffer)
5128 nil)))
5130 (defun end-of-visible-line ()
5131 "Move to end of current visible line."
5132 (end-of-line)
5133 ;; If the following character is currently invisible,
5134 ;; skip all characters with that same `invisible' property value,
5135 ;; then find the next newline.
5136 (while (and (not (eobp))
5137 (save-excursion
5138 (skip-chars-forward "^\n")
5139 (let ((prop
5140 (get-char-property (point) 'invisible)))
5141 (if (eq buffer-invisibility-spec t)
5142 prop
5143 (or (memq prop buffer-invisibility-spec)
5144 (assq prop buffer-invisibility-spec))))))
5145 (skip-chars-forward "^\n")
5146 (if (get-text-property (point) 'invisible)
5147 (goto-char (or (next-single-property-change (point) 'invisible)
5148 (point-max)))
5149 (goto-char (next-overlay-change (point))))
5150 (end-of-line)))
5152 (defun insert-buffer (buffer)
5153 "Insert after point the contents of BUFFER.
5154 Puts mark after the inserted text.
5155 BUFFER may be a buffer or a buffer name."
5156 (declare (interactive-only insert-buffer-substring))
5157 (interactive
5158 (list
5159 (progn
5160 (barf-if-buffer-read-only)
5161 (read-buffer "Insert buffer: "
5162 (if (eq (selected-window) (next-window))
5163 (other-buffer (current-buffer))
5164 (window-buffer (next-window)))
5165 t))))
5166 (push-mark
5167 (save-excursion
5168 (insert-buffer-substring (get-buffer buffer))
5169 (point)))
5170 nil)
5172 (defun append-to-buffer (buffer start end)
5173 "Append to specified buffer the text of the region.
5174 It is inserted into that buffer before its point.
5176 When calling from a program, give three arguments:
5177 BUFFER (or buffer name), START and END.
5178 START and END specify the portion of the current buffer to be copied."
5179 (interactive
5180 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5181 (region-beginning) (region-end)))
5182 (let* ((oldbuf (current-buffer))
5183 (append-to (get-buffer-create buffer))
5184 (windows (get-buffer-window-list append-to t t))
5185 point)
5186 (save-excursion
5187 (with-current-buffer append-to
5188 (setq point (point))
5189 (barf-if-buffer-read-only)
5190 (insert-buffer-substring oldbuf start end)
5191 (dolist (window windows)
5192 (when (= (window-point window) point)
5193 (set-window-point window (point))))))))
5195 (defun prepend-to-buffer (buffer start end)
5196 "Prepend to specified buffer the text of the region.
5197 It is inserted into that buffer after its point.
5199 When calling from a program, give three arguments:
5200 BUFFER (or buffer name), START and END.
5201 START and END specify the portion of the current buffer to be copied."
5202 (interactive "BPrepend to buffer: \nr")
5203 (let ((oldbuf (current-buffer)))
5204 (with-current-buffer (get-buffer-create buffer)
5205 (barf-if-buffer-read-only)
5206 (save-excursion
5207 (insert-buffer-substring oldbuf start end)))))
5209 (defun copy-to-buffer (buffer start end)
5210 "Copy to specified buffer the text of the region.
5211 It is inserted into that buffer, replacing existing text there.
5213 When calling from a program, give three arguments:
5214 BUFFER (or buffer name), START and END.
5215 START and END specify the portion of the current buffer to be copied."
5216 (interactive "BCopy to buffer: \nr")
5217 (let ((oldbuf (current-buffer)))
5218 (with-current-buffer (get-buffer-create buffer)
5219 (barf-if-buffer-read-only)
5220 (erase-buffer)
5221 (save-excursion
5222 (insert-buffer-substring oldbuf start end)))))
5224 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5226 (defvar activate-mark-hook nil
5227 "Hook run when the mark becomes active.
5228 It is also run at the end of a command, if the mark is active and
5229 it is possible that the region may have changed.")
5231 (defvar deactivate-mark-hook nil
5232 "Hook run when the mark becomes inactive.")
5234 (defun mark (&optional force)
5235 "Return this buffer's mark value as integer, or nil if never set.
5237 In Transient Mark mode, this function signals an error if
5238 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5239 or the argument FORCE is non-nil, it disregards whether the mark
5240 is active, and returns an integer or nil in the usual way.
5242 If you are using this in an editing command, you are most likely making
5243 a mistake; see the documentation of `set-mark'."
5244 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5245 (marker-position (mark-marker))
5246 (signal 'mark-inactive nil)))
5248 ;; Behind display-selections-p.
5250 (defun deactivate-mark (&optional force)
5251 "Deactivate the mark.
5252 If Transient Mark mode is disabled, this function normally does
5253 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5255 Deactivating the mark sets `mark-active' to nil, updates the
5256 primary selection according to `select-active-regions', and runs
5257 `deactivate-mark-hook'.
5259 If Transient Mark mode was temporarily enabled, reset the value
5260 of the variable `transient-mark-mode'; if this causes Transient
5261 Mark mode to be disabled, don't change `mark-active' to nil or
5262 run `deactivate-mark-hook'."
5263 (when (or (region-active-p) force)
5264 (when (and (if (eq select-active-regions 'only)
5265 (eq (car-safe transient-mark-mode) 'only)
5266 select-active-regions)
5267 (region-active-p)
5268 (display-selections-p))
5269 ;; The var `saved-region-selection', if non-nil, is the text in
5270 ;; the region prior to the last command modifying the buffer.
5271 ;; Set the selection to that, or to the current region.
5272 (cond (saved-region-selection
5273 (if (gui-backend-selection-owner-p 'PRIMARY)
5274 (gui-set-selection 'PRIMARY saved-region-selection))
5275 (setq saved-region-selection nil))
5276 ;; If another program has acquired the selection, region
5277 ;; deactivation should not clobber it (Bug#11772).
5278 ((and (/= (region-beginning) (region-end))
5279 (or (gui-backend-selection-owner-p 'PRIMARY)
5280 (null (gui-backend-selection-exists-p 'PRIMARY))))
5281 (gui-set-selection 'PRIMARY
5282 (funcall region-extract-function nil)))))
5283 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5284 (cond
5285 ((eq (car-safe transient-mark-mode) 'only)
5286 (setq transient-mark-mode (cdr transient-mark-mode))
5287 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5288 (kill-local-variable 'transient-mark-mode)))
5289 ((eq transient-mark-mode 'lambda)
5290 (kill-local-variable 'transient-mark-mode)))
5291 (setq mark-active nil)
5292 (run-hooks 'deactivate-mark-hook)
5293 (redisplay--update-region-highlight (selected-window))))
5295 (defun activate-mark (&optional no-tmm)
5296 "Activate the mark.
5297 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5298 (when (mark t)
5299 (unless (region-active-p)
5300 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5301 (setq mark-active t)
5302 (unless (or transient-mark-mode no-tmm)
5303 (setq-local transient-mark-mode 'lambda))
5304 (run-hooks 'activate-mark-hook))))
5306 (defun set-mark (pos)
5307 "Set this buffer's mark to POS. Don't use this function!
5308 That is to say, don't use this function unless you want
5309 the user to see that the mark has moved, and you want the previous
5310 mark position to be lost.
5312 Normally, when a new mark is set, the old one should go on the stack.
5313 This is why most applications should use `push-mark', not `set-mark'.
5315 Novice Emacs Lisp programmers often try to use the mark for the wrong
5316 purposes. The mark saves a location for the user's convenience.
5317 Most editing commands should not alter the mark.
5318 To remember a location for internal use in the Lisp program,
5319 store it in a Lisp variable. Example:
5321 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5322 (if pos
5323 (progn
5324 (set-marker (mark-marker) pos (current-buffer))
5325 (activate-mark 'no-tmm))
5326 ;; Normally we never clear mark-active except in Transient Mark mode.
5327 ;; But when we actually clear out the mark value too, we must
5328 ;; clear mark-active in any mode.
5329 (deactivate-mark t)
5330 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5331 ;; it should never be nil if the mark is nil.
5332 (setq mark-active nil)
5333 (set-marker (mark-marker) nil)))
5335 (defun save-mark-and-excursion--save ()
5336 (cons
5337 (let ((mark (mark-marker)))
5338 (and (marker-position mark) (copy-marker mark)))
5339 mark-active))
5341 (defun save-mark-and-excursion--restore (saved-mark-info)
5342 (let ((saved-mark (car saved-mark-info))
5343 (omark (marker-position (mark-marker)))
5344 (nmark nil)
5345 (saved-mark-active (cdr saved-mark-info)))
5346 ;; Mark marker
5347 (if (null saved-mark)
5348 (set-marker (mark-marker) nil)
5349 (setf nmark (marker-position saved-mark))
5350 (set-marker (mark-marker) nmark)
5351 (set-marker saved-mark nil))
5352 ;; Mark active
5353 (let ((cur-mark-active mark-active))
5354 (setq mark-active saved-mark-active)
5355 ;; If mark is active now, and either was not active or was at a
5356 ;; different place, run the activate hook.
5357 (if saved-mark-active
5358 (when (or (not cur-mark-active)
5359 (not (eq omark nmark)))
5360 (run-hooks 'activate-mark-hook))
5361 ;; If mark has ceased to be active, run deactivate hook.
5362 (when cur-mark-active
5363 (run-hooks 'deactivate-mark-hook))))))
5365 (defmacro save-mark-and-excursion (&rest body)
5366 "Like `save-excursion', but also save and restore the mark state.
5367 This macro does what `save-excursion' did before Emacs 25.1."
5368 (declare (indent 0) (debug t))
5369 (let ((saved-marker-sym (make-symbol "saved-marker")))
5370 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5371 (unwind-protect
5372 (save-excursion ,@body)
5373 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5375 (defcustom use-empty-active-region nil
5376 "Whether \"region-aware\" commands should act on empty regions.
5377 If nil, region-aware commands treat the empty region as inactive.
5378 If non-nil, region-aware commands treat the region as active as
5379 long as the mark is active, even if the region is empty.
5381 Region-aware commands are those that act on the region if it is
5382 active and Transient Mark mode is enabled, and on the text near
5383 point otherwise."
5384 :type 'boolean
5385 :version "23.1"
5386 :group 'editing-basics)
5388 (defun use-region-p ()
5389 "Return t if the region is active and it is appropriate to act on it.
5390 This is used by commands that act specially on the region under
5391 Transient Mark mode.
5393 The return value is t if Transient Mark mode is enabled and the
5394 mark is active; furthermore, if `use-empty-active-region' is nil,
5395 the region must not be empty. Otherwise, the return value is nil.
5397 For some commands, it may be appropriate to ignore the value of
5398 `use-empty-active-region'; in that case, use `region-active-p'."
5399 (and (region-active-p)
5400 (or use-empty-active-region (> (region-end) (region-beginning)))))
5402 (defun region-active-p ()
5403 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5405 Some commands act specially on the region when Transient Mark
5406 mode is enabled. Usually, such commands should use
5407 `use-region-p' instead of this function, because `use-region-p'
5408 also checks the value of `use-empty-active-region'."
5409 (and transient-mark-mode mark-active
5410 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5411 ;; without the mark being set (e.g. bug#17324). We really should fix
5412 ;; that problem, but in the mean time, let's make sure we don't say the
5413 ;; region is active when there's no mark.
5414 (progn (cl-assert (mark)) t)))
5416 (defun region-bounds ()
5417 "Return the boundaries of the region as a list of (START . END) positions."
5418 (funcall region-extract-function 'bounds))
5420 (defun region-noncontiguous-p ()
5421 "Return non-nil if the region contains several pieces.
5422 An example is a rectangular region handled as a list of
5423 separate contiguous regions for each line."
5424 (> (length (region-bounds)) 1))
5426 (defvar redisplay-unhighlight-region-function
5427 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5429 (defvar redisplay-highlight-region-function
5430 (lambda (start end window rol)
5431 (if (not (overlayp rol))
5432 (let ((nrol (make-overlay start end)))
5433 (funcall redisplay-unhighlight-region-function rol)
5434 (overlay-put nrol 'window window)
5435 (overlay-put nrol 'face 'region)
5436 ;; Normal priority so that a large region doesn't hide all the
5437 ;; overlays within it, but high secondary priority so that if it
5438 ;; ends/starts in the middle of a small overlay, that small overlay
5439 ;; won't hide the region's boundaries.
5440 (overlay-put nrol 'priority '(nil . 100))
5441 nrol)
5442 (unless (and (eq (overlay-buffer rol) (current-buffer))
5443 (eq (overlay-start rol) start)
5444 (eq (overlay-end rol) end))
5445 (move-overlay rol start end (current-buffer)))
5446 rol)))
5448 (defun redisplay--update-region-highlight (window)
5449 (let ((rol (window-parameter window 'internal-region-overlay)))
5450 (if (not (and (region-active-p)
5451 (or highlight-nonselected-windows
5452 (eq window (selected-window))
5453 (and (window-minibuffer-p)
5454 (eq window (minibuffer-selected-window))))))
5455 (funcall redisplay-unhighlight-region-function rol)
5456 (let* ((pt (window-point window))
5457 (mark (mark))
5458 (start (min pt mark))
5459 (end (max pt mark))
5460 (new
5461 (funcall redisplay-highlight-region-function
5462 start end window rol)))
5463 (unless (equal new rol)
5464 (set-window-parameter window 'internal-region-overlay
5465 new))))))
5467 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5468 "Hook run just before redisplay.
5469 It is called in each window that is to be redisplayed. It takes one argument,
5470 which is the window that will be redisplayed. When run, the `current-buffer'
5471 is set to the buffer displayed in that window.")
5473 (defun redisplay--pre-redisplay-functions (windows)
5474 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5475 (if (null windows)
5476 (with-current-buffer (window-buffer (selected-window))
5477 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5478 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5479 (with-current-buffer (window-buffer win)
5480 (run-hook-with-args 'pre-redisplay-functions win))))))
5482 (add-function :before pre-redisplay-function
5483 #'redisplay--pre-redisplay-functions)
5486 (defvar-local mark-ring nil
5487 "The list of former marks of the current buffer, most recent first.")
5488 (put 'mark-ring 'permanent-local t)
5490 (defcustom mark-ring-max 16
5491 "Maximum size of mark ring. Start discarding off end if gets this big."
5492 :type 'integer
5493 :group 'editing-basics)
5495 (defvar global-mark-ring nil
5496 "The list of saved global marks, most recent first.")
5498 (defcustom global-mark-ring-max 16
5499 "Maximum size of global mark ring. \
5500 Start discarding off end if gets this big."
5501 :type 'integer
5502 :group 'editing-basics)
5504 (defun pop-to-mark-command ()
5505 "Jump to mark, and pop a new position for mark off the ring.
5506 \(Does not affect global mark ring)."
5507 (interactive)
5508 (if (null (mark t))
5509 (user-error "No mark set in this buffer")
5510 (if (= (point) (mark t))
5511 (message "Mark popped"))
5512 (goto-char (mark t))
5513 (pop-mark)))
5515 (defun push-mark-command (arg &optional nomsg)
5516 "Set mark at where point is.
5517 If no prefix ARG and mark is already set there, just activate it.
5518 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5519 (interactive "P")
5520 (let ((mark (mark t)))
5521 (if (or arg (null mark) (/= mark (point)))
5522 (push-mark nil nomsg t)
5523 (activate-mark 'no-tmm)
5524 (unless nomsg
5525 (message "Mark activated")))))
5527 (defcustom set-mark-command-repeat-pop nil
5528 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5529 That means that C-u \\[set-mark-command] \\[set-mark-command]
5530 will pop the mark twice, and
5531 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5532 will pop the mark three times.
5534 A value of nil means \\[set-mark-command]'s behavior does not change
5535 after C-u \\[set-mark-command]."
5536 :type 'boolean
5537 :group 'editing-basics)
5539 (defun set-mark-command (arg)
5540 "Set the mark where point is, and activate it; or jump to the mark.
5541 Setting the mark also alters the region, which is the text
5542 between point and mark; this is the closest equivalent in
5543 Emacs to what some editors call the \"selection\".
5545 With no prefix argument, set the mark at point, and push the
5546 old mark position on local mark ring. Also push the new mark on
5547 global mark ring, if the previous mark was set in another buffer.
5549 When Transient Mark Mode is off, immediately repeating this
5550 command activates `transient-mark-mode' temporarily.
5552 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5553 jump to the mark, and set the mark from
5554 position popped off the local mark ring (this does not affect the global
5555 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5556 mark ring (see `pop-global-mark').
5558 If `set-mark-command-repeat-pop' is non-nil, repeating
5559 the \\[set-mark-command] command with no prefix argument pops the next position
5560 off the local (or global) mark ring and jumps there.
5562 With \\[universal-argument] \\[universal-argument] as prefix
5563 argument, unconditionally set mark where point is, even if
5564 `set-mark-command-repeat-pop' is non-nil.
5566 Novice Emacs Lisp programmers often try to use the mark for the wrong
5567 purposes. See the documentation of `set-mark' for more information."
5568 (interactive "P")
5569 (cond ((eq transient-mark-mode 'lambda)
5570 (kill-local-variable 'transient-mark-mode))
5571 ((eq (car-safe transient-mark-mode) 'only)
5572 (deactivate-mark)))
5573 (cond
5574 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5575 (push-mark-command nil))
5576 ((not (eq this-command 'set-mark-command))
5577 (if arg
5578 (pop-to-mark-command)
5579 (push-mark-command t)))
5580 ((and set-mark-command-repeat-pop
5581 (eq last-command 'pop-global-mark)
5582 (not arg))
5583 (setq this-command 'pop-global-mark)
5584 (pop-global-mark))
5585 ((or (and set-mark-command-repeat-pop
5586 (eq last-command 'pop-to-mark-command))
5587 arg)
5588 (setq this-command 'pop-to-mark-command)
5589 (pop-to-mark-command))
5590 ((eq last-command 'set-mark-command)
5591 (if (region-active-p)
5592 (progn
5593 (deactivate-mark)
5594 (message "Mark deactivated"))
5595 (activate-mark)
5596 (message "Mark activated")))
5598 (push-mark-command nil))))
5600 (defun push-mark (&optional location nomsg activate)
5601 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5602 If the last global mark pushed was not in the current buffer,
5603 also push LOCATION on the global mark ring.
5604 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5606 Novice Emacs Lisp programmers often try to use the mark for the wrong
5607 purposes. See the documentation of `set-mark' for more information.
5609 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5610 (unless (null (mark t))
5611 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5612 (when (> (length mark-ring) mark-ring-max)
5613 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5614 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5615 (set-marker (mark-marker) (or location (point)) (current-buffer))
5616 ;; Now push the mark on the global mark ring.
5617 (if (and global-mark-ring
5618 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5619 ;; The last global mark pushed was in this same buffer.
5620 ;; Don't push another one.
5622 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5623 (when (> (length global-mark-ring) global-mark-ring-max)
5624 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5625 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5626 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5627 (message "Mark set"))
5628 (if (or activate (not transient-mark-mode))
5629 (set-mark (mark t)))
5630 nil)
5632 (defun pop-mark ()
5633 "Pop off mark ring into the buffer's actual mark.
5634 Does not set point. Does nothing if mark ring is empty."
5635 (when mark-ring
5636 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5637 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5638 (move-marker (car mark-ring) nil)
5639 (if (null (mark t)) (ding))
5640 (setq mark-ring (cdr mark-ring)))
5641 (deactivate-mark))
5643 (define-obsolete-function-alias
5644 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5645 (defun exchange-point-and-mark (&optional arg)
5646 "Put the mark where point is now, and point where the mark is now.
5647 This command works even when the mark is not active,
5648 and it reactivates the mark.
5650 If Transient Mark mode is on, a prefix ARG deactivates the mark
5651 if it is active, and otherwise avoids reactivating it. If
5652 Transient Mark mode is off, a prefix ARG enables Transient Mark
5653 mode temporarily."
5654 (interactive "P")
5655 (let ((omark (mark t))
5656 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5657 (if (null omark)
5658 (user-error "No mark set in this buffer"))
5659 (set-mark (point))
5660 (goto-char omark)
5661 (cond (temp-highlight
5662 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5663 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5664 (not (or arg (region-active-p))))
5665 (deactivate-mark))
5666 (t (activate-mark)))
5667 nil))
5669 (defcustom shift-select-mode t
5670 "When non-nil, shifted motion keys activate the mark momentarily.
5672 While the mark is activated in this way, any shift-translated point
5673 motion key extends the region, and if Transient Mark mode was off, it
5674 is temporarily turned on. Furthermore, the mark will be deactivated
5675 by any subsequent point motion key that was not shift-translated, or
5676 by any action that normally deactivates the mark in Transient Mark mode.
5678 See `this-command-keys-shift-translated' for the meaning of
5679 shift-translation."
5680 :type 'boolean
5681 :group 'editing-basics)
5683 (defun handle-shift-selection ()
5684 "Activate/deactivate mark depending on invocation thru shift translation.
5685 This function is called by `call-interactively' when a command
5686 with a `^' character in its `interactive' spec is invoked, before
5687 running the command itself.
5689 If `shift-select-mode' is enabled and the command was invoked
5690 through shift translation, set the mark and activate the region
5691 temporarily, unless it was already set in this way. See
5692 `this-command-keys-shift-translated' for the meaning of shift
5693 translation.
5695 Otherwise, if the region has been activated temporarily,
5696 deactivate it, and restore the variable `transient-mark-mode' to
5697 its earlier value."
5698 (cond ((and shift-select-mode this-command-keys-shift-translated)
5699 (unless (and mark-active
5700 (eq (car-safe transient-mark-mode) 'only))
5701 (setq-local transient-mark-mode
5702 (cons 'only
5703 (unless (eq transient-mark-mode 'lambda)
5704 transient-mark-mode)))
5705 (push-mark nil nil t)))
5706 ((eq (car-safe transient-mark-mode) 'only)
5707 (setq transient-mark-mode (cdr transient-mark-mode))
5708 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5709 (kill-local-variable 'transient-mark-mode))
5710 (deactivate-mark))))
5712 (define-minor-mode transient-mark-mode
5713 "Toggle Transient Mark mode.
5714 With a prefix argument ARG, enable Transient Mark mode if ARG is
5715 positive, and disable it otherwise. If called from Lisp, enable
5716 Transient Mark mode if ARG is omitted or nil.
5718 Transient Mark mode is a global minor mode. When enabled, the
5719 region is highlighted with the `region' face whenever the mark
5720 is active. The mark is \"deactivated\" by changing the buffer,
5721 and after certain other operations that set the mark but whose
5722 main purpose is something else--for example, incremental search,
5723 \\[beginning-of-buffer], and \\[end-of-buffer].
5725 You can also deactivate the mark by typing \\[keyboard-quit] or
5726 \\[keyboard-escape-quit].
5728 Many commands change their behavior when Transient Mark mode is
5729 in effect and the mark is active, by acting on the region instead
5730 of their usual default part of the buffer's text. Examples of
5731 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5732 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5733 To see the documentation of commands which are sensitive to the
5734 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5735 or \"mark.*active\" at the prompt."
5736 :global t
5737 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5738 :variable (default-value 'transient-mark-mode))
5740 (defvar widen-automatically t
5741 "Non-nil means it is ok for commands to call `widen' when they want to.
5742 Some commands will do this in order to go to positions outside
5743 the current accessible part of the buffer.
5745 If `widen-automatically' is nil, these commands will do something else
5746 as a fallback, and won't change the buffer bounds.")
5748 (defvar non-essential nil
5749 "Whether the currently executing code is performing an essential task.
5750 This variable should be non-nil only when running code which should not
5751 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5752 user for a password when we are simply scanning a set of files in the
5753 background or displaying possible completions before the user even asked
5754 for it.")
5756 (defun pop-global-mark ()
5757 "Pop off global mark ring and jump to the top location."
5758 (interactive)
5759 ;; Pop entries which refer to non-existent buffers.
5760 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5761 (setq global-mark-ring (cdr global-mark-ring)))
5762 (or global-mark-ring
5763 (error "No global mark set"))
5764 (let* ((marker (car global-mark-ring))
5765 (buffer (marker-buffer marker))
5766 (position (marker-position marker)))
5767 (setq global-mark-ring (nconc (cdr global-mark-ring)
5768 (list (car global-mark-ring))))
5769 (set-buffer buffer)
5770 (or (and (>= position (point-min))
5771 (<= position (point-max)))
5772 (if widen-automatically
5773 (widen)
5774 (error "Global mark position is outside accessible part of buffer")))
5775 (goto-char position)
5776 (switch-to-buffer buffer)))
5778 (defcustom next-line-add-newlines nil
5779 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5780 :type 'boolean
5781 :version "21.1"
5782 :group 'editing-basics)
5784 (defun next-line (&optional arg try-vscroll)
5785 "Move cursor vertically down ARG lines.
5786 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5787 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5788 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5789 function will not vscroll.
5791 ARG defaults to 1.
5793 If there is no character in the target line exactly under the current column,
5794 the cursor is positioned after the character in that line which spans this
5795 column, or at the end of the line if it is not long enough.
5796 If there is no line in the buffer after this one, behavior depends on the
5797 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5798 to create a line, and moves the cursor to that line. Otherwise it moves the
5799 cursor to the end of the buffer.
5801 If the variable `line-move-visual' is non-nil, this command moves
5802 by display lines. Otherwise, it moves by buffer lines, without
5803 taking variable-width characters or continued lines into account.
5804 See \\[next-logical-line] for a command that always moves by buffer lines.
5806 The command \\[set-goal-column] can be used to create
5807 a semipermanent goal column for this command.
5808 Then instead of trying to move exactly vertically (or as close as possible),
5809 this command moves to the specified goal column (or as close as possible).
5810 The goal column is stored in the variable `goal-column', which is nil
5811 when there is no goal column. Note that setting `goal-column'
5812 overrides `line-move-visual' and causes this command to move by buffer
5813 lines rather than by display lines."
5814 (declare (interactive-only forward-line))
5815 (interactive "^p\np")
5816 (or arg (setq arg 1))
5817 (if (and next-line-add-newlines (= arg 1))
5818 (if (save-excursion (end-of-line) (eobp))
5819 ;; When adding a newline, don't expand an abbrev.
5820 (let ((abbrev-mode nil))
5821 (end-of-line)
5822 (insert (if use-hard-newlines hard-newline "\n")))
5823 (line-move arg nil nil try-vscroll))
5824 (if (called-interactively-p 'interactive)
5825 (condition-case err
5826 (line-move arg nil nil try-vscroll)
5827 ((beginning-of-buffer end-of-buffer)
5828 (signal (car err) (cdr err))))
5829 (line-move arg nil nil try-vscroll)))
5830 nil)
5832 (defun previous-line (&optional arg try-vscroll)
5833 "Move cursor vertically up ARG lines.
5834 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5835 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5836 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5837 function will not vscroll.
5839 ARG defaults to 1.
5841 If there is no character in the target line exactly over the current column,
5842 the cursor is positioned after the character in that line which spans this
5843 column, or at the end of the line if it is not long enough.
5845 If the variable `line-move-visual' is non-nil, this command moves
5846 by display lines. Otherwise, it moves by buffer lines, without
5847 taking variable-width characters or continued lines into account.
5848 See \\[previous-logical-line] for a command that always moves by buffer lines.
5850 The command \\[set-goal-column] can be used to create
5851 a semipermanent goal column for this command.
5852 Then instead of trying to move exactly vertically (or as close as possible),
5853 this command moves to the specified goal column (or as close as possible).
5854 The goal column is stored in the variable `goal-column', which is nil
5855 when there is no goal column. Note that setting `goal-column'
5856 overrides `line-move-visual' and causes this command to move by buffer
5857 lines rather than by display lines."
5858 (declare (interactive-only
5859 "use `forward-line' with negative argument instead."))
5860 (interactive "^p\np")
5861 (or arg (setq arg 1))
5862 (if (called-interactively-p 'interactive)
5863 (condition-case err
5864 (line-move (- arg) nil nil try-vscroll)
5865 ((beginning-of-buffer end-of-buffer)
5866 (signal (car err) (cdr err))))
5867 (line-move (- arg) nil nil try-vscroll))
5868 nil)
5870 (defcustom track-eol nil
5871 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5872 This means moving to the end of each line moved onto.
5873 The beginning of a blank line does not count as the end of a line.
5874 This has no effect when the variable `line-move-visual' is non-nil."
5875 :type 'boolean
5876 :group 'editing-basics)
5878 (defcustom goal-column nil
5879 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5880 A non-nil setting overrides the variable `line-move-visual', which see."
5881 :type '(choice integer
5882 (const :tag "None" nil))
5883 :group 'editing-basics)
5884 (make-variable-buffer-local 'goal-column)
5886 (defvar temporary-goal-column 0
5887 "Current goal column for vertical motion.
5888 It is the column where point was at the start of the current run
5889 of vertical motion commands.
5891 When moving by visual lines via the function `line-move-visual', it is a cons
5892 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5893 divided by the default column width, and HSCROLL is the number of
5894 columns by which window is scrolled from left margin.
5896 When the `track-eol' feature is doing its job, the value is
5897 `most-positive-fixnum'.")
5899 (defcustom line-move-ignore-invisible t
5900 "Non-nil means commands that move by lines ignore invisible newlines.
5901 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5902 as if newlines that are invisible didn't exist, and count
5903 only visible newlines. Thus, moving across across 2 newlines
5904 one of which is invisible will be counted as a one-line move.
5905 Also, a non-nil value causes invisible text to be ignored when
5906 counting columns for the purposes of keeping point in the same
5907 column by \\[next-line] and \\[previous-line].
5909 Outline mode sets this."
5910 :type 'boolean
5911 :group 'editing-basics)
5913 (defcustom line-move-visual t
5914 "When non-nil, `line-move' moves point by visual lines.
5915 This movement is based on where the cursor is displayed on the
5916 screen, instead of relying on buffer contents alone. It takes
5917 into account variable-width characters and line continuation.
5918 If nil, `line-move' moves point by logical lines.
5919 A non-nil setting of `goal-column' overrides the value of this variable
5920 and forces movement by logical lines.
5921 A window that is horizontally scrolled also forces movement by logical
5922 lines."
5923 :type 'boolean
5924 :group 'editing-basics
5925 :version "23.1")
5927 ;; Only used if display-graphic-p.
5928 (declare-function font-info "font.c" (name &optional frame))
5930 (defun default-font-height ()
5931 "Return the height in pixels of the current buffer's default face font.
5933 If the default font is remapped (see `face-remapping-alist'), the
5934 function returns the height of the remapped face."
5935 (let ((default-font (face-font 'default)))
5936 (cond
5937 ((and (display-multi-font-p)
5938 ;; Avoid calling font-info if the frame's default font was
5939 ;; not changed since the frame was created. That's because
5940 ;; font-info is expensive for some fonts, see bug #14838.
5941 (not (string= (frame-parameter nil 'font) default-font)))
5942 (aref (font-info default-font) 3))
5943 (t (frame-char-height)))))
5945 (defun default-font-width ()
5946 "Return the width in pixels of the current buffer's default face font.
5948 If the default font is remapped (see `face-remapping-alist'), the
5949 function returns the width of the remapped face."
5950 (let ((default-font (face-font 'default)))
5951 (cond
5952 ((and (display-multi-font-p)
5953 ;; Avoid calling font-info if the frame's default font was
5954 ;; not changed since the frame was created. That's because
5955 ;; font-info is expensive for some fonts, see bug #14838.
5956 (not (string= (frame-parameter nil 'font) default-font)))
5957 (let* ((info (font-info (face-font 'default)))
5958 (width (aref info 11)))
5959 (if (> width 0)
5960 width
5961 (aref info 10))))
5962 (t (frame-char-width)))))
5964 (defun default-line-height ()
5965 "Return the pixel height of current buffer's default-face text line.
5967 The value includes `line-spacing', if any, defined for the buffer
5968 or the frame."
5969 (let ((dfh (default-font-height))
5970 (lsp (if (display-graphic-p)
5971 (or line-spacing
5972 (default-value 'line-spacing)
5973 (frame-parameter nil 'line-spacing)
5975 0)))
5976 (if (floatp lsp)
5977 (setq lsp (truncate (* (frame-char-height) lsp))))
5978 (+ dfh lsp)))
5980 (defun window-screen-lines ()
5981 "Return the number of screen lines in the text area of the selected window.
5983 This is different from `window-text-height' in that this function counts
5984 lines in units of the height of the font used by the default face displayed
5985 in the window, not in units of the frame's default font, and also accounts
5986 for `line-spacing', if any, defined for the window's buffer or frame.
5988 The value is a floating-point number."
5989 (let ((edges (window-inside-pixel-edges))
5990 (dlh (default-line-height)))
5991 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5993 ;; Returns non-nil if partial move was done.
5994 (defun line-move-partial (arg noerror &optional _to-end)
5995 (if (< arg 0)
5996 ;; Move backward (up).
5997 ;; If already vscrolled, reduce vscroll
5998 (let ((vs (window-vscroll nil t))
5999 (dlh (default-line-height)))
6000 (when (> vs dlh)
6001 (set-window-vscroll nil (- vs dlh) t)))
6003 ;; Move forward (down).
6004 (let* ((lh (window-line-height -1))
6005 (rowh (car lh))
6006 (vpos (nth 1 lh))
6007 (ypos (nth 2 lh))
6008 (rbot (nth 3 lh))
6009 (this-lh (window-line-height))
6010 (this-height (car this-lh))
6011 (this-ypos (nth 2 this-lh))
6012 (dlh (default-line-height))
6013 (wslines (window-screen-lines))
6014 (edges (window-inside-pixel-edges))
6015 (winh (- (nth 3 edges) (nth 1 edges) 1))
6016 py vs last-line)
6017 (if (> (mod wslines 1.0) 0.0)
6018 (setq wslines (round (+ wslines 0.5))))
6019 (when (or (null lh)
6020 (>= rbot dlh)
6021 (<= ypos (- dlh))
6022 (null this-lh)
6023 (<= this-ypos (- dlh)))
6024 (unless lh
6025 (let ((wend (pos-visible-in-window-p t nil t)))
6026 (setq rbot (nth 3 wend)
6027 rowh (nth 4 wend)
6028 vpos (nth 5 wend))))
6029 (unless this-lh
6030 (let ((wstart (pos-visible-in-window-p nil nil t)))
6031 (setq this-ypos (nth 2 wstart)
6032 this-height (nth 4 wstart))))
6033 (setq py
6034 (or (nth 1 this-lh)
6035 (let ((ppos (posn-at-point))
6036 col-row)
6037 (setq col-row (posn-actual-col-row ppos))
6038 (if col-row
6039 (- (cdr col-row) (window-vscroll))
6040 (cdr (posn-col-row ppos))))))
6041 ;; VPOS > 0 means the last line is only partially visible.
6042 ;; But if the part that is visible is at least as tall as the
6043 ;; default font, that means the line is actually fully
6044 ;; readable, and something like line-spacing is hidden. So in
6045 ;; that case we accept the last line in the window as still
6046 ;; visible, and consider the margin as starting one line
6047 ;; later.
6048 (if (and vpos (> vpos 0))
6049 (if (and rowh
6050 (>= rowh (default-font-height))
6051 (< rowh dlh))
6052 (setq last-line (min (- wslines scroll-margin) vpos))
6053 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6054 (cond
6055 ;; If last line of window is fully visible, and vscrolling
6056 ;; more would make this line invisible, move forward.
6057 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6058 (null this-height)
6059 (<= this-height dlh))
6060 (or (null rbot) (= rbot 0)))
6061 nil)
6062 ;; If cursor is not in the bottom scroll margin, and the
6063 ;; current line is is not too tall, move forward.
6064 ((and (or (null this-height) (<= this-height winh))
6065 vpos
6066 (> vpos 0)
6067 (< py last-line))
6068 nil)
6069 ;; When already vscrolled, we vscroll some more if we can,
6070 ;; or clear vscroll and move forward at end of tall image.
6071 ((> vs 0)
6072 (when (or (and rbot (> rbot 0))
6073 (and this-height (> this-height dlh)))
6074 (set-window-vscroll nil (+ vs dlh) t)))
6075 ;; If cursor just entered the bottom scroll margin, move forward,
6076 ;; but also optionally vscroll one line so redisplay won't recenter.
6077 ((and vpos
6078 (> vpos 0)
6079 (= py last-line))
6080 ;; Don't vscroll if the partially-visible line at window
6081 ;; bottom is not too tall (a.k.a. "just one more text
6082 ;; line"): in that case, we do want redisplay to behave
6083 ;; normally, i.e. recenter or whatever.
6085 ;; Note: ROWH + RBOT from the value returned by
6086 ;; pos-visible-in-window-p give the total height of the
6087 ;; partially-visible glyph row at the end of the window. As
6088 ;; we are dealing with floats, we disregard sub-pixel
6089 ;; discrepancies between that and DLH.
6090 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6091 (set-window-vscroll nil dlh t))
6092 (line-move-1 arg noerror)
6094 ;; If there are lines above the last line, scroll-up one line.
6095 ((and vpos (> vpos 0))
6096 (scroll-up 1)
6098 ;; Finally, start vscroll.
6100 (set-window-vscroll nil dlh t)))))))
6103 ;; This is like line-move-1 except that it also performs
6104 ;; vertical scrolling of tall images if appropriate.
6105 ;; That is not really a clean thing to do, since it mixes
6106 ;; scrolling with cursor motion. But so far we don't have
6107 ;; a cleaner solution to the problem of making C-n do something
6108 ;; useful given a tall image.
6109 (defun line-move (arg &optional noerror _to-end try-vscroll)
6110 "Move forward ARG lines.
6111 If NOERROR, don't signal an error if we can't move ARG lines.
6112 TO-END is unused.
6113 TRY-VSCROLL controls whether to vscroll tall lines: if either
6114 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6115 not vscroll."
6116 (if noninteractive
6117 (line-move-1 arg noerror)
6118 (unless (and auto-window-vscroll try-vscroll
6119 ;; Only vscroll for single line moves
6120 (= (abs arg) 1)
6121 ;; Under scroll-conservatively, the display engine
6122 ;; does this better.
6123 (zerop scroll-conservatively)
6124 ;; But don't vscroll in a keyboard macro.
6125 (not defining-kbd-macro)
6126 (not executing-kbd-macro)
6127 (line-move-partial arg noerror))
6128 (set-window-vscroll nil 0 t)
6129 (if (and line-move-visual
6130 ;; Display-based column are incompatible with goal-column.
6131 (not goal-column)
6132 ;; When the text in the window is scrolled to the left,
6133 ;; display-based motion doesn't make sense (because each
6134 ;; logical line occupies exactly one screen line).
6135 (not (> (window-hscroll) 0))
6136 ;; Likewise when the text _was_ scrolled to the left
6137 ;; when the current run of vertical motion commands
6138 ;; started.
6139 (not (and (memq last-command
6140 `(next-line previous-line ,this-command))
6141 auto-hscroll-mode
6142 (numberp temporary-goal-column)
6143 (>= temporary-goal-column
6144 (- (window-width) hscroll-margin)))))
6145 (prog1 (line-move-visual arg noerror)
6146 ;; If we moved into a tall line, set vscroll to make
6147 ;; scrolling through tall images more smooth.
6148 (let ((lh (line-pixel-height))
6149 (edges (window-inside-pixel-edges))
6150 (dlh (default-line-height))
6151 winh)
6152 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6153 (if (and (< arg 0)
6154 (< (point) (window-start))
6155 (> lh winh))
6156 (set-window-vscroll
6158 (- lh dlh) t))))
6159 (line-move-1 arg noerror)))))
6161 ;; Display-based alternative to line-move-1.
6162 ;; Arg says how many lines to move. The value is t if we can move the
6163 ;; specified number of lines.
6164 (defun line-move-visual (arg &optional noerror)
6165 "Move ARG lines forward.
6166 If NOERROR, don't signal an error if we can't move that many lines."
6167 (let ((opoint (point))
6168 (hscroll (window-hscroll))
6169 target-hscroll)
6170 ;; Check if the previous command was a line-motion command, or if
6171 ;; we were called from some other command.
6172 (if (and (consp temporary-goal-column)
6173 (memq last-command `(next-line previous-line ,this-command)))
6174 ;; If so, there's no need to reset `temporary-goal-column',
6175 ;; but we may need to hscroll.
6176 (if (or (/= (cdr temporary-goal-column) hscroll)
6177 (> (cdr temporary-goal-column) 0))
6178 (setq target-hscroll (cdr temporary-goal-column)))
6179 ;; Otherwise, we should reset `temporary-goal-column'.
6180 (let ((posn (posn-at-point))
6181 x-pos)
6182 (cond
6183 ;; Handle the `overflow-newline-into-fringe' case:
6184 ((eq (nth 1 posn) 'right-fringe)
6185 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
6186 ((car (posn-x-y posn))
6187 (setq x-pos (car (posn-x-y posn)))
6188 ;; In R2L lines, the X pixel coordinate is measured from the
6189 ;; left edge of the window, but columns are still counted
6190 ;; from the logical-order beginning of the line, i.e. from
6191 ;; the right edge in this case. We need to adjust for that.
6192 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6193 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6194 (setq temporary-goal-column
6195 (cons (/ (float x-pos)
6196 (frame-char-width))
6197 hscroll)))
6198 (executing-kbd-macro
6199 ;; When we move beyond the first/last character visible in
6200 ;; the window, posn-at-point will return nil, so we need to
6201 ;; approximate the goal column as below.
6202 (setq temporary-goal-column
6203 (mod (current-column) (window-text-width)))))))
6204 (if target-hscroll
6205 (set-window-hscroll (selected-window) target-hscroll))
6206 ;; vertical-motion can move more than it was asked to if it moves
6207 ;; across display strings with newlines. We don't want to ring
6208 ;; the bell and announce beginning/end of buffer in that case.
6209 (or (and (or (and (>= arg 0)
6210 (>= (vertical-motion
6211 (cons (or goal-column
6212 (if (consp temporary-goal-column)
6213 (car temporary-goal-column)
6214 temporary-goal-column))
6215 arg))
6216 arg))
6217 (and (< arg 0)
6218 (<= (vertical-motion
6219 (cons (or goal-column
6220 (if (consp temporary-goal-column)
6221 (car temporary-goal-column)
6222 temporary-goal-column))
6223 arg))
6224 arg)))
6225 (or (>= arg 0)
6226 (/= (point) opoint)
6227 ;; If the goal column lies on a display string,
6228 ;; `vertical-motion' advances the cursor to the end
6229 ;; of the string. For arg < 0, this can cause the
6230 ;; cursor to get stuck. (Bug#3020).
6231 (= (vertical-motion arg) arg)))
6232 (unless noerror
6233 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6234 nil)))))
6236 ;; This is the guts of next-line and previous-line.
6237 ;; Arg says how many lines to move.
6238 ;; The value is t if we can move the specified number of lines.
6239 (defun line-move-1 (arg &optional noerror _to-end)
6240 ;; Don't run any point-motion hooks, and disregard intangibility,
6241 ;; for intermediate positions.
6242 (let ((inhibit-point-motion-hooks t)
6243 (opoint (point))
6244 (orig-arg arg))
6245 (if (consp temporary-goal-column)
6246 (setq temporary-goal-column (+ (car temporary-goal-column)
6247 (cdr temporary-goal-column))))
6248 (unwind-protect
6249 (progn
6250 (if (not (memq last-command '(next-line previous-line)))
6251 (setq temporary-goal-column
6252 (if (and track-eol (eolp)
6253 ;; Don't count beg of empty line as end of line
6254 ;; unless we just did explicit end-of-line.
6255 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6256 most-positive-fixnum
6257 (current-column))))
6259 (if (not (or (integerp selective-display)
6260 line-move-ignore-invisible))
6261 ;; Use just newline characters.
6262 ;; Set ARG to 0 if we move as many lines as requested.
6263 (or (if (> arg 0)
6264 (progn (if (> arg 1) (forward-line (1- arg)))
6265 ;; This way of moving forward ARG lines
6266 ;; verifies that we have a newline after the last one.
6267 ;; It doesn't get confused by intangible text.
6268 (end-of-line)
6269 (if (zerop (forward-line 1))
6270 (setq arg 0)))
6271 (and (zerop (forward-line arg))
6272 (bolp)
6273 (setq arg 0)))
6274 (unless noerror
6275 (signal (if (< arg 0)
6276 'beginning-of-buffer
6277 'end-of-buffer)
6278 nil)))
6279 ;; Move by arg lines, but ignore invisible ones.
6280 (let (done)
6281 (while (and (> arg 0) (not done))
6282 ;; If the following character is currently invisible,
6283 ;; skip all characters with that same `invisible' property value.
6284 (while (and (not (eobp)) (invisible-p (point)))
6285 (goto-char (next-char-property-change (point))))
6286 ;; Move a line.
6287 ;; We don't use `end-of-line', since we want to escape
6288 ;; from field boundaries occurring exactly at point.
6289 (goto-char (constrain-to-field
6290 (let ((inhibit-field-text-motion t))
6291 (line-end-position))
6292 (point) t t
6293 'inhibit-line-move-field-capture))
6294 ;; If there's no invisibility here, move over the newline.
6295 (cond
6296 ((eobp)
6297 (if (not noerror)
6298 (signal 'end-of-buffer nil)
6299 (setq done t)))
6300 ((and (> arg 1) ;; Use vertical-motion for last move
6301 (not (integerp selective-display))
6302 (not (invisible-p (point))))
6303 ;; We avoid vertical-motion when possible
6304 ;; because that has to fontify.
6305 (forward-line 1))
6306 ;; Otherwise move a more sophisticated way.
6307 ((zerop (vertical-motion 1))
6308 (if (not noerror)
6309 (signal 'end-of-buffer nil)
6310 (setq done t))))
6311 (unless done
6312 (setq arg (1- arg))))
6313 ;; The logic of this is the same as the loop above,
6314 ;; it just goes in the other direction.
6315 (while (and (< arg 0) (not done))
6316 ;; For completely consistency with the forward-motion
6317 ;; case, we should call beginning-of-line here.
6318 ;; However, if point is inside a field and on a
6319 ;; continued line, the call to (vertical-motion -1)
6320 ;; below won't move us back far enough; then we return
6321 ;; to the same column in line-move-finish, and point
6322 ;; gets stuck -- cyd
6323 (forward-line 0)
6324 (cond
6325 ((bobp)
6326 (if (not noerror)
6327 (signal 'beginning-of-buffer nil)
6328 (setq done t)))
6329 ((and (< arg -1) ;; Use vertical-motion for last move
6330 (not (integerp selective-display))
6331 (not (invisible-p (1- (point)))))
6332 (forward-line -1))
6333 ((zerop (vertical-motion -1))
6334 (if (not noerror)
6335 (signal 'beginning-of-buffer nil)
6336 (setq done t))))
6337 (unless done
6338 (setq arg (1+ arg))
6339 (while (and ;; Don't move over previous invis lines
6340 ;; if our target is the middle of this line.
6341 (or (zerop (or goal-column temporary-goal-column))
6342 (< arg 0))
6343 (not (bobp)) (invisible-p (1- (point))))
6344 (goto-char (previous-char-property-change (point))))))))
6345 ;; This is the value the function returns.
6346 (= arg 0))
6348 (cond ((> arg 0)
6349 ;; If we did not move down as far as desired, at least go
6350 ;; to end of line. Be sure to call point-entered and
6351 ;; point-left-hooks.
6352 (let* ((npoint (prog1 (line-end-position)
6353 (goto-char opoint)))
6354 (inhibit-point-motion-hooks nil))
6355 (goto-char npoint)))
6356 ((< arg 0)
6357 ;; If we did not move up as far as desired,
6358 ;; at least go to beginning of line.
6359 (let* ((npoint (prog1 (line-beginning-position)
6360 (goto-char opoint)))
6361 (inhibit-point-motion-hooks nil))
6362 (goto-char npoint)))
6364 (line-move-finish (or goal-column temporary-goal-column)
6365 opoint (> orig-arg 0)))))))
6367 (defun line-move-finish (column opoint forward)
6368 (let ((repeat t))
6369 (while repeat
6370 ;; Set REPEAT to t to repeat the whole thing.
6371 (setq repeat nil)
6373 (let (new
6374 (old (point))
6375 (line-beg (line-beginning-position))
6376 (line-end
6377 ;; Compute the end of the line
6378 ;; ignoring effectively invisible newlines.
6379 (save-excursion
6380 ;; Like end-of-line but ignores fields.
6381 (skip-chars-forward "^\n")
6382 (while (and (not (eobp)) (invisible-p (point)))
6383 (goto-char (next-char-property-change (point)))
6384 (skip-chars-forward "^\n"))
6385 (point))))
6387 ;; Move to the desired column.
6388 (line-move-to-column (truncate column))
6390 ;; Corner case: suppose we start out in a field boundary in
6391 ;; the middle of a continued line. When we get to
6392 ;; line-move-finish, point is at the start of a new *screen*
6393 ;; line but the same text line; then line-move-to-column would
6394 ;; move us backwards. Test using C-n with point on the "x" in
6395 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6396 (and forward
6397 (< (point) old)
6398 (goto-char old))
6400 (setq new (point))
6402 ;; Process intangibility within a line.
6403 ;; With inhibit-point-motion-hooks bound to nil, a call to
6404 ;; goto-char moves point past intangible text.
6406 ;; However, inhibit-point-motion-hooks controls both the
6407 ;; intangibility and the point-entered/point-left hooks. The
6408 ;; following hack avoids calling the point-* hooks
6409 ;; unnecessarily. Note that we move *forward* past intangible
6410 ;; text when the initial and final points are the same.
6411 (goto-char new)
6412 (let ((inhibit-point-motion-hooks nil))
6413 (goto-char new)
6415 ;; If intangibility moves us to a different (later) place
6416 ;; in the same line, use that as the destination.
6417 (if (<= (point) line-end)
6418 (setq new (point))
6419 ;; If that position is "too late",
6420 ;; try the previous allowable position.
6421 ;; See if it is ok.
6422 (backward-char)
6423 (if (if forward
6424 ;; If going forward, don't accept the previous
6425 ;; allowable position if it is before the target line.
6426 (< line-beg (point))
6427 ;; If going backward, don't accept the previous
6428 ;; allowable position if it is still after the target line.
6429 (<= (point) line-end))
6430 (setq new (point))
6431 ;; As a last resort, use the end of the line.
6432 (setq new line-end))))
6434 ;; Now move to the updated destination, processing fields
6435 ;; as well as intangibility.
6436 (goto-char opoint)
6437 (let ((inhibit-point-motion-hooks nil))
6438 (goto-char
6439 ;; Ignore field boundaries if the initial and final
6440 ;; positions have the same `field' property, even if the
6441 ;; fields are non-contiguous. This seems to be "nicer"
6442 ;; behavior in many situations.
6443 (if (eq (get-char-property new 'field)
6444 (get-char-property opoint 'field))
6446 (constrain-to-field new opoint t t
6447 'inhibit-line-move-field-capture))))
6449 ;; If all this moved us to a different line,
6450 ;; retry everything within that new line.
6451 (when (or (< (point) line-beg) (> (point) line-end))
6452 ;; Repeat the intangibility and field processing.
6453 (setq repeat t))))))
6455 (defun line-move-to-column (col)
6456 "Try to find column COL, considering invisibility.
6457 This function works only in certain cases,
6458 because what we really need is for `move-to-column'
6459 and `current-column' to be able to ignore invisible text."
6460 (if (zerop col)
6461 (beginning-of-line)
6462 (move-to-column col))
6464 (when (and line-move-ignore-invisible
6465 (not (bolp)) (invisible-p (1- (point))))
6466 (let ((normal-location (point))
6467 (normal-column (current-column)))
6468 ;; If the following character is currently invisible,
6469 ;; skip all characters with that same `invisible' property value.
6470 (while (and (not (eobp))
6471 (invisible-p (point)))
6472 (goto-char (next-char-property-change (point))))
6473 ;; Have we advanced to a larger column position?
6474 (if (> (current-column) normal-column)
6475 ;; We have made some progress towards the desired column.
6476 ;; See if we can make any further progress.
6477 (line-move-to-column (+ (current-column) (- col normal-column)))
6478 ;; Otherwise, go to the place we originally found
6479 ;; and move back over invisible text.
6480 ;; that will get us to the same place on the screen
6481 ;; but with a more reasonable buffer position.
6482 (goto-char normal-location)
6483 (let ((line-beg
6484 ;; We want the real line beginning, so it's consistent
6485 ;; with bolp below, otherwise we might infloop.
6486 (let ((inhibit-field-text-motion t))
6487 (line-beginning-position))))
6488 (while (and (not (bolp)) (invisible-p (1- (point))))
6489 (goto-char (previous-char-property-change (point) line-beg))))))))
6491 (defun move-end-of-line (arg)
6492 "Move point to end of current line as displayed.
6493 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6494 If point reaches the beginning or end of buffer, it stops there.
6496 To ignore the effects of the `intangible' text or overlay
6497 property, bind `inhibit-point-motion-hooks' to t.
6498 If there is an image in the current line, this function
6499 disregards newlines that are part of the text on which the image
6500 rests."
6501 (interactive "^p")
6502 (or arg (setq arg 1))
6503 (let (done)
6504 (while (not done)
6505 (let ((newpos
6506 (save-excursion
6507 (let ((goal-column 0)
6508 (line-move-visual nil))
6509 (and (line-move arg t)
6510 ;; With bidi reordering, we may not be at bol,
6511 ;; so make sure we are.
6512 (skip-chars-backward "^\n")
6513 (not (bobp))
6514 (progn
6515 (while (and (not (bobp)) (invisible-p (1- (point))))
6516 (goto-char (previous-single-char-property-change
6517 (point) 'invisible)))
6518 (backward-char 1)))
6519 (point)))))
6520 (goto-char newpos)
6521 (if (and (> (point) newpos)
6522 (eq (preceding-char) ?\n))
6523 (backward-char 1)
6524 (if (and (> (point) newpos) (not (eobp))
6525 (not (eq (following-char) ?\n)))
6526 ;; If we skipped something intangible and now we're not
6527 ;; really at eol, keep going.
6528 (setq arg 1)
6529 (setq done t)))))))
6531 (defun move-beginning-of-line (arg)
6532 "Move point to beginning of current line as displayed.
6533 \(If there's an image in the line, this disregards newlines
6534 which are part of the text that the image rests on.)
6536 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6537 If point reaches the beginning or end of buffer, it stops there.
6538 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6539 (interactive "^p")
6540 (or arg (setq arg 1))
6542 (let ((orig (point))
6543 first-vis first-vis-field-value)
6545 ;; Move by lines, if ARG is not 1 (the default).
6546 (if (/= arg 1)
6547 (let ((line-move-visual nil))
6548 (line-move (1- arg) t)))
6550 ;; Move to beginning-of-line, ignoring fields and invisible text.
6551 (skip-chars-backward "^\n")
6552 (while (and (not (bobp)) (invisible-p (1- (point))))
6553 (goto-char (previous-char-property-change (point)))
6554 (skip-chars-backward "^\n"))
6556 ;; Now find first visible char in the line.
6557 (while (and (< (point) orig) (invisible-p (point)))
6558 (goto-char (next-char-property-change (point) orig)))
6559 (setq first-vis (point))
6561 ;; See if fields would stop us from reaching FIRST-VIS.
6562 (setq first-vis-field-value
6563 (constrain-to-field first-vis orig (/= arg 1) t nil))
6565 (goto-char (if (/= first-vis-field-value first-vis)
6566 ;; If yes, obey them.
6567 first-vis-field-value
6568 ;; Otherwise, move to START with attention to fields.
6569 ;; (It is possible that fields never matter in this case.)
6570 (constrain-to-field (point) orig
6571 (/= arg 1) t nil)))))
6574 ;; Many people have said they rarely use this feature, and often type
6575 ;; it by accident. Maybe it shouldn't even be on a key.
6576 (put 'set-goal-column 'disabled t)
6578 (defun set-goal-column (arg)
6579 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6580 Those commands will move to this position in the line moved to
6581 rather than trying to keep the same horizontal position.
6582 With a non-nil argument ARG, clears out the goal column
6583 so that \\[next-line] and \\[previous-line] resume vertical motion.
6584 The goal column is stored in the variable `goal-column'.
6585 This is a buffer-local setting."
6586 (interactive "P")
6587 (if arg
6588 (progn
6589 (setq goal-column nil)
6590 (message "No goal column"))
6591 (setq goal-column (current-column))
6592 ;; The older method below can be erroneous if `set-goal-column' is bound
6593 ;; to a sequence containing %
6594 ;;(message (substitute-command-keys
6595 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6596 ;;goal-column)
6597 (message "%s"
6598 (concat
6599 (format "Goal column %d " goal-column)
6600 (substitute-command-keys
6601 "(use \\[set-goal-column] with an arg to unset it)")))
6604 nil)
6606 ;;; Editing based on visual lines, as opposed to logical lines.
6608 (defun end-of-visual-line (&optional n)
6609 "Move point to end of current visual line.
6610 With argument N not nil or 1, move forward N - 1 visual lines first.
6611 If point reaches the beginning or end of buffer, it stops there.
6612 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6613 (interactive "^p")
6614 (or n (setq n 1))
6615 (if (/= n 1)
6616 (let ((line-move-visual t))
6617 (line-move (1- n) t)))
6618 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6619 ;; constrain to field boundaries, so we don't either.
6620 (vertical-motion (cons (window-width) 0)))
6622 (defun beginning-of-visual-line (&optional n)
6623 "Move point to beginning of current visual line.
6624 With argument N not nil or 1, move forward N - 1 visual lines first.
6625 If point reaches the beginning or end of buffer, it stops there.
6626 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6627 (interactive "^p")
6628 (or n (setq n 1))
6629 (let ((opoint (point)))
6630 (if (/= n 1)
6631 (let ((line-move-visual t))
6632 (line-move (1- n) t)))
6633 (vertical-motion 0)
6634 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6635 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6637 (defun kill-visual-line (&optional arg)
6638 "Kill the rest of the visual line.
6639 With prefix argument ARG, kill that many visual lines from point.
6640 If ARG is negative, kill visual lines backward.
6641 If ARG is zero, kill the text before point on the current visual
6642 line.
6644 If you want to append the killed line to the last killed text,
6645 use \\[append-next-kill] before \\[kill-line].
6647 If the buffer is read-only, Emacs will beep and refrain from deleting
6648 the line, but put the line in the kill ring anyway. This means that
6649 you can use this command to copy text from a read-only buffer.
6650 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6651 even beep.)"
6652 (interactive "P")
6653 ;; Like in `kill-line', it's better to move point to the other end
6654 ;; of the kill before killing.
6655 (let ((opoint (point))
6656 (kill-whole-line (and kill-whole-line (bolp))))
6657 (if arg
6658 (vertical-motion (prefix-numeric-value arg))
6659 (end-of-visual-line 1)
6660 (if (= (point) opoint)
6661 (vertical-motion 1)
6662 ;; Skip any trailing whitespace at the end of the visual line.
6663 ;; We used to do this only if `show-trailing-whitespace' is
6664 ;; nil, but that's wrong; the correct thing would be to check
6665 ;; whether the trailing whitespace is highlighted. But, it's
6666 ;; OK to just do this unconditionally.
6667 (skip-chars-forward " \t")))
6668 (kill-region opoint (if (and kill-whole-line (= (following-char) ?\n))
6669 (1+ (point))
6670 (point)))))
6672 (defun next-logical-line (&optional arg try-vscroll)
6673 "Move cursor vertically down ARG lines.
6674 This is identical to `next-line', except that it always moves
6675 by logical lines instead of visual lines, ignoring the value of
6676 the variable `line-move-visual'."
6677 (interactive "^p\np")
6678 (let ((line-move-visual nil))
6679 (with-no-warnings
6680 (next-line arg try-vscroll))))
6682 (defun previous-logical-line (&optional arg try-vscroll)
6683 "Move cursor vertically up ARG lines.
6684 This is identical to `previous-line', except that it always moves
6685 by logical lines instead of visual lines, ignoring the value of
6686 the variable `line-move-visual'."
6687 (interactive "^p\np")
6688 (let ((line-move-visual nil))
6689 (with-no-warnings
6690 (previous-line arg try-vscroll))))
6692 (defgroup visual-line nil
6693 "Editing based on visual lines."
6694 :group 'convenience
6695 :version "23.1")
6697 (defvar visual-line-mode-map
6698 (let ((map (make-sparse-keymap)))
6699 (define-key map [remap kill-line] 'kill-visual-line)
6700 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6701 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6702 ;; These keybindings interfere with xterm function keys. Are
6703 ;; there any other suitable bindings?
6704 ;; (define-key map "\M-[" 'previous-logical-line)
6705 ;; (define-key map "\M-]" 'next-logical-line)
6706 map))
6708 (defcustom visual-line-fringe-indicators '(nil nil)
6709 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6710 The value should be a list of the form (LEFT RIGHT), where LEFT
6711 and RIGHT are symbols representing the bitmaps to display, to
6712 indicate wrapped lines, in the left and right fringes respectively.
6713 See also `fringe-indicator-alist'.
6714 The default is not to display fringe indicators for wrapped lines.
6715 This variable does not affect fringe indicators displayed for
6716 other purposes."
6717 :type '(list (choice (const :tag "Hide left indicator" nil)
6718 (const :tag "Left curly arrow" left-curly-arrow)
6719 (symbol :tag "Other bitmap"))
6720 (choice (const :tag "Hide right indicator" nil)
6721 (const :tag "Right curly arrow" right-curly-arrow)
6722 (symbol :tag "Other bitmap")))
6723 :set (lambda (symbol value)
6724 (dolist (buf (buffer-list))
6725 (with-current-buffer buf
6726 (when (and (boundp 'visual-line-mode)
6727 (symbol-value 'visual-line-mode))
6728 (setq fringe-indicator-alist
6729 (cons (cons 'continuation value)
6730 (assq-delete-all
6731 'continuation
6732 (copy-tree fringe-indicator-alist)))))))
6733 (set-default symbol value)))
6735 (defvar visual-line--saved-state nil)
6737 (define-minor-mode visual-line-mode
6738 "Toggle visual line based editing (Visual Line mode).
6739 With a prefix argument ARG, enable Visual Line mode if ARG is
6740 positive, and disable it otherwise. If called from Lisp, enable
6741 the mode if ARG is omitted or nil.
6743 When Visual Line mode is enabled, `word-wrap' is turned on in
6744 this buffer, and simple editing commands are redefined to act on
6745 visual lines, not logical lines. See Info node `Visual Line
6746 Mode' for details."
6747 :keymap visual-line-mode-map
6748 :group 'visual-line
6749 :lighter " Wrap"
6750 (if visual-line-mode
6751 (progn
6752 (set (make-local-variable 'visual-line--saved-state) nil)
6753 ;; Save the local values of some variables, to be restored if
6754 ;; visual-line-mode is turned off.
6755 (dolist (var '(line-move-visual truncate-lines
6756 truncate-partial-width-windows
6757 word-wrap fringe-indicator-alist))
6758 (if (local-variable-p var)
6759 (push (cons var (symbol-value var))
6760 visual-line--saved-state)))
6761 (set (make-local-variable 'line-move-visual) t)
6762 (set (make-local-variable 'truncate-partial-width-windows) nil)
6763 (setq truncate-lines nil
6764 word-wrap t
6765 fringe-indicator-alist
6766 (cons (cons 'continuation visual-line-fringe-indicators)
6767 fringe-indicator-alist)))
6768 (kill-local-variable 'line-move-visual)
6769 (kill-local-variable 'word-wrap)
6770 (kill-local-variable 'truncate-lines)
6771 (kill-local-variable 'truncate-partial-width-windows)
6772 (kill-local-variable 'fringe-indicator-alist)
6773 (dolist (saved visual-line--saved-state)
6774 (set (make-local-variable (car saved)) (cdr saved)))
6775 (kill-local-variable 'visual-line--saved-state)))
6777 (defun turn-on-visual-line-mode ()
6778 (visual-line-mode 1))
6780 (define-globalized-minor-mode global-visual-line-mode
6781 visual-line-mode turn-on-visual-line-mode)
6784 (defun transpose-chars (arg)
6785 "Interchange characters around point, moving forward one character.
6786 With prefix arg ARG, effect is to take character before point
6787 and drag it forward past ARG other characters (backward if ARG negative).
6788 If no argument and at end of line, the previous two chars are exchanged."
6789 (interactive "*P")
6790 (when (and (null arg) (eolp) (not (bobp))
6791 (not (get-text-property (1- (point)) 'read-only)))
6792 (forward-char -1))
6793 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6795 (defun transpose-words (arg)
6796 "Interchange words around point, leaving point at end of them.
6797 With prefix arg ARG, effect is to take word before or around point
6798 and drag it forward past ARG other words (backward if ARG negative).
6799 If ARG is zero, the words around or after point and around or after mark
6800 are interchanged."
6801 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6802 (interactive "*p")
6803 (transpose-subr 'forward-word arg))
6805 (defun transpose-sexps (arg)
6806 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6807 Unlike `transpose-words', point must be between the two sexps and not
6808 in the middle of a sexp to be transposed.
6809 With non-zero prefix arg ARG, effect is to take the sexp before point
6810 and drag it forward past ARG other sexps (backward if ARG is negative).
6811 If ARG is zero, the sexps ending at or after point and at or after mark
6812 are interchanged."
6813 (interactive "*p")
6814 (transpose-subr
6815 (lambda (arg)
6816 ;; Here we should try to simulate the behavior of
6817 ;; (cons (progn (forward-sexp x) (point))
6818 ;; (progn (forward-sexp (- x)) (point)))
6819 ;; Except that we don't want to rely on the second forward-sexp
6820 ;; putting us back to where we want to be, since forward-sexp-function
6821 ;; might do funny things like infix-precedence.
6822 (if (if (> arg 0)
6823 (looking-at "\\sw\\|\\s_")
6824 (and (not (bobp))
6825 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6826 ;; Jumping over a symbol. We might be inside it, mind you.
6827 (progn (funcall (if (> arg 0)
6828 'skip-syntax-backward 'skip-syntax-forward)
6829 "w_")
6830 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6831 ;; Otherwise, we're between sexps. Take a step back before jumping
6832 ;; to make sure we'll obey the same precedence no matter which direction
6833 ;; we're going.
6834 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6835 (cons (save-excursion (forward-sexp arg) (point))
6836 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6837 (not (zerop (funcall (if (> arg 0)
6838 'skip-syntax-forward
6839 'skip-syntax-backward)
6840 ".")))))
6841 (point)))))
6842 arg 'special))
6844 (defun transpose-lines (arg)
6845 "Exchange current line and previous line, leaving point after both.
6846 With argument ARG, takes previous line and moves it past ARG lines.
6847 With argument 0, interchanges line point is in with line mark is in."
6848 (interactive "*p")
6849 (transpose-subr (function
6850 (lambda (arg)
6851 (if (> arg 0)
6852 (progn
6853 ;; Move forward over ARG lines,
6854 ;; but create newlines if necessary.
6855 (setq arg (forward-line arg))
6856 (if (/= (preceding-char) ?\n)
6857 (setq arg (1+ arg)))
6858 (if (> arg 0)
6859 (newline arg)))
6860 (forward-line arg))))
6861 arg))
6863 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6864 ;; which seems inconsistent with the ARG /= 0 case.
6865 ;; FIXME document SPECIAL.
6866 (defun transpose-subr (mover arg &optional special)
6867 "Subroutine to do the work of transposing objects.
6868 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6869 moves forward by units of the given object (e.g. forward-sentence,
6870 forward-paragraph). If ARG is zero, exchanges the current object
6871 with the one containing mark. If ARG is an integer, moves the
6872 current object past ARG following (if ARG is positive) or
6873 preceding (if ARG is negative) objects, leaving point after the
6874 current object."
6875 (let ((aux (if special mover
6876 (lambda (x)
6877 (cons (progn (funcall mover x) (point))
6878 (progn (funcall mover (- x)) (point))))))
6879 pos1 pos2)
6880 (cond
6881 ((= arg 0)
6882 (save-excursion
6883 (setq pos1 (funcall aux 1))
6884 (goto-char (or (mark) (error "No mark set in this buffer")))
6885 (setq pos2 (funcall aux 1))
6886 (transpose-subr-1 pos1 pos2))
6887 (exchange-point-and-mark))
6888 ((> arg 0)
6889 (setq pos1 (funcall aux -1))
6890 (setq pos2 (funcall aux arg))
6891 (transpose-subr-1 pos1 pos2)
6892 (goto-char (car pos2)))
6894 (setq pos1 (funcall aux -1))
6895 (goto-char (car pos1))
6896 (setq pos2 (funcall aux arg))
6897 (transpose-subr-1 pos1 pos2)
6898 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6900 (defun transpose-subr-1 (pos1 pos2)
6901 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6902 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6903 (when (> (car pos1) (car pos2))
6904 (let ((swap pos1))
6905 (setq pos1 pos2 pos2 swap)))
6906 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6907 (atomic-change-group
6908 ;; This sequence of insertions attempts to preserve marker
6909 ;; positions at the start and end of the transposed objects.
6910 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6911 (len1 (- (cdr pos1) (car pos1)))
6912 (len2 (length word))
6913 (boundary (make-marker)))
6914 (set-marker boundary (car pos2))
6915 (goto-char (cdr pos1))
6916 (insert-before-markers word)
6917 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6918 (goto-char boundary)
6919 (insert word)
6920 (goto-char (+ boundary len1))
6921 (delete-region (point) (+ (point) len2))
6922 (set-marker boundary nil))))
6924 (defun backward-word (&optional arg)
6925 "Move backward until encountering the beginning of a word.
6926 With argument ARG, do this that many times.
6927 If ARG is omitted or nil, move point backward one word.
6929 The word boundaries are normally determined by the buffer's syntax
6930 table, but `find-word-boundary-function-table', such as set up
6931 by `subword-mode', can change that. If a Lisp program needs to
6932 move by words determined strictly by the syntax table, it should
6933 use `backward-word-strictly' instead."
6934 (interactive "^p")
6935 (forward-word (- (or arg 1))))
6937 (defun mark-word (&optional arg allow-extend)
6938 "Set mark ARG words away from point.
6939 The place mark goes is the same place \\[forward-word] would
6940 move to with the same argument.
6941 Interactively, if this command is repeated
6942 or (in Transient Mark mode) if the mark is active,
6943 it marks the next ARG words after the ones already marked."
6944 (interactive "P\np")
6945 (cond ((and allow-extend
6946 (or (and (eq last-command this-command) (mark t))
6947 (region-active-p)))
6948 (setq arg (if arg (prefix-numeric-value arg)
6949 (if (< (mark) (point)) -1 1)))
6950 (set-mark
6951 (save-excursion
6952 (goto-char (mark))
6953 (forward-word arg)
6954 (point))))
6956 (push-mark
6957 (save-excursion
6958 (forward-word (prefix-numeric-value arg))
6959 (point))
6960 nil t))))
6962 (defun kill-word (arg)
6963 "Kill characters forward until encountering the end of a word.
6964 With argument ARG, do this that many times."
6965 (interactive "p")
6966 (kill-region (point) (progn (forward-word arg) (point))))
6968 (defun backward-kill-word (arg)
6969 "Kill characters backward until encountering the beginning of a word.
6970 With argument ARG, do this that many times."
6971 (interactive "p")
6972 (kill-word (- arg)))
6974 (defun current-word (&optional strict really-word)
6975 "Return the word at or near point, as a string.
6976 The return value includes no text properties.
6978 If optional arg STRICT is non-nil, return nil unless point is
6979 within or adjacent to a word, otherwise look for a word within
6980 point's line. If there is no word anywhere on point's line, the
6981 value is nil regardless of STRICT.
6983 By default, this function treats as a single word any sequence of
6984 characters that have either word or symbol syntax. If optional
6985 arg REALLY-WORD is non-nil, only characters of word syntax can
6986 constitute a word."
6987 (save-excursion
6988 (let* ((oldpoint (point)) (start (point)) (end (point))
6989 (syntaxes (if really-word "w" "w_"))
6990 (not-syntaxes (concat "^" syntaxes)))
6991 (skip-syntax-backward syntaxes) (setq start (point))
6992 (goto-char oldpoint)
6993 (skip-syntax-forward syntaxes) (setq end (point))
6994 (when (and (eq start oldpoint) (eq end oldpoint)
6995 ;; Point is neither within nor adjacent to a word.
6996 (not strict))
6997 ;; Look for preceding word in same line.
6998 (skip-syntax-backward not-syntaxes (line-beginning-position))
6999 (if (bolp)
7000 ;; No preceding word in same line.
7001 ;; Look for following word in same line.
7002 (progn
7003 (skip-syntax-forward not-syntaxes (line-end-position))
7004 (setq start (point))
7005 (skip-syntax-forward syntaxes)
7006 (setq end (point)))
7007 (setq end (point))
7008 (skip-syntax-backward syntaxes)
7009 (setq start (point))))
7010 ;; If we found something nonempty, return it as a string.
7011 (unless (= start end)
7012 (buffer-substring-no-properties start end)))))
7014 (defcustom fill-prefix nil
7015 "String for filling to insert at front of new line, or nil for none."
7016 :type '(choice (const :tag "None" nil)
7017 string)
7018 :group 'fill)
7019 (make-variable-buffer-local 'fill-prefix)
7020 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
7022 (defcustom auto-fill-inhibit-regexp nil
7023 "Regexp to match lines which should not be auto-filled."
7024 :type '(choice (const :tag "None" nil)
7025 regexp)
7026 :group 'fill)
7028 (defun do-auto-fill ()
7029 "The default value for `normal-auto-fill-function'.
7030 This is the default auto-fill function, some major modes use a different one.
7031 Returns t if it really did any work."
7032 (let (fc justify give-up
7033 (fill-prefix fill-prefix))
7034 (if (or (not (setq justify (current-justification)))
7035 (null (setq fc (current-fill-column)))
7036 (and (eq justify 'left)
7037 (<= (current-column) fc))
7038 (and auto-fill-inhibit-regexp
7039 (save-excursion (beginning-of-line)
7040 (looking-at auto-fill-inhibit-regexp))))
7041 nil ;; Auto-filling not required
7042 (if (memq justify '(full center right))
7043 (save-excursion (unjustify-current-line)))
7045 ;; Choose a fill-prefix automatically.
7046 (when (and adaptive-fill-mode
7047 (or (null fill-prefix) (string= fill-prefix "")))
7048 (let ((prefix
7049 (fill-context-prefix
7050 (save-excursion (fill-forward-paragraph -1) (point))
7051 (save-excursion (fill-forward-paragraph 1) (point)))))
7052 (and prefix (not (equal prefix ""))
7053 ;; Use auto-indentation rather than a guessed empty prefix.
7054 (not (and fill-indent-according-to-mode
7055 (string-match "\\`[ \t]*\\'" prefix)))
7056 (setq fill-prefix prefix))))
7058 (while (and (not give-up) (> (current-column) fc))
7059 ;; Determine where to split the line.
7060 (let* (after-prefix
7061 (fill-point
7062 (save-excursion
7063 (beginning-of-line)
7064 (setq after-prefix (point))
7065 (and fill-prefix
7066 (looking-at (regexp-quote fill-prefix))
7067 (setq after-prefix (match-end 0)))
7068 (move-to-column (1+ fc))
7069 (fill-move-to-break-point after-prefix)
7070 (point))))
7072 ;; See whether the place we found is any good.
7073 (if (save-excursion
7074 (goto-char fill-point)
7075 (or (bolp)
7076 ;; There is no use breaking at end of line.
7077 (save-excursion (skip-chars-forward " ") (eolp))
7078 ;; It is futile to split at the end of the prefix
7079 ;; since we would just insert the prefix again.
7080 (and after-prefix (<= (point) after-prefix))
7081 ;; Don't split right after a comment starter
7082 ;; since we would just make another comment starter.
7083 (and comment-start-skip
7084 (let ((limit (point)))
7085 (beginning-of-line)
7086 (and (re-search-forward comment-start-skip
7087 limit t)
7088 (eq (point) limit))))))
7089 ;; No good place to break => stop trying.
7090 (setq give-up t)
7091 ;; Ok, we have a useful place to break the line. Do it.
7092 (let ((prev-column (current-column)))
7093 ;; If point is at the fill-point, do not `save-excursion'.
7094 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7095 ;; point will end up before it rather than after it.
7096 (if (save-excursion
7097 (skip-chars-backward " \t")
7098 (= (point) fill-point))
7099 (default-indent-new-line t)
7100 (save-excursion
7101 (goto-char fill-point)
7102 (default-indent-new-line t)))
7103 ;; Now do justification, if required
7104 (if (not (eq justify 'left))
7105 (save-excursion
7106 (end-of-line 0)
7107 (justify-current-line justify nil t)))
7108 ;; If making the new line didn't reduce the hpos of
7109 ;; the end of the line, then give up now;
7110 ;; trying again will not help.
7111 (if (>= (current-column) prev-column)
7112 (setq give-up t))))))
7113 ;; Justify last line.
7114 (justify-current-line justify t t)
7115 t)))
7117 (defvar comment-line-break-function 'comment-indent-new-line
7118 "Mode-specific function which line breaks and continues a comment.
7119 This function is called during auto-filling when a comment syntax
7120 is defined.
7121 The function should take a single optional argument, which is a flag
7122 indicating whether it should use soft newlines.")
7124 (defun default-indent-new-line (&optional soft)
7125 "Break line at point and indent.
7126 If a comment syntax is defined, call `comment-indent-new-line'.
7128 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7129 unless optional argument SOFT is non-nil."
7130 (interactive)
7131 (if comment-start
7132 (funcall comment-line-break-function soft)
7133 ;; Insert the newline before removing empty space so that markers
7134 ;; get preserved better.
7135 (if soft (insert-and-inherit ?\n) (newline 1))
7136 (save-excursion (forward-char -1) (delete-horizontal-space))
7137 (delete-horizontal-space)
7139 (if (and fill-prefix (not adaptive-fill-mode))
7140 ;; Blindly trust a non-adaptive fill-prefix.
7141 (progn
7142 (indent-to-left-margin)
7143 (insert-before-markers-and-inherit fill-prefix))
7145 (cond
7146 ;; If there's an adaptive prefix, use it unless we're inside
7147 ;; a comment and the prefix is not a comment starter.
7148 (fill-prefix
7149 (indent-to-left-margin)
7150 (insert-and-inherit fill-prefix))
7151 ;; If we're not inside a comment, just try to indent.
7152 (t (indent-according-to-mode))))))
7154 (defvar normal-auto-fill-function 'do-auto-fill
7155 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7156 Some major modes set this.")
7158 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7159 ;; `functions' and `hooks' are usually unsafe to set, but setting
7160 ;; auto-fill-function to nil in a file-local setting is safe and
7161 ;; can be useful to prevent auto-filling.
7162 (put 'auto-fill-function 'safe-local-variable 'null)
7164 (define-minor-mode auto-fill-mode
7165 "Toggle automatic line breaking (Auto Fill mode).
7166 With a prefix argument ARG, enable Auto Fill mode if ARG is
7167 positive, and disable it otherwise. If called from Lisp, enable
7168 the mode if ARG is omitted or nil.
7170 When Auto Fill mode is enabled, inserting a space at a column
7171 beyond `current-fill-column' automatically breaks the line at a
7172 previous space.
7174 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7175 non-nil.
7177 The value of `normal-auto-fill-function' specifies the function to use
7178 for `auto-fill-function' when turning Auto Fill mode on."
7179 :variable (auto-fill-function
7180 . (lambda (v) (setq auto-fill-function
7181 (if v normal-auto-fill-function)))))
7183 ;; This holds a document string used to document auto-fill-mode.
7184 (defun auto-fill-function ()
7185 "Automatically break line at a previous space, in insertion of text."
7186 nil)
7188 (defun turn-on-auto-fill ()
7189 "Unconditionally turn on Auto Fill mode."
7190 (auto-fill-mode 1))
7192 (defun turn-off-auto-fill ()
7193 "Unconditionally turn off Auto Fill mode."
7194 (auto-fill-mode -1))
7196 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7198 (defun set-fill-column (arg)
7199 "Set `fill-column' to specified argument.
7200 Use \\[universal-argument] followed by a number to specify a column.
7201 Just \\[universal-argument] as argument means to use the current column."
7202 (interactive
7203 (list (or current-prefix-arg
7204 ;; We used to use current-column silently, but C-x f is too easily
7205 ;; typed as a typo for C-x C-f, so we turned it into an error and
7206 ;; now an interactive prompt.
7207 (read-number "Set fill-column to: " (current-column)))))
7208 (if (consp arg)
7209 (setq arg (current-column)))
7210 (if (not (integerp arg))
7211 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7212 (error "set-fill-column requires an explicit argument")
7213 (message "Fill column set to %d (was %d)" arg fill-column)
7214 (setq fill-column arg)))
7216 (defun set-selective-display (arg)
7217 "Set `selective-display' to ARG; clear it if no arg.
7218 When the value of `selective-display' is a number > 0,
7219 lines whose indentation is >= that value are not displayed.
7220 The variable `selective-display' has a separate value for each buffer."
7221 (interactive "P")
7222 (if (eq selective-display t)
7223 (error "selective-display already in use for marked lines"))
7224 (let ((current-vpos
7225 (save-restriction
7226 (narrow-to-region (point-min) (point))
7227 (goto-char (window-start))
7228 (vertical-motion (window-height)))))
7229 (setq selective-display
7230 (and arg (prefix-numeric-value arg)))
7231 (recenter current-vpos))
7232 (set-window-start (selected-window) (window-start))
7233 (princ "selective-display set to " t)
7234 (prin1 selective-display t)
7235 (princ "." t))
7237 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7239 (defun toggle-truncate-lines (&optional arg)
7240 "Toggle truncating of long lines for the current buffer.
7241 When truncating is off, long lines are folded.
7242 With prefix argument ARG, truncate long lines if ARG is positive,
7243 otherwise fold them. Note that in side-by-side windows, this
7244 command has no effect if `truncate-partial-width-windows' is
7245 non-nil."
7246 (interactive "P")
7247 (setq truncate-lines
7248 (if (null arg)
7249 (not truncate-lines)
7250 (> (prefix-numeric-value arg) 0)))
7251 (force-mode-line-update)
7252 (unless truncate-lines
7253 (let ((buffer (current-buffer)))
7254 (walk-windows (lambda (window)
7255 (if (eq buffer (window-buffer window))
7256 (set-window-hscroll window 0)))
7257 nil t)))
7258 (message "Truncate long lines %s"
7259 (if truncate-lines "enabled" "disabled")))
7261 (defun toggle-word-wrap (&optional arg)
7262 "Toggle whether to use word-wrapping for continuation lines.
7263 With prefix argument ARG, wrap continuation lines at word boundaries
7264 if ARG is positive, otherwise wrap them at the right screen edge.
7265 This command toggles the value of `word-wrap'. It has no effect
7266 if long lines are truncated."
7267 (interactive "P")
7268 (setq word-wrap
7269 (if (null arg)
7270 (not word-wrap)
7271 (> (prefix-numeric-value arg) 0)))
7272 (force-mode-line-update)
7273 (message "Word wrapping %s"
7274 (if word-wrap "enabled" "disabled")))
7276 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7277 "The string displayed in the mode line when in overwrite mode.")
7278 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7279 "The string displayed in the mode line when in binary overwrite mode.")
7281 (define-minor-mode overwrite-mode
7282 "Toggle Overwrite mode.
7283 With a prefix argument ARG, enable Overwrite mode if ARG is
7284 positive, and disable it otherwise. If called from Lisp, enable
7285 the mode if ARG is omitted or nil.
7287 When Overwrite mode is enabled, printing characters typed in
7288 replace existing text on a one-for-one basis, rather than pushing
7289 it to the right. At the end of a line, such characters extend
7290 the line. Before a tab, such characters insert until the tab is
7291 filled in. \\[quoted-insert] still inserts characters in
7292 overwrite mode; this is supposed to make it easier to insert
7293 characters when necessary."
7294 :variable (overwrite-mode
7295 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7297 (define-minor-mode binary-overwrite-mode
7298 "Toggle Binary Overwrite mode.
7299 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7300 is positive, and disable it otherwise. If called from Lisp,
7301 enable the mode if ARG is omitted or nil.
7303 When Binary Overwrite mode is enabled, printing characters typed
7304 in replace existing text. Newlines are not treated specially, so
7305 typing at the end of a line joins the line to the next, with the
7306 typed character between them. Typing before a tab character
7307 simply replaces the tab with the character typed.
7308 \\[quoted-insert] replaces the text at the cursor, just as
7309 ordinary typing characters do.
7311 Note that Binary Overwrite mode is not its own minor mode; it is
7312 a specialization of overwrite mode, entered by setting the
7313 `overwrite-mode' variable to `overwrite-mode-binary'."
7314 :variable (overwrite-mode
7315 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7317 (define-minor-mode line-number-mode
7318 "Toggle line number display in the mode line (Line Number mode).
7319 With a prefix argument ARG, enable Line Number mode if ARG is
7320 positive, and disable it otherwise. If called from Lisp, enable
7321 the mode if ARG is omitted or nil.
7323 Line numbers do not appear for very large buffers and buffers
7324 with very long lines; see variables `line-number-display-limit'
7325 and `line-number-display-limit-width'."
7326 :init-value t :global t :group 'mode-line)
7328 (define-minor-mode column-number-mode
7329 "Toggle column number display in the mode line (Column Number mode).
7330 With a prefix argument ARG, enable Column Number mode if ARG is
7331 positive, and disable it otherwise.
7333 If called from Lisp, enable the mode if ARG is omitted or nil."
7334 :global t :group 'mode-line)
7336 (define-minor-mode size-indication-mode
7337 "Toggle buffer size display in the mode line (Size Indication mode).
7338 With a prefix argument ARG, enable Size Indication mode if ARG is
7339 positive, and disable it otherwise.
7341 If called from Lisp, enable the mode if ARG is omitted or nil."
7342 :global t :group 'mode-line)
7344 (define-minor-mode auto-save-mode
7345 "Toggle auto-saving in the current buffer (Auto Save mode).
7346 With a prefix argument ARG, enable Auto Save mode if ARG is
7347 positive, and disable it otherwise.
7349 If called from Lisp, enable the mode if ARG is omitted or nil."
7350 :variable ((and buffer-auto-save-file-name
7351 ;; If auto-save is off because buffer has shrunk,
7352 ;; then toggling should turn it on.
7353 (>= buffer-saved-size 0))
7354 . (lambda (val)
7355 (setq buffer-auto-save-file-name
7356 (cond
7357 ((null val) nil)
7358 ((and buffer-file-name auto-save-visited-file-name
7359 (not buffer-read-only))
7360 buffer-file-name)
7361 (t (make-auto-save-file-name))))))
7362 ;; If -1 was stored here, to temporarily turn off saving,
7363 ;; turn it back on.
7364 (and (< buffer-saved-size 0)
7365 (setq buffer-saved-size 0)))
7367 (defgroup paren-blinking nil
7368 "Blinking matching of parens and expressions."
7369 :prefix "blink-matching-"
7370 :group 'paren-matching)
7372 (defcustom blink-matching-paren t
7373 "Non-nil means show matching open-paren when close-paren is inserted.
7374 If t, highlight the paren. If `jump', briefly move cursor to its
7375 position. If `jump-offscreen', move cursor there even if the
7376 position is off screen. With any other non-nil value, the
7377 off-screen position of the opening paren will be shown in the
7378 echo area."
7379 :type '(choice
7380 (const :tag "Disable" nil)
7381 (const :tag "Highlight" t)
7382 (const :tag "Move cursor" jump)
7383 (const :tag "Move cursor, even if off screen" jump-offscreen))
7384 :group 'paren-blinking)
7386 (defcustom blink-matching-paren-on-screen t
7387 "Non-nil means show matching open-paren when it is on screen.
7388 If nil, don't show it (but the open-paren can still be shown
7389 in the echo area when it is off screen).
7391 This variable has no effect if `blink-matching-paren' is nil.
7392 \(In that case, the open-paren is never shown.)
7393 It is also ignored if `show-paren-mode' is enabled."
7394 :type 'boolean
7395 :group 'paren-blinking)
7397 (defcustom blink-matching-paren-distance (* 100 1024)
7398 "If non-nil, maximum distance to search backwards for matching open-paren.
7399 If nil, search stops at the beginning of the accessible portion of the buffer."
7400 :version "23.2" ; 25->100k
7401 :type '(choice (const nil) integer)
7402 :group 'paren-blinking)
7404 (defcustom blink-matching-delay 1
7405 "Time in seconds to delay after showing a matching paren."
7406 :type 'number
7407 :group 'paren-blinking)
7409 (defcustom blink-matching-paren-dont-ignore-comments nil
7410 "If nil, `blink-matching-paren' ignores comments.
7411 More precisely, when looking for the matching parenthesis,
7412 it skips the contents of comments that end before point."
7413 :type 'boolean
7414 :group 'paren-blinking)
7416 (defun blink-matching-check-mismatch (start end)
7417 "Return whether or not START...END are matching parens.
7418 END is the current point and START is the blink position.
7419 START might be nil if no matching starter was found.
7420 Returns non-nil if we find there is a mismatch."
7421 (let* ((end-syntax (syntax-after (1- end)))
7422 (matching-paren (and (consp end-syntax)
7423 (eq (syntax-class end-syntax) 5)
7424 (cdr end-syntax))))
7425 ;; For self-matched chars like " and $, we can't know when they're
7426 ;; mismatched or unmatched, so we can only do it for parens.
7427 (when matching-paren
7428 (not (and start
7430 (eq (char-after start) matching-paren)
7431 ;; The cdr might hold a new paren-class info rather than
7432 ;; a matching-char info, in which case the two CDRs
7433 ;; should match.
7434 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7436 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7437 "Function to check parentheses mismatches.
7438 The function takes two arguments (START and END) where START is the
7439 position just before the opening token and END is the position right after.
7440 START can be nil, if it was not found.
7441 The function should return non-nil if the two tokens do not match.")
7443 (defvar blink-matching--overlay
7444 (let ((ol (make-overlay (point) (point) nil t)))
7445 (overlay-put ol 'face 'show-paren-match)
7446 (delete-overlay ol)
7448 "Overlay used to highlight the matching paren.")
7450 (defun blink-matching-open ()
7451 "Momentarily highlight the beginning of the sexp before point."
7452 (interactive)
7453 (when (and (not (bobp))
7454 blink-matching-paren)
7455 (let* ((oldpos (point))
7456 (message-log-max nil) ; Don't log messages about paren matching.
7457 (blinkpos
7458 (save-excursion
7459 (save-restriction
7460 (if blink-matching-paren-distance
7461 (narrow-to-region
7462 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7463 (- (point) blink-matching-paren-distance))
7464 oldpos))
7465 (let ((parse-sexp-ignore-comments
7466 (and parse-sexp-ignore-comments
7467 (not blink-matching-paren-dont-ignore-comments))))
7468 (condition-case ()
7469 (progn
7470 (syntax-propertize (point))
7471 (forward-sexp -1)
7472 ;; backward-sexp skips backward over prefix chars,
7473 ;; so move back to the matching paren.
7474 (while (and (< (point) (1- oldpos))
7475 (let ((code (syntax-after (point))))
7476 (or (eq (syntax-class code) 6)
7477 (eq (logand 1048576 (car code))
7478 1048576))))
7479 (forward-char 1))
7480 (point))
7481 (error nil))))))
7482 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7483 (cond
7484 (mismatch
7485 (if blinkpos
7486 (if (minibufferp)
7487 (minibuffer-message "Mismatched parentheses")
7488 (message "Mismatched parentheses"))
7489 (if (minibufferp)
7490 (minibuffer-message "No matching parenthesis found")
7491 (message "No matching parenthesis found"))))
7492 ((not blinkpos) nil)
7493 ((or
7494 (eq blink-matching-paren 'jump-offscreen)
7495 (pos-visible-in-window-p blinkpos))
7496 ;; Matching open within window, temporarily move to or highlight
7497 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7498 ;; is non-nil.
7499 (and blink-matching-paren-on-screen
7500 (not show-paren-mode)
7501 (if (memq blink-matching-paren '(jump jump-offscreen))
7502 (save-excursion
7503 (goto-char blinkpos)
7504 (sit-for blink-matching-delay))
7505 (unwind-protect
7506 (progn
7507 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7508 (current-buffer))
7509 (sit-for blink-matching-delay))
7510 (delete-overlay blink-matching--overlay)))))
7512 (let ((open-paren-line-string
7513 (save-excursion
7514 (goto-char blinkpos)
7515 ;; Show what precedes the open in its line, if anything.
7516 (cond
7517 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7518 (buffer-substring (line-beginning-position)
7519 (1+ blinkpos)))
7520 ;; Show what follows the open in its line, if anything.
7521 ((save-excursion
7522 (forward-char 1)
7523 (skip-chars-forward " \t")
7524 (not (eolp)))
7525 (buffer-substring blinkpos
7526 (line-end-position)))
7527 ;; Otherwise show the previous nonblank line,
7528 ;; if there is one.
7529 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7530 (concat
7531 (buffer-substring (progn
7532 (skip-chars-backward "\n \t")
7533 (line-beginning-position))
7534 (progn (end-of-line)
7535 (skip-chars-backward " \t")
7536 (point)))
7537 ;; Replace the newline and other whitespace with `...'.
7538 "..."
7539 (buffer-substring blinkpos (1+ blinkpos))))
7540 ;; There is nothing to show except the char itself.
7541 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7542 (minibuffer-message
7543 "Matches %s"
7544 (substring-no-properties open-paren-line-string))))))))
7546 (defvar blink-paren-function 'blink-matching-open
7547 "Function called, if non-nil, whenever a close parenthesis is inserted.
7548 More precisely, a char with closeparen syntax is self-inserted.")
7550 (defun blink-paren-post-self-insert-function ()
7551 (when (and (eq (char-before) last-command-event) ; Sanity check.
7552 (memq (char-syntax last-command-event) '(?\) ?\$))
7553 blink-paren-function
7554 (not executing-kbd-macro)
7555 (not noninteractive)
7556 ;; Verify an even number of quoting characters precede the close.
7557 ;; FIXME: Also check if this parenthesis closes a comment as
7558 ;; can happen in Pascal and SML.
7559 (= 1 (logand 1 (- (point)
7560 (save-excursion
7561 (forward-char -1)
7562 (skip-syntax-backward "/\\")
7563 (point))))))
7564 (funcall blink-paren-function)))
7566 (put 'blink-paren-post-self-insert-function 'priority 100)
7568 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7569 ;; Most likely, this hook is nil, so this arg doesn't matter,
7570 ;; but I use it as a reminder that this function usually
7571 ;; likes to be run after others since it does
7572 ;; `sit-for'. That's also the reason it get a `priority' prop
7573 ;; of 100.
7574 'append)
7576 ;; This executes C-g typed while Emacs is waiting for a command.
7577 ;; Quitting out of a program does not go through here;
7578 ;; that happens in the maybe_quit function at the C code level.
7579 (defun keyboard-quit ()
7580 "Signal a `quit' condition.
7581 During execution of Lisp code, this character causes a quit directly.
7582 At top-level, as an editor command, this simply beeps."
7583 (interactive)
7584 ;; Avoid adding the region to the window selection.
7585 (setq saved-region-selection nil)
7586 (let (select-active-regions)
7587 (deactivate-mark))
7588 (if (fboundp 'kmacro-keyboard-quit)
7589 (kmacro-keyboard-quit))
7590 (when completion-in-region-mode
7591 (completion-in-region-mode -1))
7592 ;; Force the next redisplay cycle to remove the "Def" indicator from
7593 ;; all the mode lines.
7594 (if defining-kbd-macro
7595 (force-mode-line-update t))
7596 (setq defining-kbd-macro nil)
7597 (let ((debug-on-quit nil))
7598 (signal 'quit nil)))
7600 (defvar buffer-quit-function nil
7601 "Function to call to \"quit\" the current buffer, or nil if none.
7602 \\[keyboard-escape-quit] calls this function when its more local actions
7603 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7605 (defun keyboard-escape-quit ()
7606 "Exit the current \"mode\" (in a generalized sense of the word).
7607 This command can exit an interactive command such as `query-replace',
7608 can clear out a prefix argument or a region,
7609 can get out of the minibuffer or other recursive edit,
7610 cancel the use of the current buffer (for special-purpose buffers),
7611 or go back to just one window (by deleting all but the selected window)."
7612 (interactive)
7613 (cond ((eq last-command 'mode-exited) nil)
7614 ((region-active-p)
7615 (deactivate-mark))
7616 ((> (minibuffer-depth) 0)
7617 (abort-recursive-edit))
7618 (current-prefix-arg
7619 nil)
7620 ((> (recursion-depth) 0)
7621 (exit-recursive-edit))
7622 (buffer-quit-function
7623 (funcall buffer-quit-function))
7624 ((not (one-window-p t))
7625 (delete-other-windows))
7626 ((string-match "^ \\*" (buffer-name (current-buffer)))
7627 (bury-buffer))))
7629 (defun play-sound-file (file &optional volume device)
7630 "Play sound stored in FILE.
7631 VOLUME and DEVICE correspond to the keywords of the sound
7632 specification for `play-sound'."
7633 (interactive "fPlay sound file: ")
7634 (let ((sound (list :file file)))
7635 (if volume
7636 (plist-put sound :volume volume))
7637 (if device
7638 (plist-put sound :device device))
7639 (push 'sound sound)
7640 (play-sound sound)))
7643 (defcustom read-mail-command 'rmail
7644 "Your preference for a mail reading package.
7645 This is used by some keybindings which support reading mail.
7646 See also `mail-user-agent' concerning sending mail."
7647 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7648 (function-item :tag "Gnus" :format "%t\n" gnus)
7649 (function-item :tag "Emacs interface to MH"
7650 :format "%t\n" mh-rmail)
7651 (function :tag "Other"))
7652 :version "21.1"
7653 :group 'mail)
7655 (defcustom mail-user-agent 'message-user-agent
7656 "Your preference for a mail composition package.
7657 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7658 outgoing email message. This variable lets you specify which
7659 mail-sending package you prefer.
7661 Valid values include:
7663 `message-user-agent' -- use the Message package.
7664 See Info node `(message)'.
7665 `sendmail-user-agent' -- use the Mail package.
7666 See Info node `(emacs)Sending Mail'.
7667 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7668 See Info node `(mh-e)'.
7669 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7670 paraphernalia if Gnus is running, particularly
7671 the Gcc: header for archiving.
7673 Additional valid symbols may be available; check with the author of
7674 your package for details. The function should return non-nil if it
7675 succeeds.
7677 See also `read-mail-command' concerning reading mail."
7678 :type '(radio (function-item :tag "Message package"
7679 :format "%t\n"
7680 message-user-agent)
7681 (function-item :tag "Mail package"
7682 :format "%t\n"
7683 sendmail-user-agent)
7684 (function-item :tag "Emacs interface to MH"
7685 :format "%t\n"
7686 mh-e-user-agent)
7687 (function-item :tag "Message with full Gnus features"
7688 :format "%t\n"
7689 gnus-user-agent)
7690 (function :tag "Other"))
7691 :version "23.2" ; sendmail->message
7692 :group 'mail)
7694 (defcustom compose-mail-user-agent-warnings t
7695 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7696 If the value of `mail-user-agent' is the default, and the user
7697 appears to have customizations applying to the old default,
7698 `compose-mail' issues a warning."
7699 :type 'boolean
7700 :version "23.2"
7701 :group 'mail)
7703 (defun rfc822-goto-eoh ()
7704 "If the buffer starts with a mail header, move point to the header's end.
7705 Otherwise, moves to `point-min'.
7706 The end of the header is the start of the next line, if there is one,
7707 else the end of the last line. This function obeys RFC822."
7708 (goto-char (point-min))
7709 (when (re-search-forward
7710 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7711 (goto-char (match-beginning 0))))
7713 ;; Used by Rmail (e.g., rmail-forward).
7714 (defvar mail-encode-mml nil
7715 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7716 the outgoing message before sending it.")
7718 (defun compose-mail (&optional to subject other-headers continue
7719 switch-function yank-action send-actions
7720 return-action)
7721 "Start composing a mail message to send.
7722 This uses the user's chosen mail composition package
7723 as selected with the variable `mail-user-agent'.
7724 The optional arguments TO and SUBJECT specify recipients
7725 and the initial Subject field, respectively.
7727 OTHER-HEADERS is an alist specifying additional
7728 header fields. Elements look like (HEADER . VALUE) where both
7729 HEADER and VALUE are strings.
7731 CONTINUE, if non-nil, says to continue editing a message already
7732 being composed. Interactively, CONTINUE is the prefix argument.
7734 SWITCH-FUNCTION, if non-nil, is a function to use to
7735 switch to and display the buffer used for mail composition.
7737 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7738 to insert the raw text of the message being replied to.
7739 It has the form (FUNCTION . ARGS). The user agent will apply
7740 FUNCTION to ARGS, to insert the raw text of the original message.
7741 \(The user agent will also run `mail-citation-hook', *after* the
7742 original text has been inserted in this way.)
7744 SEND-ACTIONS is a list of actions to call when the message is sent.
7745 Each action has the form (FUNCTION . ARGS).
7747 RETURN-ACTION, if non-nil, is an action for returning to the
7748 caller. It has the form (FUNCTION . ARGS). The function is
7749 called after the mail has been sent or put aside, and the mail
7750 buffer buried."
7751 (interactive
7752 (list nil nil nil current-prefix-arg))
7754 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7755 ;; from sendmail-user-agent to message-user-agent. Some users may
7756 ;; encounter incompatibilities. This hack tries to detect problems
7757 ;; and warn about them.
7758 (and compose-mail-user-agent-warnings
7759 (eq mail-user-agent 'message-user-agent)
7760 (let (warn-vars)
7761 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7762 mail-yank-hooks mail-archive-file-name
7763 mail-default-reply-to mail-mailing-lists
7764 mail-self-blind))
7765 (and (boundp var)
7766 (symbol-value var)
7767 (push var warn-vars)))
7768 (when warn-vars
7769 (display-warning 'mail
7770 (format-message "\
7771 The default mail mode is now Message mode.
7772 You have the following Mail mode variable%s customized:
7773 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7774 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7775 (if (> (length warn-vars) 1) "s" "")
7776 (mapconcat 'symbol-name
7777 warn-vars " "))))))
7779 (let ((function (get mail-user-agent 'composefunc)))
7780 (funcall function to subject other-headers continue switch-function
7781 yank-action send-actions return-action)))
7783 (defun compose-mail-other-window (&optional to subject other-headers continue
7784 yank-action send-actions
7785 return-action)
7786 "Like \\[compose-mail], but edit the outgoing message in another window."
7787 (interactive (list nil nil nil current-prefix-arg))
7788 (compose-mail to subject other-headers continue
7789 'switch-to-buffer-other-window yank-action send-actions
7790 return-action))
7792 (defun compose-mail-other-frame (&optional to subject other-headers continue
7793 yank-action send-actions
7794 return-action)
7795 "Like \\[compose-mail], but edit the outgoing message in another frame."
7796 (interactive (list nil nil nil current-prefix-arg))
7797 (compose-mail to subject other-headers continue
7798 'switch-to-buffer-other-frame yank-action send-actions
7799 return-action))
7802 (defvar set-variable-value-history nil
7803 "History of values entered with `set-variable'.
7805 Maximum length of the history list is determined by the value
7806 of `history-length', which see.")
7808 (defun set-variable (variable value &optional make-local)
7809 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7810 VARIABLE should be a user option variable name, a Lisp variable
7811 meant to be customized by users. You should enter VALUE in Lisp syntax,
7812 so if you want VALUE to be a string, you must surround it with doublequotes.
7813 VALUE is used literally, not evaluated.
7815 If VARIABLE has a `variable-interactive' property, that is used as if
7816 it were the arg to `interactive' (which see) to interactively read VALUE.
7818 If VARIABLE has been defined with `defcustom', then the type information
7819 in the definition is used to check that VALUE is valid.
7821 Note that this function is at heart equivalent to the basic `set' function.
7822 For a variable defined with `defcustom', it does not pay attention to
7823 any :set property that the variable might have (if you want that, use
7824 \\[customize-set-variable] instead).
7826 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7827 (interactive
7828 (let* ((default-var (variable-at-point))
7829 (var (if (custom-variable-p default-var)
7830 (read-variable (format "Set variable (default %s): " default-var)
7831 default-var)
7832 (read-variable "Set variable: ")))
7833 (minibuffer-help-form '(describe-variable var))
7834 (prop (get var 'variable-interactive))
7835 (obsolete (car (get var 'byte-obsolete-variable)))
7836 (prompt (format "Set %s %s to value: " var
7837 (cond ((local-variable-p var)
7838 "(buffer-local)")
7839 ((or current-prefix-arg
7840 (local-variable-if-set-p var))
7841 "buffer-locally")
7842 (t "globally"))))
7843 (val (progn
7844 (when obsolete
7845 (message (concat "`%S' is obsolete; "
7846 (if (symbolp obsolete) "use `%S' instead" "%s"))
7847 var obsolete)
7848 (sit-for 3))
7849 (if prop
7850 ;; Use VAR's `variable-interactive' property
7851 ;; as an interactive spec for prompting.
7852 (call-interactively `(lambda (arg)
7853 (interactive ,prop)
7854 arg))
7855 (read-from-minibuffer prompt nil
7856 read-expression-map t
7857 'set-variable-value-history
7858 (format "%S" (symbol-value var)))))))
7859 (list var val current-prefix-arg)))
7861 (and (custom-variable-p variable)
7862 (not (get variable 'custom-type))
7863 (custom-load-symbol variable))
7864 (let ((type (get variable 'custom-type)))
7865 (when type
7866 ;; Match with custom type.
7867 (require 'cus-edit)
7868 (setq type (widget-convert type))
7869 (unless (widget-apply type :match value)
7870 (user-error "Value `%S' does not match type %S of %S"
7871 value (car type) variable))))
7873 (if make-local
7874 (make-local-variable variable))
7876 (set variable value)
7878 ;; Force a thorough redisplay for the case that the variable
7879 ;; has an effect on the display, like `tab-width' has.
7880 (force-mode-line-update))
7882 ;; Define the major mode for lists of completions.
7884 (defvar completion-list-mode-map
7885 (let ((map (make-sparse-keymap)))
7886 (define-key map [mouse-2] 'choose-completion)
7887 (define-key map [follow-link] 'mouse-face)
7888 (define-key map [down-mouse-2] nil)
7889 (define-key map "\C-m" 'choose-completion)
7890 (define-key map "\e\e\e" 'delete-completion-window)
7891 (define-key map [left] 'previous-completion)
7892 (define-key map [right] 'next-completion)
7893 (define-key map [?\t] 'next-completion)
7894 (define-key map [backtab] 'previous-completion)
7895 (define-key map "q" 'quit-window)
7896 (define-key map "z" 'kill-this-buffer)
7897 map)
7898 "Local map for completion list buffers.")
7900 ;; Completion mode is suitable only for specially formatted data.
7901 (put 'completion-list-mode 'mode-class 'special)
7903 (defvar completion-reference-buffer nil
7904 "Record the buffer that was current when the completion list was requested.
7905 This is a local variable in the completion list buffer.
7906 Initial value is nil to avoid some compiler warnings.")
7908 (defvar completion-no-auto-exit nil
7909 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7910 This also applies to other functions such as `choose-completion'.")
7912 (defvar completion-base-position nil
7913 "Position of the base of the text corresponding to the shown completions.
7914 This variable is used in the *Completions* buffers.
7915 Its value is a list of the form (START END) where START is the place
7916 where the completion should be inserted and END (if non-nil) is the end
7917 of the text to replace. If END is nil, point is used instead.")
7919 (defvar completion-list-insert-choice-function #'completion--replace
7920 "Function to use to insert the text chosen in *Completions*.
7921 Called with three arguments (BEG END TEXT), it should replace the text
7922 between BEG and END with TEXT. Expected to be set buffer-locally
7923 in the *Completions* buffer.")
7925 (defvar completion-base-size nil
7926 "Number of chars before point not involved in completion.
7927 This is a local variable in the completion list buffer.
7928 It refers to the chars in the minibuffer if completing in the
7929 minibuffer, or in `completion-reference-buffer' otherwise.
7930 Only characters in the field at point are included.
7932 If nil, Emacs determines which part of the tail end of the
7933 buffer's text is involved in completion by comparing the text
7934 directly.")
7935 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7937 (defun delete-completion-window ()
7938 "Delete the completion list window.
7939 Go to the window from which completion was requested."
7940 (interactive)
7941 (let ((buf completion-reference-buffer))
7942 (if (one-window-p t)
7943 (if (window-dedicated-p) (delete-frame))
7944 (delete-window (selected-window))
7945 (if (get-buffer-window buf)
7946 (select-window (get-buffer-window buf))))))
7948 (defun previous-completion (n)
7949 "Move to the previous item in the completion list."
7950 (interactive "p")
7951 (next-completion (- n)))
7953 (defun next-completion (n)
7954 "Move to the next item in the completion list.
7955 With prefix argument N, move N items (negative N means move backward)."
7956 (interactive "p")
7957 (let ((beg (point-min)) (end (point-max)))
7958 (while (and (> n 0) (not (eobp)))
7959 ;; If in a completion, move to the end of it.
7960 (when (get-text-property (point) 'mouse-face)
7961 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7962 ;; Move to start of next one.
7963 (unless (get-text-property (point) 'mouse-face)
7964 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7965 (setq n (1- n)))
7966 (while (and (< n 0) (not (bobp)))
7967 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7968 ;; If in a completion, move to the start of it.
7969 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7970 (goto-char (previous-single-property-change
7971 (point) 'mouse-face nil beg)))
7972 ;; Move to end of the previous completion.
7973 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7974 (goto-char (previous-single-property-change
7975 (point) 'mouse-face nil beg)))
7976 ;; Move to the start of that one.
7977 (goto-char (previous-single-property-change
7978 (point) 'mouse-face nil beg))
7979 (setq n (1+ n))))))
7981 (defun choose-completion (&optional event)
7982 "Choose the completion at point.
7983 If EVENT, use EVENT's position to determine the starting position."
7984 (interactive (list last-nonmenu-event))
7985 ;; In case this is run via the mouse, give temporary modes such as
7986 ;; isearch a chance to turn off.
7987 (run-hooks 'mouse-leave-buffer-hook)
7988 (with-current-buffer (window-buffer (posn-window (event-start event)))
7989 (let ((buffer completion-reference-buffer)
7990 (base-size completion-base-size)
7991 (base-position completion-base-position)
7992 (insert-function completion-list-insert-choice-function)
7993 (choice
7994 (save-excursion
7995 (goto-char (posn-point (event-start event)))
7996 (let (beg end)
7997 (cond
7998 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7999 (setq end (point) beg (1+ (point))))
8000 ((and (not (bobp))
8001 (get-text-property (1- (point)) 'mouse-face))
8002 (setq end (1- (point)) beg (point)))
8003 (t (error "No completion here")))
8004 (setq beg (previous-single-property-change beg 'mouse-face))
8005 (setq end (or (next-single-property-change end 'mouse-face)
8006 (point-max)))
8007 (buffer-substring-no-properties beg end)))))
8009 (unless (buffer-live-p buffer)
8010 (error "Destination buffer is dead"))
8011 (quit-window nil (posn-window (event-start event)))
8013 (with-current-buffer buffer
8014 (choose-completion-string
8015 choice buffer
8016 (or base-position
8017 (when base-size
8018 ;; Someone's using old completion code that doesn't know
8019 ;; about base-position yet.
8020 (list (+ base-size (field-beginning))))
8021 ;; If all else fails, just guess.
8022 (list (choose-completion-guess-base-position choice)))
8023 insert-function)))))
8025 ;; Delete the longest partial match for STRING
8026 ;; that can be found before POINT.
8027 (defun choose-completion-guess-base-position (string)
8028 (save-excursion
8029 (let ((opoint (point))
8030 len)
8031 ;; Try moving back by the length of the string.
8032 (goto-char (max (- (point) (length string))
8033 (minibuffer-prompt-end)))
8034 ;; See how far back we were actually able to move. That is the
8035 ;; upper bound on how much we can match and delete.
8036 (setq len (- opoint (point)))
8037 (if completion-ignore-case
8038 (setq string (downcase string)))
8039 (while (and (> len 0)
8040 (let ((tail (buffer-substring (point) opoint)))
8041 (if completion-ignore-case
8042 (setq tail (downcase tail)))
8043 (not (string= tail (substring string 0 len)))))
8044 (setq len (1- len))
8045 (forward-char 1))
8046 (point))))
8048 (defun choose-completion-delete-max-match (string)
8049 (declare (obsolete choose-completion-guess-base-position "23.2"))
8050 (delete-region (choose-completion-guess-base-position string) (point)))
8052 (defvar choose-completion-string-functions nil
8053 "Functions that may override the normal insertion of a completion choice.
8054 These functions are called in order with three arguments:
8055 CHOICE - the string to insert in the buffer,
8056 BUFFER - the buffer in which the choice should be inserted,
8057 BASE-POSITION - where to insert the completion.
8059 If a function in the list returns non-nil, that function is supposed
8060 to have inserted the CHOICE in the BUFFER, and possibly exited
8061 the minibuffer; no further functions will be called.
8063 If all functions in the list return nil, that means to use
8064 the default method of inserting the completion in BUFFER.")
8066 (defun choose-completion-string (choice &optional
8067 buffer base-position insert-function)
8068 "Switch to BUFFER and insert the completion choice CHOICE.
8069 BASE-POSITION says where to insert the completion.
8070 INSERT-FUNCTION says how to insert the completion and falls
8071 back on `completion-list-insert-choice-function' when nil."
8073 ;; If BUFFER is the minibuffer, exit the minibuffer
8074 ;; unless it is reading a file name and CHOICE is a directory,
8075 ;; or completion-no-auto-exit is non-nil.
8077 ;; Some older code may call us passing `base-size' instead of
8078 ;; `base-position'. It's difficult to make any use of `base-size',
8079 ;; so we just ignore it.
8080 (unless (consp base-position)
8081 (message "Obsolete `base-size' passed to choose-completion-string")
8082 (setq base-position nil))
8084 (let* ((buffer (or buffer completion-reference-buffer))
8085 (mini-p (minibufferp buffer)))
8086 ;; If BUFFER is a minibuffer, barf unless it's the currently
8087 ;; active minibuffer.
8088 (if (and mini-p
8089 (not (and (active-minibuffer-window)
8090 (equal buffer
8091 (window-buffer (active-minibuffer-window))))))
8092 (error "Minibuffer is not active for completion")
8093 ;; Set buffer so buffer-local choose-completion-string-functions works.
8094 (set-buffer buffer)
8095 (unless (run-hook-with-args-until-success
8096 'choose-completion-string-functions
8097 ;; The fourth arg used to be `mini-p' but was useless
8098 ;; (since minibufferp can be used on the `buffer' arg)
8099 ;; and indeed unused. The last used to be `base-size', so we
8100 ;; keep it to try and avoid breaking old code.
8101 choice buffer base-position nil)
8102 ;; This remove-text-properties should be unnecessary since `choice'
8103 ;; comes from buffer-substring-no-properties.
8104 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8105 ;; Insert the completion into the buffer where it was requested.
8106 (funcall (or insert-function completion-list-insert-choice-function)
8107 (or (car base-position) (point))
8108 (or (cadr base-position) (point))
8109 choice)
8110 ;; Update point in the window that BUFFER is showing in.
8111 (let ((window (get-buffer-window buffer t)))
8112 (set-window-point window (point)))
8113 ;; If completing for the minibuffer, exit it with this choice.
8114 (and (not completion-no-auto-exit)
8115 (minibufferp buffer)
8116 minibuffer-completion-table
8117 ;; If this is reading a file name, and the file name chosen
8118 ;; is a directory, don't exit the minibuffer.
8119 (let* ((result (buffer-substring (field-beginning) (point)))
8120 (bounds
8121 (completion-boundaries result minibuffer-completion-table
8122 minibuffer-completion-predicate
8123 "")))
8124 (if (eq (car bounds) (length result))
8125 ;; The completion chosen leads to a new set of completions
8126 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8127 (let ((mini (active-minibuffer-window)))
8128 (select-window mini)
8129 (when minibuffer-auto-raise
8130 (raise-frame (window-frame mini))))
8131 (exit-minibuffer))))))))
8133 (define-derived-mode completion-list-mode nil "Completion List"
8134 "Major mode for buffers showing lists of possible completions.
8135 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8136 to select the completion near point.
8137 Or click to select one with the mouse.
8139 \\{completion-list-mode-map}"
8140 (set (make-local-variable 'completion-base-size) nil))
8142 (defun completion-list-mode-finish ()
8143 "Finish setup of the completions buffer.
8144 Called from `temp-buffer-show-hook'."
8145 (when (eq major-mode 'completion-list-mode)
8146 (setq buffer-read-only t)))
8148 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8151 ;; Variables and faces used in `completion-setup-function'.
8153 (defcustom completion-show-help t
8154 "Non-nil means show help message in *Completions* buffer."
8155 :type 'boolean
8156 :version "22.1"
8157 :group 'completion)
8159 ;; This function goes in completion-setup-hook, so that it is called
8160 ;; after the text of the completion list buffer is written.
8161 (defun completion-setup-function ()
8162 (let* ((mainbuf (current-buffer))
8163 (base-dir
8164 ;; FIXME: This is a bad hack. We try to set the default-directory
8165 ;; in the *Completions* buffer so that the relative file names
8166 ;; displayed there can be treated as valid file names, independently
8167 ;; from the completion context. But this suffers from many problems:
8168 ;; - It's not clear when the completions are file names. With some
8169 ;; completion tables (e.g. bzr revision specs), the listed
8170 ;; completions can mix file names and other things.
8171 ;; - It doesn't pay attention to possible quoting.
8172 ;; - With fancy completion styles, the code below will not always
8173 ;; find the right base directory.
8174 (if minibuffer-completing-file-name
8175 (file-name-as-directory
8176 (expand-file-name
8177 (buffer-substring (minibuffer-prompt-end)
8178 (- (point) (or completion-base-size 0))))))))
8179 (with-current-buffer standard-output
8180 (let ((base-size completion-base-size) ;Read before killing localvars.
8181 (base-position completion-base-position)
8182 (insert-fun completion-list-insert-choice-function))
8183 (completion-list-mode)
8184 (set (make-local-variable 'completion-base-size) base-size)
8185 (set (make-local-variable 'completion-base-position) base-position)
8186 (set (make-local-variable 'completion-list-insert-choice-function)
8187 insert-fun))
8188 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8189 (if base-dir (setq default-directory base-dir))
8190 ;; Maybe insert help string.
8191 (when completion-show-help
8192 (goto-char (point-min))
8193 (if (display-mouse-p)
8194 (insert "Click on a completion to select it.\n"))
8195 (insert (substitute-command-keys
8196 "In this buffer, type \\[choose-completion] to \
8197 select the completion near point.\n\n"))))))
8199 (add-hook 'completion-setup-hook 'completion-setup-function)
8201 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8202 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8204 (defun switch-to-completions ()
8205 "Select the completion list window."
8206 (interactive)
8207 (let ((window (or (get-buffer-window "*Completions*" 0)
8208 ;; Make sure we have a completions window.
8209 (progn (minibuffer-completion-help)
8210 (get-buffer-window "*Completions*" 0)))))
8211 (when window
8212 (select-window window)
8213 ;; In the new buffer, go to the first completion.
8214 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8215 (when (bobp)
8216 (next-completion 1)))))
8218 ;;; Support keyboard commands to turn on various modifiers.
8220 ;; These functions -- which are not commands -- each add one modifier
8221 ;; to the following event.
8223 (defun event-apply-alt-modifier (_ignore-prompt)
8224 "\\<function-key-map>Add the Alt modifier to the following event.
8225 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8226 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8227 (defun event-apply-super-modifier (_ignore-prompt)
8228 "\\<function-key-map>Add the Super modifier to the following event.
8229 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8230 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8231 (defun event-apply-hyper-modifier (_ignore-prompt)
8232 "\\<function-key-map>Add the Hyper modifier to the following event.
8233 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8234 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8235 (defun event-apply-shift-modifier (_ignore-prompt)
8236 "\\<function-key-map>Add the Shift modifier to the following event.
8237 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8238 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8239 (defun event-apply-control-modifier (_ignore-prompt)
8240 "\\<function-key-map>Add the Ctrl modifier to the following event.
8241 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8242 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8243 (defun event-apply-meta-modifier (_ignore-prompt)
8244 "\\<function-key-map>Add the Meta modifier to the following event.
8245 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8246 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8248 (defun event-apply-modifier (event symbol lshiftby prefix)
8249 "Apply a modifier flag to event EVENT.
8250 SYMBOL is the name of this modifier, as a symbol.
8251 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8252 PREFIX is the string that represents this modifier in an event type symbol."
8253 (if (numberp event)
8254 (cond ((eq symbol 'control)
8255 (if (and (<= (downcase event) ?z)
8256 (>= (downcase event) ?a))
8257 (- (downcase event) ?a -1)
8258 (if (and (<= (downcase event) ?Z)
8259 (>= (downcase event) ?A))
8260 (- (downcase event) ?A -1)
8261 (logior (lsh 1 lshiftby) event))))
8262 ((eq symbol 'shift)
8263 (if (and (<= (downcase event) ?z)
8264 (>= (downcase event) ?a))
8265 (upcase event)
8266 (logior (lsh 1 lshiftby) event)))
8268 (logior (lsh 1 lshiftby) event)))
8269 (if (memq symbol (event-modifiers event))
8270 event
8271 (let ((event-type (if (symbolp event) event (car event))))
8272 (setq event-type (intern (concat prefix (symbol-name event-type))))
8273 (if (symbolp event)
8274 event-type
8275 (cons event-type (cdr event)))))))
8277 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8278 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8279 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8280 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8281 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8282 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8284 ;;;; Keypad support.
8286 ;; Make the keypad keys act like ordinary typing keys. If people add
8287 ;; bindings for the function key symbols, then those bindings will
8288 ;; override these, so this shouldn't interfere with any existing
8289 ;; bindings.
8291 ;; Also tell read-char how to handle these keys.
8292 (mapc
8293 (lambda (keypad-normal)
8294 (let ((keypad (nth 0 keypad-normal))
8295 (normal (nth 1 keypad-normal)))
8296 (put keypad 'ascii-character normal)
8297 (define-key function-key-map (vector keypad) (vector normal))))
8298 ;; See also kp-keys bound in bindings.el.
8299 '((kp-space ?\s)
8300 (kp-tab ?\t)
8301 (kp-enter ?\r)
8302 (kp-separator ?,)
8303 (kp-equal ?=)
8304 ;; Do the same for various keys that are represented as symbols under
8305 ;; GUIs but naturally correspond to characters.
8306 (backspace 127)
8307 (delete 127)
8308 (tab ?\t)
8309 (linefeed ?\n)
8310 (clear ?\C-l)
8311 (return ?\C-m)
8312 (escape ?\e)
8315 ;;;;
8316 ;;;; forking a twin copy of a buffer.
8317 ;;;;
8319 (defvar clone-buffer-hook nil
8320 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8322 (defvar clone-indirect-buffer-hook nil
8323 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8325 (defun clone-process (process &optional newname)
8326 "Create a twin copy of PROCESS.
8327 If NEWNAME is nil, it defaults to PROCESS' name;
8328 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8329 If PROCESS is associated with a buffer, the new process will be associated
8330 with the current buffer instead.
8331 Returns nil if PROCESS has already terminated."
8332 (setq newname (or newname (process-name process)))
8333 (if (string-match "<[0-9]+>\\'" newname)
8334 (setq newname (substring newname 0 (match-beginning 0))))
8335 (when (memq (process-status process) '(run stop open))
8336 (let* ((process-connection-type (process-tty-name process))
8337 (new-process
8338 (if (memq (process-status process) '(open))
8339 (let ((args (process-contact process t)))
8340 (setq args (plist-put args :name newname))
8341 (setq args (plist-put args :buffer
8342 (if (process-buffer process)
8343 (current-buffer))))
8344 (apply 'make-network-process args))
8345 (apply 'start-process newname
8346 (if (process-buffer process) (current-buffer))
8347 (process-command process)))))
8348 (set-process-query-on-exit-flag
8349 new-process (process-query-on-exit-flag process))
8350 (set-process-inherit-coding-system-flag
8351 new-process (process-inherit-coding-system-flag process))
8352 (set-process-filter new-process (process-filter process))
8353 (set-process-sentinel new-process (process-sentinel process))
8354 (set-process-plist new-process (copy-sequence (process-plist process)))
8355 new-process)))
8357 ;; things to maybe add (currently partly covered by `funcall mode'):
8358 ;; - syntax-table
8359 ;; - overlays
8360 (defun clone-buffer (&optional newname display-flag)
8361 "Create and return a twin copy of the current buffer.
8362 Unlike an indirect buffer, the new buffer can be edited
8363 independently of the old one (if it is not read-only).
8364 NEWNAME is the name of the new buffer. It may be modified by
8365 adding or incrementing <N> at the end as necessary to create a
8366 unique buffer name. If nil, it defaults to the name of the
8367 current buffer, with the proper suffix. If DISPLAY-FLAG is
8368 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8369 clone a file-visiting buffer, or a buffer whose major mode symbol
8370 has a non-nil `no-clone' property, results in an error.
8372 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8373 current buffer with appropriate suffix. However, if a prefix
8374 argument is given, then the command prompts for NEWNAME in the
8375 minibuffer.
8377 This runs the normal hook `clone-buffer-hook' in the new buffer
8378 after it has been set up properly in other respects."
8379 (interactive
8380 (progn
8381 (if buffer-file-name
8382 (error "Cannot clone a file-visiting buffer"))
8383 (if (get major-mode 'no-clone)
8384 (error "Cannot clone a buffer in %s mode" mode-name))
8385 (list (if current-prefix-arg
8386 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8387 t)))
8388 (if buffer-file-name
8389 (error "Cannot clone a file-visiting buffer"))
8390 (if (get major-mode 'no-clone)
8391 (error "Cannot clone a buffer in %s mode" mode-name))
8392 (setq newname (or newname (buffer-name)))
8393 (if (string-match "<[0-9]+>\\'" newname)
8394 (setq newname (substring newname 0 (match-beginning 0))))
8395 (let ((buf (current-buffer))
8396 (ptmin (point-min))
8397 (ptmax (point-max))
8398 (pt (point))
8399 (mk (if mark-active (mark t)))
8400 (modified (buffer-modified-p))
8401 (mode major-mode)
8402 (lvars (buffer-local-variables))
8403 (process (get-buffer-process (current-buffer)))
8404 (new (generate-new-buffer (or newname (buffer-name)))))
8405 (save-restriction
8406 (widen)
8407 (with-current-buffer new
8408 (insert-buffer-substring buf)))
8409 (with-current-buffer new
8410 (narrow-to-region ptmin ptmax)
8411 (goto-char pt)
8412 (if mk (set-mark mk))
8413 (set-buffer-modified-p modified)
8415 ;; Clone the old buffer's process, if any.
8416 (when process (clone-process process))
8418 ;; Now set up the major mode.
8419 (funcall mode)
8421 ;; Set up other local variables.
8422 (mapc (lambda (v)
8423 (condition-case () ;in case var is read-only
8424 (if (symbolp v)
8425 (makunbound v)
8426 (set (make-local-variable (car v)) (cdr v)))
8427 (error nil)))
8428 lvars)
8430 ;; Run any hooks (typically set up by the major mode
8431 ;; for cloning to work properly).
8432 (run-hooks 'clone-buffer-hook))
8433 (if display-flag
8434 ;; Presumably the current buffer is shown in the selected frame, so
8435 ;; we want to display the clone elsewhere.
8436 (let ((same-window-regexps nil)
8437 (same-window-buffer-names))
8438 (pop-to-buffer new)))
8439 new))
8442 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8443 "Create an indirect buffer that is a twin copy of the current buffer.
8445 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8446 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8447 or if not called with a prefix arg, NEWNAME defaults to the current
8448 buffer's name. The name is modified by adding a `<N>' suffix to it
8449 or by incrementing the N in an existing suffix. Trying to clone a
8450 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8451 property results in an error.
8453 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8454 This is always done when called interactively.
8456 Optional third arg NORECORD non-nil means do not put this buffer at the
8457 front of the list of recently selected ones.
8459 Returns the newly created indirect buffer."
8460 (interactive
8461 (progn
8462 (if (get major-mode 'no-clone-indirect)
8463 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8464 (list (if current-prefix-arg
8465 (read-buffer "Name of indirect buffer: " (current-buffer)))
8466 t)))
8467 (if (get major-mode 'no-clone-indirect)
8468 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8469 (setq newname (or newname (buffer-name)))
8470 (if (string-match "<[0-9]+>\\'" newname)
8471 (setq newname (substring newname 0 (match-beginning 0))))
8472 (let* ((name (generate-new-buffer-name newname))
8473 (buffer (make-indirect-buffer (current-buffer) name t)))
8474 (with-current-buffer buffer
8475 (run-hooks 'clone-indirect-buffer-hook))
8476 (when display-flag
8477 (pop-to-buffer buffer nil norecord))
8478 buffer))
8481 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8482 "Like `clone-indirect-buffer' but display in another window."
8483 (interactive
8484 (progn
8485 (if (get major-mode 'no-clone-indirect)
8486 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8487 (list (if current-prefix-arg
8488 (read-buffer "Name of indirect buffer: " (current-buffer)))
8489 t)))
8490 (let ((pop-up-windows t))
8491 (clone-indirect-buffer newname display-flag norecord)))
8494 ;;; Handling of Backspace and Delete keys.
8496 (defcustom normal-erase-is-backspace 'maybe
8497 "Set the default behavior of the Delete and Backspace keys.
8499 If set to t, Delete key deletes forward and Backspace key deletes
8500 backward.
8502 If set to nil, both Delete and Backspace keys delete backward.
8504 If set to `maybe' (which is the default), Emacs automatically
8505 selects a behavior. On window systems, the behavior depends on
8506 the keyboard used. If the keyboard has both a Backspace key and
8507 a Delete key, and both are mapped to their usual meanings, the
8508 option's default value is set to t, so that Backspace can be used
8509 to delete backward, and Delete can be used to delete forward.
8511 If not running under a window system, customizing this option
8512 accomplishes a similar effect by mapping C-h, which is usually
8513 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8514 via `keyboard-translate'. The former functionality of C-h is
8515 available on the F1 key. You should probably not use this
8516 setting if you don't have both Backspace, Delete and F1 keys.
8518 Setting this variable with setq doesn't take effect. Programmatically,
8519 call `normal-erase-is-backspace-mode' (which see) instead."
8520 :type '(choice (const :tag "Off" nil)
8521 (const :tag "Maybe" maybe)
8522 (other :tag "On" t))
8523 :group 'editing-basics
8524 :version "21.1"
8525 :set (lambda (symbol value)
8526 ;; The fboundp is because of a problem with :set when
8527 ;; dumping Emacs. It doesn't really matter.
8528 (if (fboundp 'normal-erase-is-backspace-mode)
8529 (normal-erase-is-backspace-mode (or value 0))
8530 (set-default symbol value))))
8532 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8533 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8534 (unless frame (setq frame (selected-frame)))
8535 (with-selected-frame frame
8536 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8537 (normal-erase-is-backspace-mode
8538 (if (if (eq normal-erase-is-backspace 'maybe)
8539 (and (not noninteractive)
8540 (or (memq system-type '(ms-dos windows-nt))
8541 (memq window-system '(w32 ns))
8542 (and (memq window-system '(x))
8543 (fboundp 'x-backspace-delete-keys-p)
8544 (x-backspace-delete-keys-p))
8545 ;; If the terminal Emacs is running on has erase char
8546 ;; set to ^H, use the Backspace key for deleting
8547 ;; backward, and the Delete key for deleting forward.
8548 (and (null window-system)
8549 (eq tty-erase-char ?\^H))))
8550 normal-erase-is-backspace)
8551 1 0)))))
8553 (define-minor-mode normal-erase-is-backspace-mode
8554 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8555 With a prefix argument ARG, enable this feature if ARG is
8556 positive, and disable it otherwise. If called from Lisp, enable
8557 the mode if ARG is omitted or nil.
8559 On window systems, when this mode is on, Delete is mapped to C-d
8560 and Backspace is mapped to DEL; when this mode is off, both
8561 Delete and Backspace are mapped to DEL. (The remapping goes via
8562 `local-function-key-map', so binding Delete or Backspace in the
8563 global or local keymap will override that.)
8565 In addition, on window systems, the bindings of C-Delete, M-Delete,
8566 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8567 the global keymap in accordance with the functionality of Delete and
8568 Backspace. For example, if Delete is remapped to C-d, which deletes
8569 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8570 to DEL, which deletes backward, C-Delete is bound to
8571 `backward-kill-word'.
8573 If not running on a window system, a similar effect is accomplished by
8574 remapping C-h (normally produced by the Backspace key) and DEL via
8575 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8576 to C-d; if it's off, the keys are not remapped.
8578 When not running on a window system, and this mode is turned on, the
8579 former functionality of C-h is available on the F1 key. You should
8580 probably not turn on this mode on a text-only terminal if you don't
8581 have both Backspace, Delete and F1 keys.
8583 See also `normal-erase-is-backspace'."
8584 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8585 . (lambda (v)
8586 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8587 (if v 1 0))))
8588 (let ((enabled (eq 1 (terminal-parameter
8589 nil 'normal-erase-is-backspace))))
8591 (cond ((or (memq window-system '(x w32 ns pc))
8592 (memq system-type '(ms-dos windows-nt)))
8593 (let ((bindings
8594 `(([M-delete] [M-backspace])
8595 ([C-M-delete] [C-M-backspace])
8596 ([?\e C-delete] [?\e C-backspace]))))
8598 (if enabled
8599 (progn
8600 (define-key local-function-key-map [delete] [deletechar])
8601 (define-key local-function-key-map [kp-delete] [deletechar])
8602 (define-key local-function-key-map [backspace] [?\C-?])
8603 (dolist (b bindings)
8604 ;; Not sure if input-decode-map is really right, but
8605 ;; keyboard-translate-table (used below) only works
8606 ;; for integer events, and key-translation-table is
8607 ;; global (like the global-map, used earlier).
8608 (define-key input-decode-map (car b) nil)
8609 (define-key input-decode-map (cadr b) nil)))
8610 (define-key local-function-key-map [delete] [?\C-?])
8611 (define-key local-function-key-map [kp-delete] [?\C-?])
8612 (define-key local-function-key-map [backspace] [?\C-?])
8613 (dolist (b bindings)
8614 (define-key input-decode-map (car b) (cadr b))
8615 (define-key input-decode-map (cadr b) (car b))))))
8617 (if enabled
8618 (progn
8619 (keyboard-translate ?\C-h ?\C-?)
8620 (keyboard-translate ?\C-? ?\C-d))
8621 (keyboard-translate ?\C-h ?\C-h)
8622 (keyboard-translate ?\C-? ?\C-?))))
8624 (if (called-interactively-p 'interactive)
8625 (message "Delete key deletes %s"
8626 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8627 "forward" "backward")))))
8629 (defvar vis-mode-saved-buffer-invisibility-spec nil
8630 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8632 (define-minor-mode read-only-mode
8633 "Change whether the current buffer is read-only.
8634 With prefix argument ARG, make the buffer read-only if ARG is
8635 positive, otherwise make it writable. If buffer is read-only
8636 and `view-read-only' is non-nil, enter view mode.
8638 Do not call this from a Lisp program unless you really intend to
8639 do the same thing as the \\[read-only-mode] command, including
8640 possibly enabling or disabling View mode. Also, note that this
8641 command works by setting the variable `buffer-read-only', which
8642 does not affect read-only regions caused by text properties. To
8643 ignore read-only status in a Lisp program (whether due to text
8644 properties or buffer state), bind `inhibit-read-only' temporarily
8645 to a non-nil value."
8646 :variable buffer-read-only
8647 (cond
8648 ((and (not buffer-read-only) view-mode)
8649 (View-exit-and-edit)
8650 (make-local-variable 'view-read-only)
8651 (setq view-read-only t)) ; Must leave view mode.
8652 ((and buffer-read-only view-read-only
8653 ;; If view-mode is already active, `view-mode-enter' is a nop.
8654 (not view-mode)
8655 (not (eq (get major-mode 'mode-class) 'special)))
8656 (view-mode-enter))))
8658 (define-minor-mode visible-mode
8659 "Toggle making all invisible text temporarily visible (Visible mode).
8660 With a prefix argument ARG, enable Visible mode if ARG is
8661 positive, and disable it otherwise. If called from Lisp, enable
8662 the mode if ARG is omitted or nil.
8664 This mode works by saving the value of `buffer-invisibility-spec'
8665 and setting it to nil."
8666 :lighter " Vis"
8667 :group 'editing-basics
8668 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8669 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8670 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8671 (when visible-mode
8672 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8673 buffer-invisibility-spec)
8674 (setq buffer-invisibility-spec nil)))
8676 (defvar messages-buffer-mode-map
8677 (let ((map (make-sparse-keymap)))
8678 (set-keymap-parent map special-mode-map)
8679 (define-key map "g" nil) ; nothing to revert
8680 map))
8682 (define-derived-mode messages-buffer-mode special-mode "Messages"
8683 "Major mode used in the \"*Messages*\" buffer.")
8685 (defun messages-buffer ()
8686 "Return the \"*Messages*\" buffer.
8687 If it does not exist, create and it switch it to `messages-buffer-mode'."
8688 (or (get-buffer "*Messages*")
8689 (with-current-buffer (get-buffer-create "*Messages*")
8690 (messages-buffer-mode)
8691 (current-buffer))))
8694 ;; Minibuffer prompt stuff.
8696 ;;(defun minibuffer-prompt-modification (start end)
8697 ;; (error "You cannot modify the prompt"))
8700 ;;(defun minibuffer-prompt-insertion (start end)
8701 ;; (let ((inhibit-modification-hooks t))
8702 ;; (delete-region start end)
8703 ;; ;; Discard undo information for the text insertion itself
8704 ;; ;; and for the text deletion.above.
8705 ;; (when (consp buffer-undo-list)
8706 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8707 ;; (message "You cannot modify the prompt")))
8710 ;;(setq minibuffer-prompt-properties
8711 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8712 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8715 ;;;; Problematic external packages.
8717 ;; rms says this should be done by specifying symbols that define
8718 ;; versions together with bad values. This is therefore not as
8719 ;; flexible as it could be. See the thread:
8720 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8721 (defconst bad-packages-alist
8722 ;; Not sure exactly which semantic versions have problems.
8723 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8724 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8725 "The version of `semantic' loaded does not work in Emacs 22.
8726 It can cause constant high CPU load.
8727 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8728 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8729 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8730 ;; provided the `CUA-mode' feature. Since this is no longer true,
8731 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8732 (CUA-mode t nil
8733 "CUA-mode is now part of the standard GNU Emacs distribution,
8734 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8736 You have loaded an older version of CUA-mode which does not work
8737 correctly with this version of Emacs. You should remove the old
8738 version and use the one distributed with Emacs."))
8739 "Alist of packages known to cause problems in this version of Emacs.
8740 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8741 PACKAGE is either a regular expression to match file names, or a
8742 symbol (a feature name), like for `with-eval-after-load'.
8743 SYMBOL is either the name of a string variable, or t. Upon
8744 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8745 warning using STRING as the message.")
8747 (defun bad-package-check (package)
8748 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8749 (condition-case nil
8750 (let* ((list (assoc package bad-packages-alist))
8751 (symbol (nth 1 list)))
8752 (and list
8753 (boundp symbol)
8754 (or (eq symbol t)
8755 (and (stringp (setq symbol (eval symbol)))
8756 (string-match-p (nth 2 list) symbol)))
8757 (display-warning package (nth 3 list) :warning)))
8758 (error nil)))
8760 (dolist (elem bad-packages-alist)
8761 (let ((pkg (car elem)))
8762 (with-eval-after-load pkg
8763 (bad-package-check pkg))))
8766 ;;; Generic dispatcher commands
8768 ;; Macro `define-alternatives' is used to create generic commands.
8769 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8770 ;; that can have different alternative implementations where choosing
8771 ;; among them is exclusively a matter of user preference.
8773 ;; (define-alternatives COMMAND) creates a new interactive command
8774 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8775 ;; Typically, the user will not need to customize this variable; packages
8776 ;; wanting to add alternative implementations should use
8778 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8780 (defmacro define-alternatives (command &rest customizations)
8781 "Define the new command `COMMAND'.
8783 The argument `COMMAND' should be a symbol.
8785 Running `M-x COMMAND RET' for the first time prompts for which
8786 alternative to use and records the selected command as a custom
8787 variable.
8789 Running `C-u M-x COMMAND RET' prompts again for an alternative
8790 and overwrites the previous choice.
8792 The variable `COMMAND-alternatives' contains an alist with
8793 alternative implementations of COMMAND. `define-alternatives'
8794 does not have any effect until this variable is set.
8796 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8797 `defcustom' keywords and values to add to the declaration of
8798 `COMMAND-alternatives' (typically :group and :version)."
8799 (let* ((command-name (symbol-name command))
8800 (varalt-name (concat command-name "-alternatives"))
8801 (varalt-sym (intern varalt-name))
8802 (varimp-sym (intern (concat command-name "--implementation"))))
8803 `(progn
8805 (defcustom ,varalt-sym nil
8806 ,(format "Alist of alternative implementations for the `%s' command.
8808 Each entry must be a pair (ALTNAME . ALTFUN), where:
8809 ALTNAME - The name shown at user to describe the alternative implementation.
8810 ALTFUN - The function called to implement this alternative."
8811 command-name)
8812 :type '(alist :key-type string :value-type function)
8813 ,@customizations)
8815 (put ',varalt-sym 'definition-name ',command)
8816 (defvar ,varimp-sym nil "Internal use only.")
8818 (defun ,command (&optional arg)
8819 ,(format "Run generic command `%s'.
8820 If used for the first time, or with interactive ARG, ask the user which
8821 implementation to use for `%s'. The variable `%s'
8822 contains the list of implementations currently supported for this command."
8823 command-name command-name varalt-name)
8824 (interactive "P")
8825 (when (or arg (null ,varimp-sym))
8826 (let ((val (completing-read
8827 ,(format-message
8828 "Select implementation for command `%s': "
8829 command-name)
8830 ,varalt-sym nil t)))
8831 (unless (string-equal val "")
8832 (when (null ,varimp-sym)
8833 (message
8834 "Use C-u M-x %s RET`to select another implementation"
8835 ,command-name)
8836 (sit-for 3))
8837 (customize-save-variable ',varimp-sym
8838 (cdr (assoc-string val ,varalt-sym))))))
8839 (if ,varimp-sym
8840 (call-interactively ,varimp-sym)
8841 (message "%s" ,(format-message
8842 "No implementation selected for command `%s'"
8843 command-name)))))))
8846 ;;; Functions for changing capitalization that Do What I Mean
8847 (defun upcase-dwim (arg)
8848 "Upcase words in the region, if active; if not, upcase word at point.
8849 If the region is active, this function calls `upcase-region'.
8850 Otherwise, it calls `upcase-word', with prefix argument passed to it
8851 to upcase ARG words."
8852 (interactive "*p")
8853 (if (use-region-p)
8854 (upcase-region (region-beginning) (region-end))
8855 (upcase-word arg)))
8857 (defun downcase-dwim (arg)
8858 "Downcase words in the region, if active; if not, downcase word at point.
8859 If the region is active, this function calls `downcase-region'.
8860 Otherwise, it calls `downcase-word', with prefix argument passed to it
8861 to downcase ARG words."
8862 (interactive "*p")
8863 (if (use-region-p)
8864 (downcase-region (region-beginning) (region-end))
8865 (downcase-word arg)))
8867 (defun capitalize-dwim (arg)
8868 "Capitalize words in the region, if active; if not, capitalize word at point.
8869 If the region is active, this function calls `capitalize-region'.
8870 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8871 to capitalize ARG words."
8872 (interactive "*p")
8873 (if (use-region-p)
8874 (capitalize-region (region-beginning) (region-end))
8875 (capitalize-word arg)))
8879 (provide 'simple)
8881 ;;; simple.el ends here