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