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