Merge branch 'master' into comment-cache
[emacs.git] / lisp / simple.el
blob441713a18b859bd92b4e2c0668853f391ce693c2
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2017 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: internal
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
29 ;;; Code:
31 (eval-when-compile (require 'cl-lib))
33 (declare-function widget-convert "wid-edit" (type &rest args))
34 (declare-function shell-mode "shell" ())
36 ;;; From compile.el
37 (defvar compilation-current-error)
38 (defvar compilation-context-lines)
40 (defcustom shell-command-dont-erase-buffer nil
41 "If non-nil, output buffer is not erased between shell commands.
42 Also, a non-nil value set the point in the output buffer
43 once the command complete.
44 The value `beg-last-out' set point at the beginning of the output,
45 `end-last-out' set point at the end of the buffer, `save-point'
46 restore the buffer position before the command."
47 :type '(choice
48 (const :tag "Erase buffer" nil)
49 (const :tag "Set point to beginning of last output" beg-last-out)
50 (const :tag "Set point to end of last output" end-last-out)
51 (const :tag "Save point" save-point))
52 :group 'shell
53 :version "26.1")
55 (defvar shell-command-saved-pos nil
56 "Point position in the output buffer after command complete.
57 It is an alist (BUFFER . POS), where BUFFER is the output
58 buffer, and POS is the point position in BUFFER once the command finish.
59 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
61 (defcustom idle-update-delay 0.5
62 "Idle time delay before updating various things on the screen.
63 Various Emacs features that update auxiliary information when point moves
64 wait this many seconds after Emacs becomes idle before doing an update."
65 :type 'number
66 :group 'display
67 :version "22.1")
69 (defgroup killing nil
70 "Killing and yanking commands."
71 :group 'editing)
73 (defgroup paren-matching nil
74 "Highlight (un)matching of parens and expressions."
75 :group 'matching)
77 ;;; next-error support framework
79 (defgroup next-error nil
80 "`next-error' support framework."
81 :group 'compilation
82 :version "22.1")
84 (defface next-error
85 '((t (:inherit region)))
86 "Face used to highlight next error locus."
87 :group 'next-error
88 :version "22.1")
90 (defcustom next-error-highlight 0.5
91 "Highlighting of locations in selected source buffers.
92 If a number, highlight the locus in `next-error' face for the given time
93 in seconds, or until the next command is executed.
94 If t, highlight the locus until the next command is executed, or until
95 some other locus replaces it.
96 If nil, don't highlight the locus in the source buffer.
97 If `fringe-arrow', indicate the locus by the fringe arrow
98 indefinitely until some other locus replaces it."
99 :type '(choice (number :tag "Highlight for specified time")
100 (const :tag "Semipermanent highlighting" t)
101 (const :tag "No highlighting" nil)
102 (const :tag "Fringe arrow" fringe-arrow))
103 :group 'next-error
104 :version "22.1")
106 (defcustom next-error-highlight-no-select 0.5
107 "Highlighting of locations in `next-error-no-select'.
108 If number, highlight the locus in `next-error' face for given time in seconds.
109 If t, highlight the locus indefinitely until some other locus replaces it.
110 If nil, don't highlight the locus in the source buffer.
111 If `fringe-arrow', indicate the locus by the fringe arrow
112 indefinitely until some other locus replaces it."
113 :type '(choice (number :tag "Highlight for specified time")
114 (const :tag "Semipermanent highlighting" t)
115 (const :tag "No highlighting" nil)
116 (const :tag "Fringe arrow" fringe-arrow))
117 :group 'next-error
118 :version "22.1")
120 (defcustom next-error-recenter nil
121 "Display the line in the visited source file recentered as specified.
122 If non-nil, the value is passed directly to `recenter'."
123 :type '(choice (integer :tag "Line to recenter to")
124 (const :tag "Center of window" (4))
125 (const :tag "No recentering" nil))
126 :group 'next-error
127 :version "23.1")
129 (defcustom next-error-hook nil
130 "List of hook functions run by `next-error' after visiting source file."
131 :type 'hook
132 :group 'next-error)
134 (defvar next-error-highlight-timer nil)
136 (defvar next-error-overlay-arrow-position nil)
137 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
138 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
140 (defvar next-error-last-buffer nil
141 "The most recent `next-error' buffer.
142 A buffer becomes most recent when its compilation, grep, or
143 similar mode is started, or when it is used with \\[next-error]
144 or \\[compile-goto-error].")
146 (defvar next-error-function nil
147 "Function to use to find the next error in the current buffer.
148 The function is called with 2 parameters:
149 ARG is an integer specifying by how many errors to move.
150 RESET is a boolean which, if non-nil, says to go back to the beginning
151 of the errors before moving.
152 Major modes providing compile-like functionality should set this variable
153 to indicate to `next-error' that this is a candidate buffer and how
154 to navigate in it.")
155 (make-variable-buffer-local 'next-error-function)
157 (defvar next-error-move-function nil
158 "Function to use to move to an error locus.
159 It takes two arguments, a buffer position in the error buffer
160 and a buffer position in the error locus buffer.
161 The buffer for the error locus should already be current.
162 nil means use goto-char using the second argument position.")
163 (make-variable-buffer-local 'next-error-move-function)
165 (defsubst next-error-buffer-p (buffer
166 &optional avoid-current
167 extra-test-inclusive
168 extra-test-exclusive)
169 "Return non-nil if BUFFER is a `next-error' capable buffer.
170 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
171 return nil.
173 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
174 BUFFER would not normally qualify. If it returns non-nil, BUFFER
175 is considered `next-error' capable, anyway, and the function
176 returns non-nil.
178 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
179 buffer would normally qualify. If it returns nil, BUFFER is
180 rejected, and the function returns nil."
181 (and (buffer-name buffer) ;First make sure it's live.
182 (not (and avoid-current (eq buffer (current-buffer))))
183 (with-current-buffer buffer
184 (if next-error-function ; This is the normal test.
185 ;; Optionally reject some buffers.
186 (if extra-test-exclusive
187 (funcall extra-test-exclusive)
189 ;; Optionally accept some other buffers.
190 (and extra-test-inclusive
191 (funcall extra-test-inclusive))))))
193 (defun next-error-find-buffer (&optional avoid-current
194 extra-test-inclusive
195 extra-test-exclusive)
196 "Return a `next-error' capable buffer.
198 If AVOID-CURRENT is non-nil, treat the current buffer
199 as an absolute last resort only.
201 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
202 that normally would not qualify. If it returns t, the buffer
203 in question is treated as usable.
205 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
206 that would normally be considered usable. If it returns nil,
207 that buffer is rejected."
209 ;; 1. If one window on the selected frame displays such buffer, return it.
210 (let ((window-buffers
211 (delete-dups
212 (delq nil (mapcar (lambda (w)
213 (if (next-error-buffer-p
214 (window-buffer w)
215 avoid-current
216 extra-test-inclusive extra-test-exclusive)
217 (window-buffer w)))
218 (window-list))))))
219 (if (eq (length window-buffers) 1)
220 (car window-buffers)))
221 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
222 (if (and next-error-last-buffer
223 (next-error-buffer-p next-error-last-buffer avoid-current
224 extra-test-inclusive extra-test-exclusive))
225 next-error-last-buffer)
226 ;; 3. If the current buffer is acceptable, choose it.
227 (if (next-error-buffer-p (current-buffer) avoid-current
228 extra-test-inclusive extra-test-exclusive)
229 (current-buffer))
230 ;; 4. Look for any acceptable buffer.
231 (let ((buffers (buffer-list)))
232 (while (and buffers
233 (not (next-error-buffer-p
234 (car buffers) avoid-current
235 extra-test-inclusive extra-test-exclusive)))
236 (setq buffers (cdr buffers)))
237 (car buffers))
238 ;; 5. Use the current buffer as a last resort if it qualifies,
239 ;; even despite AVOID-CURRENT.
240 (and avoid-current
241 (next-error-buffer-p (current-buffer) nil
242 extra-test-inclusive extra-test-exclusive)
243 (progn
244 (message "This is the only buffer with error message locations")
245 (current-buffer)))
246 ;; 6. Give up.
247 (error "No buffers contain error message locations")))
249 (defun next-error (&optional arg reset)
250 "Visit next `next-error' message and corresponding source code.
252 If all the error messages parsed so far have been processed already,
253 the message buffer is checked for new ones.
255 A prefix ARG specifies how many error messages to move;
256 negative means move back to previous error messages.
257 Just \\[universal-argument] as a prefix means reparse the error message buffer
258 and start at the first error.
260 The RESET argument specifies that we should restart from the beginning.
262 \\[next-error] normally uses the most recently started
263 compilation, grep, or occur buffer. It can also operate on any
264 buffer with output from the \\[compile], \\[grep] commands, or,
265 more generally, on any buffer in Compilation mode or with
266 Compilation Minor mode enabled, or any buffer in which
267 `next-error-function' is bound to an appropriate function.
268 To specify use of a particular buffer for error messages, type
269 \\[next-error] in that buffer when it is the only one displayed
270 in the current frame.
272 Once \\[next-error] has chosen the buffer for error messages, it
273 runs `next-error-hook' with `run-hooks', and stays with that buffer
274 until you use it in some other buffer which uses Compilation mode
275 or Compilation Minor mode.
277 To control which errors are matched, customize the variable
278 `compilation-error-regexp-alist'."
279 (interactive "P")
280 (if (consp arg) (setq reset t arg nil))
281 (when (setq next-error-last-buffer (next-error-find-buffer))
282 ;; we know here that next-error-function is a valid symbol we can funcall
283 (with-current-buffer next-error-last-buffer
284 (funcall next-error-function (prefix-numeric-value arg) reset)
285 (when next-error-recenter
286 (recenter next-error-recenter))
287 (run-hooks 'next-error-hook))))
289 (defun next-error-internal ()
290 "Visit the source code corresponding to the `next-error' message at point."
291 (setq next-error-last-buffer (current-buffer))
292 ;; we know here that next-error-function is a valid symbol we can funcall
293 (with-current-buffer next-error-last-buffer
294 (funcall next-error-function 0 nil)
295 (when next-error-recenter
296 (recenter next-error-recenter))
297 (run-hooks 'next-error-hook)))
299 (defalias 'goto-next-locus 'next-error)
300 (defalias 'next-match 'next-error)
302 (defun previous-error (&optional n)
303 "Visit previous `next-error' message and corresponding source code.
305 Prefix arg N says how many error messages to move backwards (or
306 forwards, if negative).
308 This operates on the output from the \\[compile] and \\[grep] commands."
309 (interactive "p")
310 (next-error (- (or n 1))))
312 (defun first-error (&optional n)
313 "Restart at the first error.
314 Visit corresponding source code.
315 With prefix arg N, visit the source code of the Nth error.
316 This operates on the output from the \\[compile] command, for instance."
317 (interactive "p")
318 (next-error n t))
320 (defun next-error-no-select (&optional n)
321 "Move point to the next error in the `next-error' buffer and highlight match.
322 Prefix arg N says how many error messages to move forwards (or
323 backwards, if negative).
324 Finds and highlights the source line like \\[next-error], but does not
325 select the source buffer."
326 (interactive "p")
327 (let ((next-error-highlight next-error-highlight-no-select))
328 (next-error n))
329 (pop-to-buffer next-error-last-buffer))
331 (defun previous-error-no-select (&optional n)
332 "Move point to the previous error in the `next-error' buffer and highlight match.
333 Prefix arg N says how many error messages to move backwards (or
334 forwards, if negative).
335 Finds and highlights the source line like \\[previous-error], but does not
336 select the source buffer."
337 (interactive "p")
338 (next-error-no-select (- (or n 1))))
340 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
341 (defvar next-error-follow-last-line nil)
343 (define-minor-mode next-error-follow-minor-mode
344 "Minor mode for compilation, occur and diff modes.
345 With a prefix argument ARG, enable mode if ARG is positive, and
346 disable it otherwise. If called from Lisp, enable mode if ARG is
347 omitted or nil.
348 When turned on, cursor motion in the compilation, grep, occur or diff
349 buffer causes automatic display of the corresponding source code location."
350 :group 'next-error :init-value nil :lighter " Fol"
351 (if (not next-error-follow-minor-mode)
352 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
353 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
354 (make-local-variable 'next-error-follow-last-line)))
356 ;; Used as a `post-command-hook' by `next-error-follow-mode'
357 ;; for the *Compilation* *grep* and *Occur* buffers.
358 (defun next-error-follow-mode-post-command-hook ()
359 (unless (equal next-error-follow-last-line (line-number-at-pos))
360 (setq next-error-follow-last-line (line-number-at-pos))
361 (condition-case nil
362 (let ((compilation-context-lines nil))
363 (setq compilation-current-error (point))
364 (next-error-no-select 0))
365 (error t))))
370 (defun fundamental-mode ()
371 "Major mode not specialized for anything in particular.
372 Other major modes are defined by comparison with this one."
373 (interactive)
374 (kill-all-local-variables)
375 (run-mode-hooks))
377 ;; Special major modes to view specially formatted data rather than files.
379 (defvar special-mode-map
380 (let ((map (make-sparse-keymap)))
381 (suppress-keymap map)
382 (define-key map "q" 'quit-window)
383 (define-key map " " 'scroll-up-command)
384 (define-key map [?\S-\ ] 'scroll-down-command)
385 (define-key map "\C-?" 'scroll-down-command)
386 (define-key map "?" 'describe-mode)
387 (define-key map "h" 'describe-mode)
388 (define-key map ">" 'end-of-buffer)
389 (define-key map "<" 'beginning-of-buffer)
390 (define-key map "g" 'revert-buffer)
391 map))
393 (put 'special-mode 'mode-class 'special)
394 (define-derived-mode special-mode nil "Special"
395 "Parent major mode from which special major modes should inherit."
396 (setq buffer-read-only t))
398 ;; Making and deleting lines.
400 (defvar self-insert-uses-region-functions nil
401 "Special hook to tell if `self-insert-command' will use the region.
402 It must be called via `run-hook-with-args-until-success' with no arguments.
403 Any `post-self-insert-command' which consumes the region should
404 register a function on this hook so that things like `delete-selection-mode'
405 can refrain from consuming the region.")
407 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
408 "Propertized string representing a hard newline character.")
410 (defun newline (&optional arg interactive)
411 "Insert a newline, and move to left margin of the new line if it's blank.
412 If option `use-hard-newlines' is non-nil, the newline is marked with the
413 text-property `hard'.
414 With ARG, insert that many newlines.
416 If `electric-indent-mode' is enabled, this indents the final new line
417 that it adds, and reindents the preceding line. To just insert
418 a newline, use \\[electric-indent-just-newline].
420 Calls `auto-fill-function' if the current column number is greater
421 than the value of `fill-column' and ARG is nil.
422 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
423 (interactive "*P\np")
424 (barf-if-buffer-read-only)
425 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
426 ;; Set last-command-event to tell self-insert what to insert.
427 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
428 (beforepos (point))
429 (last-command-event ?\n)
430 ;; Don't auto-fill if we have a numeric argument.
431 (auto-fill-function (if arg nil auto-fill-function))
432 (arg (prefix-numeric-value arg))
433 (postproc
434 ;; Do the rest in post-self-insert-hook, because we want to do it
435 ;; *before* other functions on that hook.
436 (lambda ()
437 ;; We are not going to insert any newlines if arg is
438 ;; non-positive.
439 (or (and (numberp arg) (<= arg 0))
440 (cl-assert (eq ?\n (char-before))))
441 ;; Mark the newline(s) `hard'.
442 (if use-hard-newlines
443 (set-hard-newline-properties
444 (- (point) arg) (point)))
445 ;; If the newline leaves the previous line blank, and we
446 ;; have a left margin, delete that from the blank line.
447 (save-excursion
448 (goto-char beforepos)
449 (beginning-of-line)
450 (and (looking-at "[ \t]$")
451 (> (current-left-margin) 0)
452 (delete-region (point)
453 (line-end-position))))
454 ;; Indent the line after the newline, except in one case:
455 ;; when we added the newline at the beginning of a line which
456 ;; starts a page.
457 (or was-page-start
458 (move-to-left-margin nil t)))))
459 (unwind-protect
460 (if (not interactive)
461 ;; FIXME: For non-interactive uses, many calls actually
462 ;; just want (insert "\n"), so maybe we should do just
463 ;; that, so as to avoid the risk of filling or running
464 ;; abbrevs unexpectedly.
465 (let ((post-self-insert-hook (list postproc)))
466 (self-insert-command arg))
467 (unwind-protect
468 (progn
469 (add-hook 'post-self-insert-hook postproc nil t)
470 (self-insert-command arg))
471 ;; We first used let-binding to protect the hook, but that
472 ;; was naive since add-hook affects the symbol-default
473 ;; value of the variable, whereas the let-binding might
474 ;; only protect the buffer-local value.
475 (remove-hook 'post-self-insert-hook postproc t)))
476 (cl-assert (not (member postproc post-self-insert-hook)))
477 (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
478 nil)
480 (defun set-hard-newline-properties (from to)
481 (let ((sticky (get-text-property from 'rear-nonsticky)))
482 (put-text-property from to 'hard 't)
483 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
484 (if (and (listp sticky) (not (memq 'hard sticky)))
485 (put-text-property from (point) 'rear-nonsticky
486 (cons 'hard sticky)))))
488 (defun open-line (n)
489 "Insert a newline and leave point before it.
490 If there is a fill prefix and/or a `left-margin', insert them on
491 the new line if the line would have been blank.
492 With arg N, insert N newlines."
493 (interactive "*p")
494 (let* ((do-fill-prefix (and fill-prefix (bolp)))
495 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
496 (loc (point-marker))
497 ;; Don't expand an abbrev before point.
498 (abbrev-mode nil))
499 (newline n)
500 (goto-char loc)
501 (while (> n 0)
502 (cond ((bolp)
503 (if do-left-margin (indent-to (current-left-margin)))
504 (if do-fill-prefix (insert-and-inherit fill-prefix))))
505 (forward-line 1)
506 (setq n (1- n)))
507 (goto-char loc)
508 ;; Necessary in case a margin or prefix was inserted.
509 (end-of-line)))
511 (defun split-line (&optional arg)
512 "Split current line, moving portion beyond point vertically down.
513 If the current line starts with `fill-prefix', insert it on the new
514 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
516 When called from Lisp code, ARG may be a prefix string to copy."
517 (interactive "*P")
518 (skip-chars-forward " \t")
519 (let* ((col (current-column))
520 (pos (point))
521 ;; What prefix should we check for (nil means don't).
522 (prefix (cond ((stringp arg) arg)
523 (arg nil)
524 (t fill-prefix)))
525 ;; Does this line start with it?
526 (have-prfx (and prefix
527 (save-excursion
528 (beginning-of-line)
529 (looking-at (regexp-quote prefix))))))
530 (newline 1)
531 (if have-prfx (insert-and-inherit prefix))
532 (indent-to col 0)
533 (goto-char pos)))
535 (defun delete-indentation (&optional arg)
536 "Join this line to previous and fix up whitespace at join.
537 If there is a fill prefix, delete it from the beginning of this line.
538 With argument, join this line to following line."
539 (interactive "*P")
540 (beginning-of-line)
541 (if arg (forward-line 1))
542 (if (eq (preceding-char) ?\n)
543 (progn
544 (delete-region (point) (1- (point)))
545 ;; If the second line started with the fill prefix,
546 ;; delete the prefix.
547 (if (and fill-prefix
548 (<= (+ (point) (length fill-prefix)) (point-max))
549 (string= fill-prefix
550 (buffer-substring (point)
551 (+ (point) (length fill-prefix)))))
552 (delete-region (point) (+ (point) (length fill-prefix))))
553 (fixup-whitespace))))
555 (defalias 'join-line #'delete-indentation) ; easier to find
557 (defun delete-blank-lines ()
558 "On blank line, delete all surrounding blank lines, leaving just one.
559 On isolated blank line, delete that one.
560 On nonblank line, delete any immediately following blank lines."
561 (interactive "*")
562 (let (thisblank singleblank)
563 (save-excursion
564 (beginning-of-line)
565 (setq thisblank (looking-at "[ \t]*$"))
566 ;; Set singleblank if there is just one blank line here.
567 (setq singleblank
568 (and thisblank
569 (not (looking-at "[ \t]*\n[ \t]*$"))
570 (or (bobp)
571 (progn (forward-line -1)
572 (not (looking-at "[ \t]*$")))))))
573 ;; Delete preceding blank lines, and this one too if it's the only one.
574 (if thisblank
575 (progn
576 (beginning-of-line)
577 (if singleblank (forward-line 1))
578 (delete-region (point)
579 (if (re-search-backward "[^ \t\n]" nil t)
580 (progn (forward-line 1) (point))
581 (point-min)))))
582 ;; Delete following blank lines, unless the current line is blank
583 ;; and there are no following blank lines.
584 (if (not (and thisblank singleblank))
585 (save-excursion
586 (end-of-line)
587 (forward-line 1)
588 (delete-region (point)
589 (if (re-search-forward "[^ \t\n]" nil t)
590 (progn (beginning-of-line) (point))
591 (point-max)))))
592 ;; Handle the special case where point is followed by newline and eob.
593 ;; Delete the line, leaving point at eob.
594 (if (looking-at "^[ \t]*\n\\'")
595 (delete-region (point) (point-max)))))
597 (defcustom delete-trailing-lines t
598 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
599 Trailing lines are deleted only if `delete-trailing-whitespace'
600 is called on the entire buffer (rather than an active region)."
601 :type 'boolean
602 :group 'editing
603 :version "24.3")
605 (defun region-modifiable-p (start end)
606 "Return non-nil if the region contains no read-only text."
607 (and (not (get-text-property start 'read-only))
608 (eq end (next-single-property-change start 'read-only nil end))))
610 (defun delete-trailing-whitespace (&optional start end)
611 "Delete trailing whitespace between START and END.
612 If called interactively, START and END are the start/end of the
613 region if the mark is active, or of the buffer's accessible
614 portion if the mark is inactive.
616 This command deletes whitespace characters after the last
617 non-whitespace character in each line between START and END. It
618 does not consider formfeed characters to be whitespace.
620 If this command acts on the entire buffer (i.e. if called
621 interactively with the mark inactive, or called from Lisp with
622 END nil), it also deletes all trailing lines at the end of the
623 buffer if the variable `delete-trailing-lines' is non-nil."
624 (interactive (progn
625 (barf-if-buffer-read-only)
626 (if (use-region-p)
627 (list (region-beginning) (region-end))
628 (list nil nil))))
629 (save-match-data
630 (save-excursion
631 (let ((end-marker (and end (copy-marker end))))
632 (goto-char (or start (point-min)))
633 (with-syntax-table (make-syntax-table (syntax-table))
634 ;; Don't delete formfeeds, even if they are considered whitespace.
635 (modify-syntax-entry ?\f "_")
636 ;; Treating \n as non-whitespace makes things easier.
637 (modify-syntax-entry ?\n "_")
638 (while (re-search-forward "\\s-+$" end-marker t)
639 (let ((b (match-beginning 0)) (e (match-end 0)))
640 (when (region-modifiable-p b e)
641 (delete-region b e)))))
642 (if end
643 (set-marker end-marker nil)
644 ;; Delete trailing empty lines.
645 (and delete-trailing-lines
646 ;; Really the end of buffer.
647 (= (goto-char (point-max)) (1+ (buffer-size)))
648 (<= (skip-chars-backward "\n") -2)
649 (region-modifiable-p (1+ (point)) (point-max))
650 (delete-region (1+ (point)) (point-max)))))))
651 ;; Return nil for the benefit of `write-file-functions'.
652 nil)
654 (defun newline-and-indent ()
655 "Insert a newline, then indent according to major mode.
656 Indentation is done using the value of `indent-line-function'.
657 In programming language modes, this is the same as TAB.
658 In some text modes, where TAB inserts a tab, this command indents to the
659 column specified by the function `current-left-margin'."
660 (interactive "*")
661 (delete-horizontal-space t)
662 (newline nil t)
663 (indent-according-to-mode))
665 (defun reindent-then-newline-and-indent ()
666 "Reindent current line, insert newline, then indent the new line.
667 Indentation of both lines is done according to the current major mode,
668 which means calling the current value of `indent-line-function'.
669 In programming language modes, this is the same as TAB.
670 In some text modes, where TAB inserts a tab, this indents to the
671 column specified by the function `current-left-margin'."
672 (interactive "*")
673 (let ((pos (point)))
674 ;; Be careful to insert the newline before indenting the line.
675 ;; Otherwise, the indentation might be wrong.
676 (newline)
677 (save-excursion
678 (goto-char pos)
679 ;; We are at EOL before the call to indent-according-to-mode, and
680 ;; after it we usually are as well, but not always. We tried to
681 ;; address it with `save-excursion' but that uses a normal marker
682 ;; whereas we need `move after insertion', so we do the save/restore
683 ;; by hand.
684 (setq pos (copy-marker pos t))
685 (indent-according-to-mode)
686 (goto-char pos)
687 ;; Remove the trailing white-space after indentation because
688 ;; indentation may introduce the whitespace.
689 (delete-horizontal-space t))
690 (indent-according-to-mode)))
692 (defcustom read-quoted-char-radix 8
693 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
694 Legitimate radix values are 8, 10 and 16."
695 :type '(choice (const 8) (const 10) (const 16))
696 :group 'editing-basics)
698 (defun read-quoted-char (&optional prompt)
699 "Like `read-char', but do not allow quitting.
700 Also, if the first character read is an octal digit,
701 we read any number of octal digits and return the
702 specified character code. Any nondigit terminates the sequence.
703 If the terminator is RET, it is discarded;
704 any other terminator is used itself as input.
706 The optional argument PROMPT specifies a string to use to prompt the user.
707 The variable `read-quoted-char-radix' controls which radix to use
708 for numeric input."
709 (let ((message-log-max nil)
710 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
711 help-event-list)))
712 done (first t) (code 0) char translated)
713 (while (not done)
714 (let ((inhibit-quit first)
715 ;; Don't let C-h or other help chars get the help
716 ;; message--only help function keys. See bug#16617.
717 (help-char nil)
718 (help-event-list help-events)
719 (help-form
720 "Type the special character you want to use,
721 or the octal character code.
722 RET terminates the character code and is discarded;
723 any other non-digit terminates the character code and is then used as input."))
724 (setq char (read-event (and prompt (format "%s-" prompt)) t))
725 (if inhibit-quit (setq quit-flag nil)))
726 ;; Translate TAB key into control-I ASCII character, and so on.
727 ;; Note: `read-char' does it using the `ascii-character' property.
728 ;; We tried using read-key instead, but that disables the keystroke
729 ;; echo produced by 'C-q', see bug#24635.
730 (let ((translation (lookup-key local-function-key-map (vector char))))
731 (setq translated (if (arrayp translation)
732 (aref translation 0)
733 char)))
734 (if (integerp translated)
735 (setq translated (char-resolve-modifiers translated)))
736 (cond ((null translated))
737 ((not (integerp translated))
738 (setq unread-command-events (list char)
739 done t))
740 ((/= (logand translated ?\M-\^@) 0)
741 ;; Turn a meta-character into a character with the 0200 bit set.
742 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
743 done t))
744 ((and (<= ?0 translated)
745 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
746 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
747 (and prompt (setq prompt (message "%s %c" prompt translated))))
748 ((and (<= ?a (downcase translated))
749 (< (downcase translated)
750 (+ ?a -10 (min 36 read-quoted-char-radix))))
751 (setq code (+ (* code read-quoted-char-radix)
752 (+ 10 (- (downcase translated) ?a))))
753 (and prompt (setq prompt (message "%s %c" prompt translated))))
754 ((and (not first) (eq translated ?\C-m))
755 (setq done t))
756 ((not first)
757 (setq unread-command-events (list char)
758 done t))
759 (t (setq code translated
760 done t)))
761 (setq first nil))
762 code))
764 (defun quoted-insert (arg)
765 "Read next input character and insert it.
766 This is useful for inserting control characters.
767 With argument, insert ARG copies of the character.
769 If the first character you type after this command is an octal digit,
770 you should type a sequence of octal digits which specify a character code.
771 Any nondigit terminates the sequence. If the terminator is a RET,
772 it is discarded; any other terminator is used itself as input.
773 The variable `read-quoted-char-radix' specifies the radix for this feature;
774 set it to 10 or 16 to use decimal or hex instead of octal.
776 In overwrite mode, this function inserts the character anyway, and
777 does not handle octal digits specially. This means that if you use
778 overwrite as your normal editing mode, you can use this function to
779 insert characters when necessary.
781 In binary overwrite mode, this function does overwrite, and octal
782 digits are interpreted as a character code. This is intended to be
783 useful for editing binary files."
784 (interactive "*p")
785 (let* ((char
786 ;; Avoid "obsolete" warnings for translation-table-for-input.
787 (with-no-warnings
788 (let (translation-table-for-input input-method-function)
789 (if (or (not overwrite-mode)
790 (eq overwrite-mode 'overwrite-mode-binary))
791 (read-quoted-char)
792 (read-char))))))
793 ;; This used to assume character codes 0240 - 0377 stand for
794 ;; characters in some single-byte character set, and converted them
795 ;; to Emacs characters. But in 23.1 this feature is deprecated
796 ;; in favor of inserting the corresponding Unicode characters.
797 ;; (if (and enable-multibyte-characters
798 ;; (>= char ?\240)
799 ;; (<= char ?\377))
800 ;; (setq char (unibyte-char-to-multibyte char)))
801 (unless (characterp char)
802 (user-error "%s is not a valid character"
803 (key-description (vector char))))
804 (if (> arg 0)
805 (if (eq overwrite-mode 'overwrite-mode-binary)
806 (delete-char arg)))
807 (while (> arg 0)
808 (insert-and-inherit char)
809 (setq arg (1- arg)))))
811 (defun forward-to-indentation (&optional arg)
812 "Move forward ARG lines and position at first nonblank character."
813 (interactive "^p")
814 (forward-line (or arg 1))
815 (skip-chars-forward " \t"))
817 (defun backward-to-indentation (&optional arg)
818 "Move backward ARG lines and position at first nonblank character."
819 (interactive "^p")
820 (forward-line (- (or arg 1)))
821 (skip-chars-forward " \t"))
823 (defun back-to-indentation ()
824 "Move point to the first non-whitespace character on this line."
825 (interactive "^")
826 (beginning-of-line 1)
827 (skip-syntax-forward " " (line-end-position))
828 ;; Move back over chars that have whitespace syntax but have the p flag.
829 (backward-prefix-chars))
831 (defun fixup-whitespace ()
832 "Fixup white space between objects around point.
833 Leave one space or none, according to the context."
834 (interactive "*")
835 (save-excursion
836 (delete-horizontal-space)
837 (if (or (looking-at "^\\|\\s)")
838 (save-excursion (forward-char -1)
839 (looking-at "$\\|\\s(\\|\\s'")))
841 (insert ?\s))))
843 (defun delete-horizontal-space (&optional backward-only)
844 "Delete all spaces and tabs around point.
845 If BACKWARD-ONLY is non-nil, only delete them before point."
846 (interactive "*P")
847 (let ((orig-pos (point)))
848 (delete-region
849 (if backward-only
850 orig-pos
851 (progn
852 (skip-chars-forward " \t")
853 (constrain-to-field nil orig-pos t)))
854 (progn
855 (skip-chars-backward " \t")
856 (constrain-to-field nil orig-pos)))))
858 (defun just-one-space (&optional n)
859 "Delete all spaces and tabs around point, leaving one space (or N spaces).
860 If N is negative, delete newlines as well, leaving -N spaces.
861 See also `cycle-spacing'."
862 (interactive "*p")
863 (cycle-spacing n nil 'single-shot))
865 (defvar cycle-spacing--context nil
866 "Store context used in consecutive calls to `cycle-spacing' command.
867 The first time `cycle-spacing' runs, it saves in this variable:
868 its N argument, the original point position, and the original spacing
869 around point.")
871 (defun cycle-spacing (&optional n preserve-nl-back mode)
872 "Manipulate whitespace around point in a smart way.
873 In interactive use, this function behaves differently in successive
874 consecutive calls.
876 The first call in a sequence acts like `just-one-space'.
877 It deletes all spaces and tabs around point, leaving one space
878 \(or N spaces). N is the prefix argument. If N is negative,
879 it deletes newlines as well, leaving -N spaces.
880 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
882 The second call in a sequence deletes all spaces.
884 The third call in a sequence restores the original whitespace (and point).
886 If MODE is `single-shot', it only performs the first step in the sequence.
887 If MODE is `fast' and the first step would not result in any change
888 \(i.e., there are exactly (abs N) spaces around point),
889 the function goes straight to the second step.
891 Repeatedly calling the function with different values of N starts a
892 new sequence each time."
893 (interactive "*p")
894 (let ((orig-pos (point))
895 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
896 (num (abs (or n 1))))
897 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
898 (constrain-to-field nil orig-pos)
899 (cond
900 ;; Command run for the first time, single-shot mode or different argument
901 ((or (eq 'single-shot mode)
902 (not (equal last-command this-command))
903 (not cycle-spacing--context)
904 (not (eq (car cycle-spacing--context) n)))
905 (let* ((start (point))
906 (num (- num (skip-chars-forward " " (+ num (point)))))
907 (mid (point))
908 (end (progn
909 (skip-chars-forward skip-characters)
910 (constrain-to-field nil orig-pos t))))
911 (setq cycle-spacing--context ;; Save for later.
912 ;; Special handling for case where there was no space at all.
913 (unless (= start end)
914 (cons n (cons orig-pos (buffer-substring start (point))))))
915 ;; If this run causes no change in buffer content, delete all spaces,
916 ;; otherwise delete all excess spaces.
917 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
918 start mid) end)
919 (insert (make-string num ?\s))))
921 ;; Command run for the second time.
922 ((not (equal orig-pos (point)))
923 (delete-region (point) orig-pos))
925 ;; Command run for the third time.
927 (insert (cddr cycle-spacing--context))
928 (goto-char (cadr cycle-spacing--context))
929 (setq cycle-spacing--context nil)))))
931 (defun beginning-of-buffer (&optional arg)
932 "Move point to the beginning of the buffer.
933 With numeric arg N, put point N/10 of the way from the beginning.
934 If the buffer is narrowed, this command uses the beginning of the
935 accessible part of the buffer.
937 Push mark at previous position, unless either a \\[universal-argument] prefix
938 is supplied, or Transient Mark mode is enabled and the mark is active."
939 (declare (interactive-only "use `(goto-char (point-min))' instead."))
940 (interactive "^P")
941 (or (consp arg)
942 (region-active-p)
943 (push-mark))
944 (let ((size (- (point-max) (point-min))))
945 (goto-char (if (and arg (not (consp arg)))
946 (+ (point-min)
947 (if (> size 10000)
948 ;; Avoid overflow for large buffer sizes!
949 (* (prefix-numeric-value arg)
950 (/ size 10))
951 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
952 (point-min))))
953 (if (and arg (not (consp arg))) (forward-line 1)))
955 (defun end-of-buffer (&optional arg)
956 "Move point to the end of the buffer.
957 With numeric arg N, put point N/10 of the way from the end.
958 If the buffer is narrowed, this command uses the end of the
959 accessible part of the buffer.
961 Push mark at previous position, unless either a \\[universal-argument] prefix
962 is supplied, or Transient Mark mode is enabled and the mark is active."
963 (declare (interactive-only "use `(goto-char (point-max))' instead."))
964 (interactive "^P")
965 (or (consp arg) (region-active-p) (push-mark))
966 (let ((size (- (point-max) (point-min))))
967 (goto-char (if (and arg (not (consp arg)))
968 (- (point-max)
969 (if (> size 10000)
970 ;; Avoid overflow for large buffer sizes!
971 (* (prefix-numeric-value arg)
972 (/ size 10))
973 (/ (* size (prefix-numeric-value arg)) 10)))
974 (point-max))))
975 ;; If we went to a place in the middle of the buffer,
976 ;; adjust it to the beginning of a line.
977 (cond ((and arg (not (consp arg))) (forward-line 1))
978 ((and (eq (current-buffer) (window-buffer))
979 (> (point) (window-end nil t)))
980 ;; If the end of the buffer is not already on the screen,
981 ;; then scroll specially to put it near, but not at, the bottom.
982 (overlay-recenter (point))
983 (recenter -3))))
985 (defcustom delete-active-region t
986 "Whether single-char deletion commands delete an active region.
987 This has an effect only if Transient Mark mode is enabled, and
988 affects `delete-forward-char' and `delete-backward-char', though
989 not `delete-char'.
991 If the value is the symbol `kill', the active region is killed
992 instead of deleted."
993 :type '(choice (const :tag "Delete active region" t)
994 (const :tag "Kill active region" kill)
995 (const :tag "Do ordinary deletion" nil))
996 :group 'killing
997 :version "24.1")
999 (defvar region-extract-function
1000 (lambda (delete)
1001 (when (region-beginning)
1002 (cond
1003 ((eq delete 'bounds)
1004 (list (cons (region-beginning) (region-end))))
1005 ((eq delete 'delete-only)
1006 (delete-region (region-beginning) (region-end)))
1008 (filter-buffer-substring (region-beginning) (region-end) delete)))))
1009 "Function to get the region's content.
1010 Called with one argument DELETE.
1011 If DELETE is `delete-only', then only delete the region and the return value
1012 is undefined. If DELETE is nil, just return the content as a string.
1013 If DELETE is `bounds', then don't delete, but just return the
1014 boundaries of the region as a list of (START . END) positions.
1015 If anything else, delete the region and return its content as a string,
1016 after filtering it with `filter-buffer-substring'.")
1018 (defvar region-insert-function
1019 (lambda (lines)
1020 (let ((first t))
1021 (while lines
1022 (or first
1023 (insert ?\n))
1024 (insert-for-yank (car lines))
1025 (setq lines (cdr lines)
1026 first nil))))
1027 "Function to insert the region's content.
1028 Called with one argument LINES.
1029 Insert the region as a list of lines.")
1031 (defun delete-backward-char (n &optional killflag)
1032 "Delete the previous N characters (following if N is negative).
1033 If Transient Mark mode is enabled, the mark is active, and N is 1,
1034 delete the text in the region and deactivate the mark instead.
1035 To disable this, set option `delete-active-region' to nil.
1037 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1038 kill ring) instead of delete. Interactively, N is the prefix
1039 arg, and KILLFLAG is set if N is explicitly specified.
1041 When killing, the killed text is filtered by
1042 `filter-buffer-substring' before it is saved in the kill ring, so
1043 the actual saved text might be different from what was killed.
1045 In Overwrite mode, single character backward deletion may replace
1046 tabs with spaces so as to back over columns, unless point is at
1047 the end of the line."
1048 (declare (interactive-only delete-char))
1049 (interactive "p\nP")
1050 (unless (integerp n)
1051 (signal 'wrong-type-argument (list 'integerp n)))
1052 (cond ((and (use-region-p)
1053 delete-active-region
1054 (= n 1))
1055 ;; If a region is active, kill or delete it.
1056 (if (eq delete-active-region 'kill)
1057 (kill-region (region-beginning) (region-end) 'region)
1058 (funcall region-extract-function 'delete-only)))
1059 ;; In Overwrite mode, maybe untabify while deleting
1060 ((null (or (null overwrite-mode)
1061 (<= n 0)
1062 (memq (char-before) '(?\t ?\n))
1063 (eobp)
1064 (eq (char-after) ?\n)))
1065 (let ((ocol (current-column)))
1066 (delete-char (- n) killflag)
1067 (save-excursion
1068 (insert-char ?\s (- ocol (current-column)) nil))))
1069 ;; Otherwise, do simple deletion.
1070 (t (delete-char (- n) killflag))))
1072 (defun delete-forward-char (n &optional killflag)
1073 "Delete the following N characters (previous if N is negative).
1074 If Transient Mark mode is enabled, the mark is active, and N is 1,
1075 delete the text in the region and deactivate the mark instead.
1076 To disable this, set variable `delete-active-region' to nil.
1078 Optional second arg KILLFLAG non-nil means to kill (save in kill
1079 ring) instead of delete. Interactively, N is the prefix arg, and
1080 KILLFLAG is set if N was explicitly specified.
1082 When killing, the killed text is filtered by
1083 `filter-buffer-substring' before it is saved in the kill ring, so
1084 the actual saved text might be different from what was killed."
1085 (declare (interactive-only delete-char))
1086 (interactive "p\nP")
1087 (unless (integerp n)
1088 (signal 'wrong-type-argument (list 'integerp n)))
1089 (cond ((and (use-region-p)
1090 delete-active-region
1091 (= n 1))
1092 ;; If a region is active, kill or delete it.
1093 (if (eq delete-active-region 'kill)
1094 (kill-region (region-beginning) (region-end) 'region)
1095 (funcall region-extract-function 'delete-only)))
1097 ;; Otherwise, do simple deletion.
1098 (t (delete-char n killflag))))
1100 (defun mark-whole-buffer ()
1101 "Put point at beginning and mark at end of buffer.
1102 If narrowing is in effect, only uses the accessible part of the buffer.
1103 You probably should not use this function in Lisp programs;
1104 it is usually a mistake for a Lisp function to use any subroutine
1105 that uses or sets the mark."
1106 (declare (interactive-only t))
1107 (interactive)
1108 (push-mark (point))
1109 (push-mark (point-max) nil t)
1110 ;; This is really `point-min' in most cases, but if we're in the
1111 ;; minibuffer, this is at the end of the prompt.
1112 (goto-char (minibuffer-prompt-end)))
1115 ;; Counting lines, one way or another.
1117 (defun goto-line (line &optional buffer)
1118 "Go to LINE, counting from line 1 at beginning of buffer.
1119 If called interactively, a numeric prefix argument specifies
1120 LINE; without a numeric prefix argument, read LINE from the
1121 minibuffer.
1123 If optional argument BUFFER is non-nil, switch to that buffer and
1124 move to line LINE there. If called interactively with \\[universal-argument]
1125 as argument, BUFFER is the most recently selected other buffer.
1127 Prior to moving point, this function sets the mark (without
1128 activating it), unless Transient Mark mode is enabled and the
1129 mark is already active.
1131 This function is usually the wrong thing to use in a Lisp program.
1132 What you probably want instead is something like:
1133 (goto-char (point-min))
1134 (forward-line (1- N))
1135 If at all possible, an even better solution is to use char counts
1136 rather than line counts."
1137 (declare (interactive-only forward-line))
1138 (interactive
1139 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1140 (list (prefix-numeric-value current-prefix-arg))
1141 ;; Look for a default, a number in the buffer at point.
1142 (let* ((default
1143 (save-excursion
1144 (skip-chars-backward "0-9")
1145 (if (looking-at "[0-9]")
1146 (string-to-number
1147 (buffer-substring-no-properties
1148 (point)
1149 (progn (skip-chars-forward "0-9")
1150 (point)))))))
1151 ;; Decide if we're switching buffers.
1152 (buffer
1153 (if (consp current-prefix-arg)
1154 (other-buffer (current-buffer) t)))
1155 (buffer-prompt
1156 (if buffer
1157 (concat " in " (buffer-name buffer))
1158 "")))
1159 ;; Read the argument, offering that number (if any) as default.
1160 (list (read-number (format "Goto line%s: " buffer-prompt)
1161 (list default (line-number-at-pos)))
1162 buffer))))
1163 ;; Switch to the desired buffer, one way or another.
1164 (if buffer
1165 (let ((window (get-buffer-window buffer)))
1166 (if window (select-window window)
1167 (switch-to-buffer-other-window buffer))))
1168 ;; Leave mark at previous position
1169 (or (region-active-p) (push-mark))
1170 ;; Move to the specified line number in that buffer.
1171 (save-restriction
1172 (widen)
1173 (goto-char (point-min))
1174 (if (eq selective-display t)
1175 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1176 (forward-line (1- line)))))
1178 (defun count-words-region (start end &optional arg)
1179 "Count the number of words in the region.
1180 If called interactively, print a message reporting the number of
1181 lines, words, and characters in the region (whether or not the
1182 region is active); with prefix ARG, report for the entire buffer
1183 rather than the region.
1185 If called from Lisp, return the number of words between positions
1186 START and END."
1187 (interactive (if current-prefix-arg
1188 (list nil nil current-prefix-arg)
1189 (list (region-beginning) (region-end) nil)))
1190 (cond ((not (called-interactively-p 'any))
1191 (count-words start end))
1192 (arg
1193 (count-words--buffer-message))
1195 (count-words--message "Region" start end))))
1197 (defun count-words (start end)
1198 "Count words between START and END.
1199 If called interactively, START and END are normally the start and
1200 end of the buffer; but if the region is active, START and END are
1201 the start and end of the region. Print a message reporting the
1202 number of lines, words, and chars.
1204 If called from Lisp, return the number of words between START and
1205 END, without printing any message."
1206 (interactive (list nil nil))
1207 (cond ((not (called-interactively-p 'any))
1208 (let ((words 0))
1209 (save-excursion
1210 (save-restriction
1211 (narrow-to-region start end)
1212 (goto-char (point-min))
1213 (while (forward-word-strictly 1)
1214 (setq words (1+ words)))))
1215 words))
1216 ((use-region-p)
1217 (call-interactively 'count-words-region))
1219 (count-words--buffer-message))))
1221 (defun count-words--buffer-message ()
1222 (count-words--message
1223 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1224 (point-min) (point-max)))
1226 (defun count-words--message (str start end)
1227 (let ((lines (count-lines start end))
1228 (words (count-words start end))
1229 (chars (- end start)))
1230 (message "%s has %d line%s, %d word%s, and %d character%s."
1232 lines (if (= lines 1) "" "s")
1233 words (if (= words 1) "" "s")
1234 chars (if (= chars 1) "" "s"))))
1236 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1238 (defun what-line ()
1239 "Print the current buffer line number and narrowed line number of point."
1240 (interactive)
1241 (let ((start (point-min))
1242 (n (line-number-at-pos)))
1243 (if (= start 1)
1244 (message "Line %d" n)
1245 (save-excursion
1246 (save-restriction
1247 (widen)
1248 (message "line %d (narrowed line %d)"
1249 (+ n (line-number-at-pos start) -1) n))))))
1251 (defun count-lines (start end)
1252 "Return number of lines between START and END.
1253 This is usually the number of newlines between them,
1254 but can be one more if START is not equal to END
1255 and the greater of them is not at the start of a line."
1256 (save-excursion
1257 (save-restriction
1258 (narrow-to-region start end)
1259 (goto-char (point-min))
1260 (if (eq selective-display t)
1261 (save-match-data
1262 (let ((done 0))
1263 (while (re-search-forward "[\n\C-m]" nil t 40)
1264 (setq done (+ 40 done)))
1265 (while (re-search-forward "[\n\C-m]" nil t 1)
1266 (setq done (+ 1 done)))
1267 (goto-char (point-max))
1268 (if (and (/= start end)
1269 (not (bolp)))
1270 (1+ done)
1271 done)))
1272 (- (buffer-size) (forward-line (buffer-size)))))))
1274 (defun line-number-at-pos (&optional pos)
1275 "Return (narrowed) buffer line number at position POS.
1276 If POS is nil, use current buffer location.
1277 Counting starts at (point-min), so the value refers
1278 to the contents of the accessible portion of the buffer."
1279 (let ((opoint (or pos (point))) start)
1280 (save-excursion
1281 (goto-char (point-min))
1282 (setq start (point))
1283 (goto-char opoint)
1284 (forward-line 0)
1285 (1+ (count-lines start (point))))))
1287 (defun what-cursor-position (&optional detail)
1288 "Print info on cursor position (on screen and within buffer).
1289 Also describe the character after point, and give its character code
1290 in octal, decimal and hex.
1292 For a non-ASCII multibyte character, also give its encoding in the
1293 buffer's selected coding system if the coding system encodes the
1294 character safely. If the character is encoded into one byte, that
1295 code is shown in hex. If the character is encoded into more than one
1296 byte, just \"...\" is shown.
1298 In addition, with prefix argument, show details about that character
1299 in *Help* buffer. See also the command `describe-char'."
1300 (interactive "P")
1301 (let* ((char (following-char))
1302 (bidi-fixer
1303 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1304 ;; start a directional embedding, which could completely
1305 ;; disrupt the rest of the line (e.g., RLO will display the
1306 ;; rest of the line right-to-left). So we put an invisible
1307 ;; PDF character after these characters, to end the
1308 ;; embedding, which eliminates any effects on the rest of
1309 ;; the line. For RLE and RLO we also append an invisible
1310 ;; LRM, to avoid reordering the following numerical
1311 ;; characters. For LRI/RLI/FSI we append a PDI.
1312 (cond ((memq char '(?\x202a ?\x202d))
1313 (propertize (string ?\x202c) 'invisible t))
1314 ((memq char '(?\x202b ?\x202e))
1315 (propertize (string ?\x202c ?\x200e) 'invisible t))
1316 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1317 (propertize (string ?\x2069) 'invisible t))
1318 ;; Strong right-to-left characters cause reordering of
1319 ;; the following numerical characters which show the
1320 ;; codepoint, so append LRM to countermand that.
1321 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1322 (propertize (string ?\x200e) 'invisible t))
1324 "")))
1325 (beg (point-min))
1326 (end (point-max))
1327 (pos (point))
1328 (total (buffer-size))
1329 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1330 (hscroll (if (= (window-hscroll) 0)
1332 (format " Hscroll=%d" (window-hscroll))))
1333 (col (current-column)))
1334 (if (= pos end)
1335 (if (or (/= beg 1) (/= end (1+ total)))
1336 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1337 pos total percent beg end col hscroll)
1338 (message "point=%d of %d (EOB) column=%d%s"
1339 pos total col hscroll))
1340 (let ((coding buffer-file-coding-system)
1341 encoded encoding-msg display-prop under-display)
1342 (if (or (not coding)
1343 (eq (coding-system-type coding) t))
1344 (setq coding (default-value 'buffer-file-coding-system)))
1345 (if (eq (char-charset char) 'eight-bit)
1346 (setq encoding-msg
1347 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1348 ;; Check if the character is displayed with some `display'
1349 ;; text property. In that case, set under-display to the
1350 ;; buffer substring covered by that property.
1351 (setq display-prop (get-char-property pos 'display))
1352 (if display-prop
1353 (let ((to (or (next-single-char-property-change pos 'display)
1354 (point-max))))
1355 (if (< to (+ pos 4))
1356 (setq under-display "")
1357 (setq under-display "..."
1358 to (+ pos 4)))
1359 (setq under-display
1360 (concat (buffer-substring-no-properties pos to)
1361 under-display)))
1362 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1363 (setq encoding-msg
1364 (if display-prop
1365 (if (not (stringp display-prop))
1366 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1367 char char char under-display)
1368 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1369 char char char under-display display-prop))
1370 (if encoded
1371 (format "(%d, #o%o, #x%x, file %s)"
1372 char char char
1373 (if (> (length encoded) 1)
1374 "..."
1375 (encoded-string-description encoded coding)))
1376 (format "(%d, #o%o, #x%x)" char char char)))))
1377 (if detail
1378 ;; We show the detailed information about CHAR.
1379 (describe-char (point)))
1380 (if (or (/= beg 1) (/= end (1+ total)))
1381 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1382 (if (< char 256)
1383 (single-key-description char)
1384 (buffer-substring-no-properties (point) (1+ (point))))
1385 bidi-fixer
1386 encoding-msg pos total percent beg end col hscroll)
1387 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1388 (if enable-multibyte-characters
1389 (if (< char 128)
1390 (single-key-description char)
1391 (buffer-substring-no-properties (point) (1+ (point))))
1392 (single-key-description char))
1393 bidi-fixer encoding-msg pos total percent col hscroll))))))
1395 ;; Initialize read-expression-map. It is defined at C level.
1396 (defvar read-expression-map
1397 (let ((m (make-sparse-keymap)))
1398 (define-key m "\M-\t" 'completion-at-point)
1399 ;; Might as well bind TAB to completion, since inserting a TAB char is
1400 ;; much too rarely useful.
1401 (define-key m "\t" 'completion-at-point)
1402 (set-keymap-parent m minibuffer-local-map)
1405 (defun read-minibuffer (prompt &optional initial-contents)
1406 "Return a Lisp object read using the minibuffer, unevaluated.
1407 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1408 is a string to insert in the minibuffer before reading.
1409 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1410 Such arguments are used as in `read-from-minibuffer'.)"
1411 ;; Used for interactive spec `x'.
1412 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1413 t 'minibuffer-history))
1415 (defun eval-minibuffer (prompt &optional initial-contents)
1416 "Return value of Lisp expression read using the minibuffer.
1417 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1418 is a string to insert in the minibuffer before reading.
1419 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1420 Such arguments are used as in `read-from-minibuffer'.)"
1421 ;; Used for interactive spec `X'.
1422 (eval (read--expression prompt initial-contents)))
1424 (defvar minibuffer-completing-symbol nil
1425 "Non-nil means completing a Lisp symbol in the minibuffer.")
1426 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1428 (defvar minibuffer-default nil
1429 "The current default value or list of default values in the minibuffer.
1430 The functions `read-from-minibuffer' and `completing-read' bind
1431 this variable locally.")
1433 (defcustom eval-expression-print-level 4
1434 "Value for `print-level' while printing value in `eval-expression'.
1435 A value of nil means no limit."
1436 :group 'lisp
1437 :type '(choice (const :tag "No Limit" nil) integer)
1438 :version "21.1")
1440 (defcustom eval-expression-print-length 12
1441 "Value for `print-length' while printing value in `eval-expression'.
1442 A value of nil means no limit."
1443 :group 'lisp
1444 :type '(choice (const :tag "No Limit" nil) integer)
1445 :version "21.1")
1447 (defcustom eval-expression-debug-on-error t
1448 "If non-nil set `debug-on-error' to t in `eval-expression'.
1449 If nil, don't change the value of `debug-on-error'."
1450 :group 'lisp
1451 :type 'boolean
1452 :version "21.1")
1454 (defun eval-expression-print-format (value)
1455 "If VALUE in an integer, return a specially formatted string.
1456 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1457 If VALUE is not an integer, nil is returned.
1458 This function is used by functions like `prin1' that display the
1459 result of expression evaluation."
1460 (if (and (integerp value)
1461 (or (eq standard-output t)
1462 (zerop (prefix-numeric-value current-prefix-arg))))
1463 (let ((char-string
1464 (if (and (characterp value)
1465 (char-displayable-p value))
1466 (prin1-char value))))
1467 (if char-string
1468 (format " (#o%o, #x%x, %s)" value value char-string)
1469 (format " (#o%o, #x%x)" value value)))))
1471 (defvar eval-expression-minibuffer-setup-hook nil
1472 "Hook run by `eval-expression' when entering the minibuffer.")
1474 (defun read--expression (prompt &optional initial-contents)
1475 (let ((minibuffer-completing-symbol t))
1476 (minibuffer-with-setup-hook
1477 (lambda ()
1478 ;; FIXME: call emacs-lisp-mode?
1479 (add-function :before-until (local 'eldoc-documentation-function)
1480 #'elisp-eldoc-documentation-function)
1481 (add-hook 'completion-at-point-functions
1482 #'elisp-completion-at-point nil t)
1483 (run-hooks 'eval-expression-minibuffer-setup-hook))
1484 (read-from-minibuffer prompt initial-contents
1485 read-expression-map t
1486 'read-expression-history))))
1488 ;; We define this, rather than making `eval' interactive,
1489 ;; for the sake of completion of names like eval-region, eval-buffer.
1490 (defun eval-expression (exp &optional insert-value)
1491 "Evaluate EXP and print value in the echo area.
1492 When called interactively, read an Emacs Lisp expression and evaluate it.
1493 Value is also consed on to front of the variable `values'.
1494 If the resulting value is an integer, it will be printed in
1495 several additional formats (octal, hexadecimal, and character).
1496 Optional argument INSERT-VALUE non-nil (interactively, with
1497 prefix argument) means insert the result into the current buffer
1498 instead of printing it in the echo area.
1500 Normally, this function truncates long output according to the value
1501 of the variables `eval-expression-print-length' and
1502 `eval-expression-print-level'. With a prefix argument of zero,
1503 however, there is no such truncation.
1505 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1506 minibuffer.
1508 If `eval-expression-debug-on-error' is non-nil, which is the default,
1509 this command arranges for all errors to enter the debugger."
1510 (interactive
1511 (list (read--expression "Eval: ")
1512 current-prefix-arg))
1514 (if (null eval-expression-debug-on-error)
1515 (push (eval exp lexical-binding) values)
1516 (let ((old-value (make-symbol "t")) new-value)
1517 ;; Bind debug-on-error to something unique so that we can
1518 ;; detect when evalled code changes it.
1519 (let ((debug-on-error old-value))
1520 (push (eval (macroexpand-all exp) lexical-binding) values)
1521 (setq new-value debug-on-error))
1522 ;; If evalled code has changed the value of debug-on-error,
1523 ;; propagate that change to the global binding.
1524 (unless (eq old-value new-value)
1525 (setq debug-on-error new-value))))
1527 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
1528 eval-expression-print-length))
1529 (print-level (and (not (zerop (prefix-numeric-value insert-value)))
1530 eval-expression-print-level))
1531 (deactivate-mark))
1532 (if insert-value
1533 (with-no-warnings
1534 (let ((standard-output (current-buffer)))
1535 (prog1
1536 (prin1 (car values))
1537 (when (zerop (prefix-numeric-value insert-value))
1538 (let ((str (eval-expression-print-format (car values))))
1539 (if str (princ str)))))))
1540 (prog1
1541 (prin1 (car values) t)
1542 (let ((str (eval-expression-print-format (car values))))
1543 (if str (princ str t)))))))
1545 (defun edit-and-eval-command (prompt command)
1546 "Prompting with PROMPT, let user edit COMMAND and eval result.
1547 COMMAND is a Lisp expression. Let user edit that expression in
1548 the minibuffer, then read and evaluate the result."
1549 (let ((command
1550 (let ((print-level nil)
1551 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1552 (unwind-protect
1553 (read-from-minibuffer prompt
1554 (prin1-to-string command)
1555 read-expression-map t
1556 'command-history)
1557 ;; If command was added to command-history as a string,
1558 ;; get rid of that. We want only evaluable expressions there.
1559 (if (stringp (car command-history))
1560 (setq command-history (cdr command-history)))))))
1562 ;; If command to be redone does not match front of history,
1563 ;; add it to the history.
1564 (or (equal command (car command-history))
1565 (setq command-history (cons command command-history)))
1566 (eval command)))
1568 (defun repeat-complex-command (arg)
1569 "Edit and re-evaluate last complex command, or ARGth from last.
1570 A complex command is one which used the minibuffer.
1571 The command is placed in the minibuffer as a Lisp form for editing.
1572 The result is executed, repeating the command as changed.
1573 If the command has been changed or is not the most recent previous
1574 command it is added to the front of the command history.
1575 You can use the minibuffer history commands \
1576 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1577 to get different commands to edit and resubmit."
1578 (interactive "p")
1579 (let ((elt (nth (1- arg) command-history))
1580 newcmd)
1581 (if elt
1582 (progn
1583 (setq newcmd
1584 (let ((print-level nil)
1585 (minibuffer-history-position arg)
1586 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1587 (unwind-protect
1588 (read-from-minibuffer
1589 "Redo: " (prin1-to-string elt) read-expression-map t
1590 (cons 'command-history arg))
1592 ;; If command was added to command-history as a
1593 ;; string, get rid of that. We want only
1594 ;; evaluable expressions there.
1595 (if (stringp (car command-history))
1596 (setq command-history (cdr command-history))))))
1598 ;; If command to be redone does not match front of history,
1599 ;; add it to the history.
1600 (or (equal newcmd (car command-history))
1601 (setq command-history (cons newcmd command-history)))
1602 (apply #'funcall-interactively
1603 (car newcmd)
1604 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1605 (if command-history
1606 (error "Argument %d is beyond length of command history" arg)
1607 (error "There are no previous complex commands to repeat")))))
1610 (defvar extended-command-history nil)
1611 (defvar execute-extended-command--last-typed nil)
1613 (defun read-extended-command ()
1614 "Read command name to invoke in `execute-extended-command'."
1615 (minibuffer-with-setup-hook
1616 (lambda ()
1617 (add-hook 'post-self-insert-hook
1618 (lambda ()
1619 (setq execute-extended-command--last-typed
1620 (minibuffer-contents)))
1621 nil 'local)
1622 (set (make-local-variable 'minibuffer-default-add-function)
1623 (lambda ()
1624 ;; Get a command name at point in the original buffer
1625 ;; to propose it after M-n.
1626 (with-current-buffer (window-buffer (minibuffer-selected-window))
1627 (and (commandp (function-called-at-point))
1628 (format "%S" (function-called-at-point)))))))
1629 ;; Read a string, completing from and restricting to the set of
1630 ;; all defined commands. Don't provide any initial input.
1631 ;; Save the command read on the extended-command history list.
1632 (completing-read
1633 (concat (cond
1634 ((eq current-prefix-arg '-) "- ")
1635 ((and (consp current-prefix-arg)
1636 (eq (car current-prefix-arg) 4)) "C-u ")
1637 ((and (consp current-prefix-arg)
1638 (integerp (car current-prefix-arg)))
1639 (format "%d " (car current-prefix-arg)))
1640 ((integerp current-prefix-arg)
1641 (format "%d " current-prefix-arg)))
1642 ;; This isn't strictly correct if `execute-extended-command'
1643 ;; is bound to anything else (e.g. [menu]).
1644 ;; It could use (key-description (this-single-command-keys)),
1645 ;; but actually a prompt other than "M-x" would be confusing,
1646 ;; because "M-x" is a well-known prompt to read a command
1647 ;; and it serves as a shorthand for "Extended command: ".
1648 "M-x ")
1649 (lambda (string pred action)
1650 (let ((pred
1651 (if (memq action '(nil t))
1652 ;; Exclude obsolete commands from completions.
1653 (lambda (sym)
1654 (and (funcall pred sym)
1655 (or (equal string (symbol-name sym))
1656 (not (get sym 'byte-obsolete-info)))))
1657 pred)))
1658 (complete-with-action action obarray string pred)))
1659 #'commandp t nil 'extended-command-history)))
1661 (defcustom suggest-key-bindings t
1662 "Non-nil means show the equivalent key-binding when M-x command has one.
1663 The value can be a length of time to show the message for.
1664 If the value is non-nil and not a number, we wait 2 seconds."
1665 :group 'keyboard
1666 :type '(choice (const :tag "off" nil)
1667 (integer :tag "time" 2)
1668 (other :tag "on")))
1670 (defcustom extended-command-suggest-shorter t
1671 "If non-nil, show a shorter M-x invocation when there is one."
1672 :group 'keyboard
1673 :type 'boolean
1674 :version "26.1")
1676 (defun execute-extended-command--shorter-1 (name length)
1677 (cond
1678 ((zerop length) (list ""))
1679 ((equal name "") nil)
1681 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1682 (execute-extended-command--shorter-1
1683 (substring name 1) (1- length)))
1684 (when (string-match "\\`\\(-\\)?[^-]*" name)
1685 (execute-extended-command--shorter-1
1686 (substring name (match-end 0)) length))))))
1688 (defun execute-extended-command--shorter (name typed)
1689 (let ((candidates '())
1690 (max (length typed))
1691 (len 1)
1692 binding)
1693 (while (and (not binding)
1694 (progn
1695 (unless candidates
1696 (setq len (1+ len))
1697 (setq candidates (execute-extended-command--shorter-1
1698 name len)))
1699 ;; Don't show the help message if the binding isn't
1700 ;; significantly shorter than the M-x command the user typed.
1701 (< len (- max 5))))
1702 (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
1703 (let ((candidate (pop candidates)))
1704 (when (equal name
1705 (car-safe (completion-try-completion
1706 candidate obarray 'commandp len)))
1707 (setq binding candidate))))
1708 binding))
1710 (defun execute-extended-command (prefixarg &optional command-name typed)
1711 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1712 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1713 "Read a command name, then read the arguments and call the command.
1714 To pass a prefix argument to the command you are
1715 invoking, give a prefix argument to `execute-extended-command'."
1716 (declare (interactive-only command-execute))
1717 ;; FIXME: Remember the actual text typed by the user before completion,
1718 ;; so that we don't later on suggest the same shortening.
1719 (interactive
1720 (let ((execute-extended-command--last-typed nil))
1721 (list current-prefix-arg
1722 (read-extended-command)
1723 execute-extended-command--last-typed)))
1724 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1725 (unless command-name
1726 (let ((current-prefix-arg prefixarg) ; for prompt
1727 (execute-extended-command--last-typed nil))
1728 (setq command-name (read-extended-command))
1729 (setq typed execute-extended-command--last-typed)))
1730 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1731 (binding (and suggest-key-bindings
1732 (not executing-kbd-macro)
1733 (where-is-internal function overriding-local-map t))))
1734 (unless (commandp function)
1735 (error "`%s' is not a valid command name" command-name))
1736 (setq this-command function)
1737 ;; Normally `real-this-command' should never be changed, but here we really
1738 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1739 ;; binding" for <cmd>, so the command the user really wanted to run is
1740 ;; `function' and not `execute-extended-command'. The difference is
1741 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1742 (setq real-this-command function)
1743 (let ((prefix-arg prefixarg))
1744 (command-execute function 'record))
1745 ;; If enabled, show which key runs this command.
1746 ;; But first wait, and skip the message if there is input.
1747 (let* ((waited
1748 ;; If this command displayed something in the echo area;
1749 ;; wait a few seconds, then display our suggestion message.
1750 ;; FIXME: Wait *after* running post-command-hook!
1751 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1752 ;; find a better answer anyway!
1753 (when suggest-key-bindings
1754 (sit-for (cond
1755 ((zerop (length (current-message))) 0)
1756 ((numberp suggest-key-bindings) suggest-key-bindings)
1757 (t 2))))))
1758 (when (and waited (not (consp unread-command-events)))
1759 (unless (or (not extended-command-suggest-shorter)
1760 binding executing-kbd-macro (not (symbolp function))
1761 (<= (length (symbol-name function)) 2))
1762 ;; There's no binding for CMD. Let's try and find the shortest
1763 ;; string to use in M-x.
1764 ;; FIXME: Can be slow. Cache it maybe?
1765 (while-no-input
1766 (setq binding (execute-extended-command--shorter
1767 (symbol-name function) typed))))
1768 (when binding
1769 (with-temp-message
1770 (format-message "You can run the command `%s' with %s"
1771 function
1772 (if (stringp binding)
1773 (concat "M-x " binding " RET")
1774 (key-description binding)))
1775 (sit-for (if (numberp suggest-key-bindings)
1776 suggest-key-bindings
1777 2))))))))
1779 (defun command-execute (cmd &optional record-flag keys special)
1780 ;; BEWARE: Called directly from the C code.
1781 "Execute CMD as an editor command.
1782 CMD must be a symbol that satisfies the `commandp' predicate.
1783 Optional second arg RECORD-FLAG non-nil
1784 means unconditionally put this command in the variable `command-history'.
1785 Otherwise, that is done only if an arg is read using the minibuffer.
1786 The argument KEYS specifies the value to use instead of (this-command-keys)
1787 when reading the arguments; if it is nil, (this-command-keys) is used.
1788 The argument SPECIAL, if non-nil, means that this command is executing
1789 a special event, so ignore the prefix argument and don't clear it."
1790 (setq debug-on-next-call nil)
1791 (let ((prefixarg (unless special
1792 ;; FIXME: This should probably be done around
1793 ;; pre-command-hook rather than here!
1794 (prog1 prefix-arg
1795 (setq current-prefix-arg prefix-arg)
1796 (setq prefix-arg nil)
1797 (when current-prefix-arg
1798 (prefix-command-update))))))
1799 (if (and (symbolp cmd)
1800 (get cmd 'disabled)
1801 disabled-command-function)
1802 ;; FIXME: Weird calling convention!
1803 (run-hooks 'disabled-command-function)
1804 (let ((final cmd))
1805 (while
1806 (progn
1807 (setq final (indirect-function final))
1808 (if (autoloadp final)
1809 (setq final (autoload-do-load final cmd)))))
1810 (cond
1811 ((arrayp final)
1812 ;; If requested, place the macro in the command history. For
1813 ;; other sorts of commands, call-interactively takes care of this.
1814 (when record-flag
1815 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1816 ;; Don't keep command history around forever.
1817 (when (and (numberp history-length) (> history-length 0))
1818 (let ((cell (nthcdr history-length command-history)))
1819 (if (consp cell) (setcdr cell nil)))))
1820 (execute-kbd-macro final prefixarg))
1822 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1823 (prog1 (call-interactively cmd record-flag keys)
1824 (when (and (symbolp cmd)
1825 (get cmd 'byte-obsolete-info)
1826 (not (get cmd 'command-execute-obsolete-warned)))
1827 (put cmd 'command-execute-obsolete-warned t)
1828 (message "%s" (macroexp--obsolete-warning
1829 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1831 (defvar minibuffer-history nil
1832 "Default minibuffer history list.
1833 This is used for all minibuffer input
1834 except when an alternate history list is specified.
1836 Maximum length of the history list is determined by the value
1837 of `history-length', which see.")
1838 (defvar minibuffer-history-sexp-flag nil
1839 "Control whether history list elements are expressions or strings.
1840 If the value of this variable equals current minibuffer depth,
1841 they are expressions; otherwise they are strings.
1842 \(That convention is designed to do the right thing for
1843 recursive uses of the minibuffer.)")
1844 (setq minibuffer-history-variable 'minibuffer-history)
1845 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1846 (defvar minibuffer-history-search-history nil)
1848 (defvar minibuffer-text-before-history nil
1849 "Text that was in this minibuffer before any history commands.
1850 This is nil if there have not yet been any history commands
1851 in this use of the minibuffer.")
1853 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1855 (defun minibuffer-history-initialize ()
1856 (setq minibuffer-text-before-history nil))
1858 (defun minibuffer-avoid-prompt (_new _old)
1859 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1860 (declare (obsolete cursor-intangible-mode "25.1"))
1861 (constrain-to-field nil (point-max)))
1863 (defcustom minibuffer-history-case-insensitive-variables nil
1864 "Minibuffer history variables for which matching should ignore case.
1865 If a history variable is a member of this list, then the
1866 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1867 commands ignore case when searching it, regardless of `case-fold-search'."
1868 :type '(repeat variable)
1869 :group 'minibuffer)
1871 (defun previous-matching-history-element (regexp n)
1872 "Find the previous history element that matches REGEXP.
1873 \(Previous history elements refer to earlier actions.)
1874 With prefix argument N, search for Nth previous match.
1875 If N is negative, find the next or Nth next match.
1876 Normally, history elements are matched case-insensitively if
1877 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1878 makes the search case-sensitive.
1879 See also `minibuffer-history-case-insensitive-variables'."
1880 (interactive
1881 (let* ((enable-recursive-minibuffers t)
1882 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1884 minibuffer-local-map
1886 'minibuffer-history-search-history
1887 (car minibuffer-history-search-history))))
1888 ;; Use the last regexp specified, by default, if input is empty.
1889 (list (if (string= regexp "")
1890 (if minibuffer-history-search-history
1891 (car minibuffer-history-search-history)
1892 (user-error "No previous history search regexp"))
1893 regexp)
1894 (prefix-numeric-value current-prefix-arg))))
1895 (unless (zerop n)
1896 (if (and (zerop minibuffer-history-position)
1897 (null minibuffer-text-before-history))
1898 (setq minibuffer-text-before-history
1899 (minibuffer-contents-no-properties)))
1900 (let ((history (symbol-value minibuffer-history-variable))
1901 (case-fold-search
1902 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1903 ;; On some systems, ignore case for file names.
1904 (if (memq minibuffer-history-variable
1905 minibuffer-history-case-insensitive-variables)
1907 ;; Respect the user's setting for case-fold-search:
1908 case-fold-search)
1909 nil))
1910 prevpos
1911 match-string
1912 match-offset
1913 (pos minibuffer-history-position))
1914 (while (/= n 0)
1915 (setq prevpos pos)
1916 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1917 (when (= pos prevpos)
1918 (user-error (if (= pos 1)
1919 "No later matching history item"
1920 "No earlier matching history item")))
1921 (setq match-string
1922 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1923 (let ((print-level nil))
1924 (prin1-to-string (nth (1- pos) history)))
1925 (nth (1- pos) history)))
1926 (setq match-offset
1927 (if (< n 0)
1928 (and (string-match regexp match-string)
1929 (match-end 0))
1930 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1931 (match-beginning 1))))
1932 (when match-offset
1933 (setq n (+ n (if (< n 0) 1 -1)))))
1934 (setq minibuffer-history-position pos)
1935 (goto-char (point-max))
1936 (delete-minibuffer-contents)
1937 (insert match-string)
1938 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1939 (if (memq (car (car command-history)) '(previous-matching-history-element
1940 next-matching-history-element))
1941 (setq command-history (cdr command-history))))
1943 (defun next-matching-history-element (regexp n)
1944 "Find the next history element that matches REGEXP.
1945 \(The next history element refers to a more recent action.)
1946 With prefix argument N, search for Nth next match.
1947 If N is negative, find the previous or Nth previous match.
1948 Normally, history elements are matched case-insensitively if
1949 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1950 makes the search case-sensitive."
1951 (interactive
1952 (let* ((enable-recursive-minibuffers t)
1953 (regexp (read-from-minibuffer "Next element matching (regexp): "
1955 minibuffer-local-map
1957 'minibuffer-history-search-history
1958 (car minibuffer-history-search-history))))
1959 ;; Use the last regexp specified, by default, if input is empty.
1960 (list (if (string= regexp "")
1961 (if minibuffer-history-search-history
1962 (car minibuffer-history-search-history)
1963 (user-error "No previous history search regexp"))
1964 regexp)
1965 (prefix-numeric-value current-prefix-arg))))
1966 (previous-matching-history-element regexp (- n)))
1968 (defvar minibuffer-temporary-goal-position nil)
1970 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1971 "Function run by `goto-history-element' before consuming default values.
1972 This is useful to dynamically add more elements to the list of default values
1973 when `goto-history-element' reaches the end of this list.
1974 Before calling this function `goto-history-element' sets the variable
1975 `minibuffer-default-add-done' to t, so it will call this function only
1976 once. In special cases, when this function needs to be called more
1977 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1978 overriding the setting of this variable to t in `goto-history-element'.")
1980 (defvar minibuffer-default-add-done nil
1981 "When nil, add more elements to the end of the list of default values.
1982 The value nil causes `goto-history-element' to add more elements to
1983 the list of defaults when it reaches the end of this list. It does
1984 this by calling a function defined by `minibuffer-default-add-function'.")
1986 (make-variable-buffer-local 'minibuffer-default-add-done)
1988 (defun minibuffer-default-add-completions ()
1989 "Return a list of all completions without the default value.
1990 This function is used to add all elements of the completion table to
1991 the end of the list of defaults just after the default value."
1992 (let ((def minibuffer-default)
1993 (all (all-completions ""
1994 minibuffer-completion-table
1995 minibuffer-completion-predicate)))
1996 (if (listp def)
1997 (append def all)
1998 (cons def (delete def all)))))
2000 (defun goto-history-element (nabs)
2001 "Puts element of the minibuffer history in the minibuffer.
2002 The argument NABS specifies the absolute history position."
2003 (interactive "p")
2004 (when (and (not minibuffer-default-add-done)
2005 (functionp minibuffer-default-add-function)
2006 (< nabs (- (if (listp minibuffer-default)
2007 (length minibuffer-default)
2008 1))))
2009 (setq minibuffer-default-add-done t
2010 minibuffer-default (funcall minibuffer-default-add-function)))
2011 (let ((minimum (if minibuffer-default
2012 (- (if (listp minibuffer-default)
2013 (length minibuffer-default)
2016 elt minibuffer-returned-to-present)
2017 (if (and (zerop minibuffer-history-position)
2018 (null minibuffer-text-before-history))
2019 (setq minibuffer-text-before-history
2020 (minibuffer-contents-no-properties)))
2021 (if (< nabs minimum)
2022 (user-error (if minibuffer-default
2023 "End of defaults; no next item"
2024 "End of history; no default available")))
2025 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
2026 (length (symbol-value minibuffer-history-variable))
2028 (user-error "Beginning of history; no preceding item"))
2029 (unless (memq last-command '(next-history-element
2030 previous-history-element))
2031 (let ((prompt-end (minibuffer-prompt-end)))
2032 (set (make-local-variable 'minibuffer-temporary-goal-position)
2033 (cond ((<= (point) prompt-end) prompt-end)
2034 ((eobp) nil)
2035 (t (point))))))
2036 (goto-char (point-max))
2037 (delete-minibuffer-contents)
2038 (setq minibuffer-history-position nabs)
2039 (cond ((< nabs 0)
2040 (setq elt (if (listp minibuffer-default)
2041 (nth (1- (abs nabs)) minibuffer-default)
2042 minibuffer-default)))
2043 ((= nabs 0)
2044 (setq elt (or minibuffer-text-before-history ""))
2045 (setq minibuffer-returned-to-present t)
2046 (setq minibuffer-text-before-history nil))
2047 (t (setq elt (nth (1- minibuffer-history-position)
2048 (symbol-value minibuffer-history-variable)))))
2049 (insert
2050 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2051 (not minibuffer-returned-to-present))
2052 (let ((print-level nil))
2053 (prin1-to-string elt))
2054 elt))
2055 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2057 (defun next-history-element (n)
2058 "Puts next element of the minibuffer history in the minibuffer.
2059 With argument N, it uses the Nth following element."
2060 (interactive "p")
2061 (or (zerop n)
2062 (goto-history-element (- minibuffer-history-position n))))
2064 (defun previous-history-element (n)
2065 "Puts previous element of the minibuffer history in the minibuffer.
2066 With argument N, it uses the Nth previous element."
2067 (interactive "p")
2068 (or (zerop n)
2069 (goto-history-element (+ minibuffer-history-position n))))
2071 (defun next-line-or-history-element (&optional arg)
2072 "Move cursor vertically down ARG lines, or to the next history element.
2073 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2074 next element of the minibuffer history in the minibuffer."
2075 (interactive "^p")
2076 (or arg (setq arg 1))
2077 (let* ((old-point (point))
2078 ;; Remember the original goal column of possibly multi-line input
2079 ;; excluding the length of the prompt on the first line.
2080 (prompt-end (minibuffer-prompt-end))
2081 (old-column (unless (and (eolp) (> (point) prompt-end))
2082 (if (= (line-number-at-pos) 1)
2083 (max (- (current-column) (1- prompt-end)) 0)
2084 (current-column)))))
2085 (condition-case nil
2086 (with-no-warnings
2087 (next-line arg))
2088 (end-of-buffer
2089 ;; Restore old position since `line-move-visual' moves point to
2090 ;; the end of the line when it fails to go to the next line.
2091 (goto-char old-point)
2092 (next-history-element arg)
2093 ;; Reset `temporary-goal-column' because a correct value is not
2094 ;; calculated when `next-line' above fails by bumping against
2095 ;; the bottom of the minibuffer (bug#22544).
2096 (setq temporary-goal-column 0)
2097 ;; Restore the original goal column on the last line
2098 ;; of possibly multi-line input.
2099 (goto-char (point-max))
2100 (when old-column
2101 (if (= (line-number-at-pos) 1)
2102 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2103 (move-to-column old-column)))))))
2105 (defun previous-line-or-history-element (&optional arg)
2106 "Move cursor vertically up ARG lines, or to the previous history element.
2107 When point moves over the top line of multi-line minibuffer, puts ARGth
2108 previous element of the minibuffer history in the minibuffer."
2109 (interactive "^p")
2110 (or arg (setq arg 1))
2111 (let* ((old-point (point))
2112 ;; Remember the original goal column of possibly multi-line input
2113 ;; excluding the length of the prompt on the first line.
2114 (prompt-end (minibuffer-prompt-end))
2115 (old-column (unless (and (eolp) (> (point) prompt-end))
2116 (if (= (line-number-at-pos) 1)
2117 (max (- (current-column) (1- prompt-end)) 0)
2118 (current-column)))))
2119 (condition-case nil
2120 (with-no-warnings
2121 (previous-line arg))
2122 (beginning-of-buffer
2123 ;; Restore old position since `line-move-visual' moves point to
2124 ;; the beginning of the line when it fails to go to the previous line.
2125 (goto-char old-point)
2126 (previous-history-element arg)
2127 ;; Reset `temporary-goal-column' because a correct value is not
2128 ;; calculated when `previous-line' above fails by bumping against
2129 ;; the top of the minibuffer (bug#22544).
2130 (setq temporary-goal-column 0)
2131 ;; Restore the original goal column on the first line
2132 ;; of possibly multi-line input.
2133 (goto-char (minibuffer-prompt-end))
2134 (if old-column
2135 (if (= (line-number-at-pos) 1)
2136 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2137 (move-to-column old-column))
2138 ;; Put the cursor at the end of the visual line instead of the
2139 ;; logical line, so the next `previous-line-or-history-element'
2140 ;; would move to the previous history element, not to a possible upper
2141 ;; visual line from the end of logical line in `line-move-visual' mode.
2142 (end-of-visual-line)
2143 ;; Since `end-of-visual-line' puts the cursor at the beginning
2144 ;; of the next visual line, move it one char back to the end
2145 ;; of the first visual line (bug#22544).
2146 (unless (eolp) (backward-char 1)))))))
2148 (defun next-complete-history-element (n)
2149 "Get next history element which completes the minibuffer before the point.
2150 The contents of the minibuffer after the point are deleted, and replaced
2151 by the new completion."
2152 (interactive "p")
2153 (let ((point-at-start (point)))
2154 (next-matching-history-element
2155 (concat
2156 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2158 ;; next-matching-history-element always puts us at (point-min).
2159 ;; Move to the position we were at before changing the buffer contents.
2160 ;; This is still sensible, because the text before point has not changed.
2161 (goto-char point-at-start)))
2163 (defun previous-complete-history-element (n)
2165 Get previous history element which completes the minibuffer before the point.
2166 The contents of the minibuffer after the point are deleted, and replaced
2167 by the new completion."
2168 (interactive "p")
2169 (next-complete-history-element (- n)))
2171 ;; For compatibility with the old subr of the same name.
2172 (defun minibuffer-prompt-width ()
2173 "Return the display width of the minibuffer prompt.
2174 Return 0 if current buffer is not a minibuffer."
2175 ;; Return the width of everything before the field at the end of
2176 ;; the buffer; this should be 0 for normal buffers.
2177 (1- (minibuffer-prompt-end)))
2179 ;; isearch minibuffer history
2180 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2182 (defvar minibuffer-history-isearch-message-overlay)
2183 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2185 (defun minibuffer-history-isearch-setup ()
2186 "Set up a minibuffer for using isearch to search the minibuffer history.
2187 Intended to be added to `minibuffer-setup-hook'."
2188 (set (make-local-variable 'isearch-search-fun-function)
2189 'minibuffer-history-isearch-search)
2190 (set (make-local-variable 'isearch-message-function)
2191 'minibuffer-history-isearch-message)
2192 (set (make-local-variable 'isearch-wrap-function)
2193 'minibuffer-history-isearch-wrap)
2194 (set (make-local-variable 'isearch-push-state-function)
2195 'minibuffer-history-isearch-push-state)
2196 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2198 (defun minibuffer-history-isearch-end ()
2199 "Clean up the minibuffer after terminating isearch in the minibuffer."
2200 (if minibuffer-history-isearch-message-overlay
2201 (delete-overlay minibuffer-history-isearch-message-overlay)))
2203 (defun minibuffer-history-isearch-search ()
2204 "Return the proper search function, for isearch in minibuffer history."
2205 (lambda (string bound noerror)
2206 (let ((search-fun
2207 ;; Use standard functions to search within minibuffer text
2208 (isearch-search-fun-default))
2209 found)
2210 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2211 ;; searching forward. Lazy-highlight calls this lambda with the
2212 ;; bound arg, so skip the minibuffer prompt.
2213 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2214 (goto-char (minibuffer-prompt-end)))
2216 ;; 1. First try searching in the initial minibuffer text
2217 (funcall search-fun string
2218 (if isearch-forward bound (minibuffer-prompt-end))
2219 noerror)
2220 ;; 2. If the above search fails, start putting next/prev history
2221 ;; elements in the minibuffer successively, and search the string
2222 ;; in them. Do this only when bound is nil (i.e. not while
2223 ;; lazy-highlighting search strings in the current minibuffer text).
2224 (unless bound
2225 (condition-case nil
2226 (progn
2227 (while (not found)
2228 (cond (isearch-forward
2229 (next-history-element 1)
2230 (goto-char (minibuffer-prompt-end)))
2232 (previous-history-element 1)
2233 (goto-char (point-max))))
2234 (setq isearch-barrier (point) isearch-opoint (point))
2235 ;; After putting the next/prev history element, search
2236 ;; the string in them again, until next-history-element
2237 ;; or previous-history-element raises an error at the
2238 ;; beginning/end of history.
2239 (setq found (funcall search-fun string
2240 (unless isearch-forward
2241 ;; For backward search, don't search
2242 ;; in the minibuffer prompt
2243 (minibuffer-prompt-end))
2244 noerror)))
2245 ;; Return point of the new search result
2246 (point))
2247 ;; Return nil when next(prev)-history-element fails
2248 (error nil)))))))
2250 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2251 "Display the minibuffer history search prompt.
2252 If there are no search errors, this function displays an overlay with
2253 the isearch prompt which replaces the original minibuffer prompt.
2254 Otherwise, it displays the standard isearch message returned from
2255 the function `isearch-message'."
2256 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2257 ;; Use standard function `isearch-message' when not in the minibuffer,
2258 ;; or search fails, or has an error (like incomplete regexp).
2259 ;; This function overwrites minibuffer text with isearch message,
2260 ;; so it's possible to see what is wrong in the search string.
2261 (isearch-message c-q-hack ellipsis)
2262 ;; Otherwise, put the overlay with the standard isearch prompt over
2263 ;; the initial minibuffer prompt.
2264 (if (overlayp minibuffer-history-isearch-message-overlay)
2265 (move-overlay minibuffer-history-isearch-message-overlay
2266 (point-min) (minibuffer-prompt-end))
2267 (setq minibuffer-history-isearch-message-overlay
2268 (make-overlay (point-min) (minibuffer-prompt-end)))
2269 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2270 (overlay-put minibuffer-history-isearch-message-overlay
2271 'display (isearch-message-prefix c-q-hack ellipsis))
2272 ;; And clear any previous isearch message.
2273 (message "")))
2275 (defun minibuffer-history-isearch-wrap ()
2276 "Wrap the minibuffer history search when search fails.
2277 Move point to the first history element for a forward search,
2278 or to the last history element for a backward search."
2279 ;; When `minibuffer-history-isearch-search' fails on reaching the
2280 ;; beginning/end of the history, wrap the search to the first/last
2281 ;; minibuffer history element.
2282 (if isearch-forward
2283 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2284 (goto-history-element 0))
2285 (setq isearch-success t)
2286 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2288 (defun minibuffer-history-isearch-push-state ()
2289 "Save a function restoring the state of minibuffer history search.
2290 Save `minibuffer-history-position' to the additional state parameter
2291 in the search status stack."
2292 (let ((pos minibuffer-history-position))
2293 (lambda (cmd)
2294 (minibuffer-history-isearch-pop-state cmd pos))))
2296 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2297 "Restore the minibuffer history search state.
2298 Go to the history element by the absolute history position HIST-POS."
2299 (goto-history-element hist-pos))
2302 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2303 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2305 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2306 "Table mapping redo records to the corresponding undo one.
2307 A redo record for undo-in-region maps to t.
2308 A redo record for ordinary undo maps to the following (earlier) undo.")
2310 (defvar undo-in-region nil
2311 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2313 (defvar undo-no-redo nil
2314 "If t, `undo' doesn't go through redo entries.")
2316 (defvar pending-undo-list nil
2317 "Within a run of consecutive undo commands, list remaining to be undone.
2318 If t, we undid all the way to the end of it.")
2320 (defun undo (&optional arg)
2321 "Undo some previous changes.
2322 Repeat this command to undo more changes.
2323 A numeric ARG serves as a repeat count.
2325 In Transient Mark mode when the mark is active, only undo changes within
2326 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2327 as an argument limits undo to changes within the current region."
2328 (interactive "*P")
2329 ;; Make last-command indicate for the next command that this was an undo.
2330 ;; That way, another undo will undo more.
2331 ;; If we get to the end of the undo history and get an error,
2332 ;; another undo command will find the undo history empty
2333 ;; and will get another error. To begin undoing the undos,
2334 ;; you must type some other command.
2335 (let* ((modified (buffer-modified-p))
2336 ;; For an indirect buffer, look in the base buffer for the
2337 ;; auto-save data.
2338 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2339 (recent-save (with-current-buffer base-buffer
2340 (recent-auto-save-p)))
2341 message)
2342 ;; If we get an error in undo-start,
2343 ;; the next command should not be a "consecutive undo".
2344 ;; So set `this-command' to something other than `undo'.
2345 (setq this-command 'undo-start)
2347 (unless (and (eq last-command 'undo)
2348 (or (eq pending-undo-list t)
2349 ;; If something (a timer or filter?) changed the buffer
2350 ;; since the previous command, don't continue the undo seq.
2351 (let ((list buffer-undo-list))
2352 (while (eq (car list) nil)
2353 (setq list (cdr list)))
2354 ;; If the last undo record made was made by undo
2355 ;; it shows nothing else happened in between.
2356 (gethash list undo-equiv-table))))
2357 (setq undo-in-region
2358 (or (region-active-p) (and arg (not (numberp arg)))))
2359 (if undo-in-region
2360 (undo-start (region-beginning) (region-end))
2361 (undo-start))
2362 ;; get rid of initial undo boundary
2363 (undo-more 1))
2364 ;; If we got this far, the next command should be a consecutive undo.
2365 (setq this-command 'undo)
2366 ;; Check to see whether we're hitting a redo record, and if
2367 ;; so, ask the user whether she wants to skip the redo/undo pair.
2368 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2369 (or (eq (selected-window) (minibuffer-window))
2370 (setq message (format "%s%s!"
2371 (if (or undo-no-redo (not equiv))
2372 "Undo" "Redo")
2373 (if undo-in-region " in region" ""))))
2374 (when (and (consp equiv) undo-no-redo)
2375 ;; The equiv entry might point to another redo record if we have done
2376 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2377 (while (let ((next (gethash equiv undo-equiv-table)))
2378 (if next (setq equiv next))))
2379 (setq pending-undo-list equiv)))
2380 (undo-more
2381 (if (numberp arg)
2382 (prefix-numeric-value arg)
2384 ;; Record the fact that the just-generated undo records come from an
2385 ;; undo operation--that is, they are redo records.
2386 ;; In the ordinary case (not within a region), map the redo
2387 ;; record to the following undos.
2388 ;; I don't know how to do that in the undo-in-region case.
2389 (let ((list buffer-undo-list))
2390 ;; Strip any leading undo boundaries there might be, like we do
2391 ;; above when checking.
2392 (while (eq (car list) nil)
2393 (setq list (cdr list)))
2394 (puthash list
2395 ;; Prevent identity mapping. This can happen if
2396 ;; consecutive nils are erroneously in undo list.
2397 (if (or undo-in-region (eq list pending-undo-list))
2399 pending-undo-list)
2400 undo-equiv-table))
2401 ;; Don't specify a position in the undo record for the undo command.
2402 ;; Instead, undoing this should move point to where the change is.
2403 (let ((tail buffer-undo-list)
2404 (prev nil))
2405 (while (car tail)
2406 (when (integerp (car tail))
2407 (let ((pos (car tail)))
2408 (if prev
2409 (setcdr prev (cdr tail))
2410 (setq buffer-undo-list (cdr tail)))
2411 (setq tail (cdr tail))
2412 (while (car tail)
2413 (if (eq pos (car tail))
2414 (if prev
2415 (setcdr prev (cdr tail))
2416 (setq buffer-undo-list (cdr tail)))
2417 (setq prev tail))
2418 (setq tail (cdr tail)))
2419 (setq tail nil)))
2420 (setq prev tail tail (cdr tail))))
2421 ;; Record what the current undo list says,
2422 ;; so the next command can tell if the buffer was modified in between.
2423 (and modified (not (buffer-modified-p))
2424 (with-current-buffer base-buffer
2425 (delete-auto-save-file-if-necessary recent-save)))
2426 ;; Display a message announcing success.
2427 (if message
2428 (message "%s" message))))
2430 (defun buffer-disable-undo (&optional buffer)
2431 "Make BUFFER stop keeping undo information.
2432 No argument or nil as argument means do this for the current buffer."
2433 (interactive)
2434 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2435 (setq buffer-undo-list t)))
2437 (defun undo-only (&optional arg)
2438 "Undo some previous changes.
2439 Repeat this command to undo more changes.
2440 A numeric ARG serves as a repeat count.
2441 Contrary to `undo', this will not redo a previous undo."
2442 (interactive "*p")
2443 (let ((undo-no-redo t)) (undo arg)))
2445 (defvar undo-in-progress nil
2446 "Non-nil while performing an undo.
2447 Some change-hooks test this variable to do something different.")
2449 (defun undo-more (n)
2450 "Undo back N undo-boundaries beyond what was already undone recently.
2451 Call `undo-start' to get ready to undo recent changes,
2452 then call `undo-more' one or more times to undo them."
2453 (or (listp pending-undo-list)
2454 (user-error (concat "No further undo information"
2455 (and undo-in-region " for region"))))
2456 (let ((undo-in-progress t))
2457 ;; Note: The following, while pulling elements off
2458 ;; `pending-undo-list' will call primitive change functions which
2459 ;; will push more elements onto `buffer-undo-list'.
2460 (setq pending-undo-list (primitive-undo n pending-undo-list))
2461 (if (null pending-undo-list)
2462 (setq pending-undo-list t))))
2464 (defun primitive-undo (n list)
2465 "Undo N records from the front of the list LIST.
2466 Return what remains of the list."
2468 ;; This is a good feature, but would make undo-start
2469 ;; unable to do what is expected.
2470 ;;(when (null (car (list)))
2471 ;; ;; If the head of the list is a boundary, it is the boundary
2472 ;; ;; preceding this command. Get rid of it and don't count it.
2473 ;; (setq list (cdr list))))
2475 (let ((arg n)
2476 ;; In a writable buffer, enable undoing read-only text that is
2477 ;; so because of text properties.
2478 (inhibit-read-only t)
2479 ;; Don't let `intangible' properties interfere with undo.
2480 (inhibit-point-motion-hooks t)
2481 ;; We use oldlist only to check for EQ. ++kfs
2482 (oldlist buffer-undo-list)
2483 (did-apply nil)
2484 (next nil))
2485 (while (> arg 0)
2486 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2487 ;; Handle an integer by setting point to that value.
2488 (pcase next
2489 ((pred integerp) (goto-char next))
2490 ;; Element (t . TIME) records previous modtime.
2491 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2492 ;; UNKNOWN_MODTIME_NSECS.
2493 (`(t . ,time)
2494 ;; If this records an obsolete save
2495 ;; (not matching the actual disk file)
2496 ;; then don't mark unmodified.
2497 (when (or (equal time (visited-file-modtime))
2498 (and (consp time)
2499 (equal (list (car time) (cdr time))
2500 (visited-file-modtime))))
2501 (when (fboundp 'unlock-buffer)
2502 (unlock-buffer))
2503 (set-buffer-modified-p nil)))
2504 ;; Element (nil PROP VAL BEG . END) is property change.
2505 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2506 (when (or (> (point-min) beg) (< (point-max) end))
2507 (error "Changes to be undone are outside visible portion of buffer"))
2508 (put-text-property beg end prop val))
2509 ;; Element (BEG . END) means range was inserted.
2510 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2511 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2512 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2513 (when (or (> (point-min) beg) (< (point-max) end))
2514 (error "Changes to be undone are outside visible portion of buffer"))
2515 ;; Set point first thing, so that undoing this undo
2516 ;; does not send point back to where it is now.
2517 (goto-char beg)
2518 (delete-region beg end))
2519 ;; Element (apply FUN . ARGS) means call FUN to undo.
2520 (`(apply . ,fun-args)
2521 (let ((currbuff (current-buffer)))
2522 (if (integerp (car fun-args))
2523 ;; Long format: (apply DELTA START END FUN . ARGS).
2524 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2525 (start-mark (copy-marker start nil))
2526 (end-mark (copy-marker end t)))
2527 (when (or (> (point-min) start) (< (point-max) end))
2528 (error "Changes to be undone are outside visible portion of buffer"))
2529 (apply fun args) ;; Use `save-current-buffer'?
2530 ;; Check that the function did what the entry
2531 ;; said it would do.
2532 (unless (and (= start start-mark)
2533 (= (+ delta end) end-mark))
2534 (error "Changes to be undone by function different than announced"))
2535 (set-marker start-mark nil)
2536 (set-marker end-mark nil))
2537 (apply fun-args))
2538 (unless (eq currbuff (current-buffer))
2539 (error "Undo function switched buffer"))
2540 (setq did-apply t)))
2541 ;; Element (STRING . POS) means STRING was deleted.
2542 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2543 (when (let ((apos (abs pos)))
2544 (or (< apos (point-min)) (> apos (point-max))))
2545 (error "Changes to be undone are outside visible portion of buffer"))
2546 (let (valid-marker-adjustments)
2547 ;; Check that marker adjustments which were recorded
2548 ;; with the (STRING . POS) record are still valid, ie
2549 ;; the markers haven't moved. We check their validity
2550 ;; before reinserting the string so as we don't need to
2551 ;; mind marker insertion-type.
2552 (while (and (markerp (car-safe (car list)))
2553 (integerp (cdr-safe (car list))))
2554 (let* ((marker-adj (pop list))
2555 (m (car marker-adj)))
2556 (and (eq (marker-buffer m) (current-buffer))
2557 (= pos m)
2558 (push marker-adj valid-marker-adjustments))))
2559 ;; Insert string and adjust point
2560 (if (< pos 0)
2561 (progn
2562 (goto-char (- pos))
2563 (insert string))
2564 (goto-char pos)
2565 (insert string)
2566 (goto-char pos))
2567 ;; Adjust the valid marker adjustments
2568 (dolist (adj valid-marker-adjustments)
2569 (set-marker (car adj)
2570 (- (car adj) (cdr adj))))))
2571 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2572 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2573 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2574 next)
2575 ;; Even though these elements are not expected in the undo
2576 ;; list, adjust them to be conservative for the 24.4
2577 ;; release. (Bug#16818)
2578 (when (marker-buffer marker)
2579 (set-marker marker
2580 (- marker offset)
2581 (marker-buffer marker))))
2582 (_ (error "Unrecognized entry in undo list %S" next))))
2583 (setq arg (1- arg)))
2584 ;; Make sure an apply entry produces at least one undo entry,
2585 ;; so the test in `undo' for continuing an undo series
2586 ;; will work right.
2587 (if (and did-apply
2588 (eq oldlist buffer-undo-list))
2589 (setq buffer-undo-list
2590 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2591 list)
2593 ;; Deep copy of a list
2594 (defun undo-copy-list (list)
2595 "Make a copy of undo list LIST."
2596 (mapcar 'undo-copy-list-1 list))
2598 (defun undo-copy-list-1 (elt)
2599 (if (consp elt)
2600 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2601 elt))
2603 (defun undo-start (&optional beg end)
2604 "Set `pending-undo-list' to the front of the undo list.
2605 The next call to `undo-more' will undo the most recently made change.
2606 If BEG and END are specified, then only undo elements
2607 that apply to text between BEG and END are used; other undo elements
2608 are ignored. If BEG and END are nil, all undo elements are used."
2609 (if (eq buffer-undo-list t)
2610 (user-error "No undo information in this buffer"))
2611 (setq pending-undo-list
2612 (if (and beg end (not (= beg end)))
2613 (undo-make-selective-list (min beg end) (max beg end))
2614 buffer-undo-list)))
2616 ;; The positions given in elements of the undo list are the positions
2617 ;; as of the time that element was recorded to undo history. In
2618 ;; general, subsequent buffer edits render those positions invalid in
2619 ;; the current buffer, unless adjusted according to the intervening
2620 ;; undo elements.
2622 ;; Undo in region is a use case that requires adjustments to undo
2623 ;; elements. It must adjust positions of elements in the region based
2624 ;; on newer elements not in the region so as they may be correctly
2625 ;; applied in the current buffer. undo-make-selective-list
2626 ;; accomplishes this with its undo-deltas list of adjustments. An
2627 ;; example undo history from oldest to newest:
2629 ;; buf pos:
2630 ;; 123456789 buffer-undo-list undo-deltas
2631 ;; --------- ---------------- -----------
2632 ;; aaa (1 . 4) (1 . -3)
2633 ;; aaba (3 . 4) N/A (in region)
2634 ;; ccaaba (1 . 3) (1 . -2)
2635 ;; ccaabaddd (7 . 10) (7 . -3)
2636 ;; ccaabdd ("ad" . 6) (6 . 2)
2637 ;; ccaabaddd (6 . 8) (6 . -2)
2638 ;; | |<-- region: "caab", from 2 to 6
2640 ;; When the user starts a run of undos in region,
2641 ;; undo-make-selective-list is called to create the full list of in
2642 ;; region elements. Each element is adjusted forward chronologically
2643 ;; through undo-deltas to determine if it is in the region.
2645 ;; In the above example, the insertion of "b" is (3 . 4) in the
2646 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2647 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2648 ;; . 6) is assessed as in the region and placed in the selective list.
2649 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2650 ;; due to the selected element. The "b" insertion is the only element
2651 ;; fully in the region, so in this example undo-make-selective-list
2652 ;; returns (nil (5 . 6)).
2654 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2655 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2656 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2657 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2658 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2660 ;; More interesting is how to adjust the "ddd" insertion due to the
2661 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2662 ;; If the reinsertion was a manual retyping of "ad", then the total
2663 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2664 ;; the reinsertion was due to undo, one might expect the first "d"
2665 ;; character would again be a part of the "ddd" text, meaning its
2666 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2668 ;; undo-make-selective-list assumes in this situation that "ad" was a
2669 ;; new edit, even if it was inserted because of an undo.
2670 ;; Consequently, if the user undos in region "8 to 10" of the
2671 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2672 ;; "ccaabad", as though the first "d" became detached from the
2673 ;; original "ddd" insertion. This quirk is a FIXME.
2675 (defun undo-make-selective-list (start end)
2676 "Return a list of undo elements for the region START to END.
2677 The elements come from `buffer-undo-list', but we keep only the
2678 elements inside this region, and discard those outside this
2679 region. The elements' positions are adjusted so as the returned
2680 list can be applied to the current buffer."
2681 (let ((ulist buffer-undo-list)
2682 ;; A list of position adjusted undo elements in the region.
2683 (selective-list (list nil))
2684 ;; A list of undo-deltas for out of region undo elements.
2685 undo-deltas
2686 undo-elt)
2687 (while ulist
2688 (when undo-no-redo
2689 (while (gethash ulist undo-equiv-table)
2690 (setq ulist (gethash ulist undo-equiv-table))))
2691 (setq undo-elt (car ulist))
2692 (cond
2693 ((null undo-elt)
2694 ;; Don't put two nils together in the list
2695 (when (car selective-list)
2696 (push nil selective-list)))
2697 ((and (consp undo-elt) (eq (car undo-elt) t))
2698 ;; This is a "was unmodified" element. Keep it
2699 ;; if we have kept everything thus far.
2700 (when (not undo-deltas)
2701 (push undo-elt selective-list)))
2702 ;; Skip over marker adjustments, instead relying
2703 ;; on finding them after (TEXT . POS) elements
2704 ((markerp (car-safe undo-elt))
2705 nil)
2707 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2708 undo-deltas)))
2709 (if (undo-elt-in-region adjusted-undo-elt start end)
2710 (progn
2711 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2712 (push adjusted-undo-elt selective-list)
2713 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2714 ;; kept. primitive-undo may discard them later.
2715 (when (and (stringp (car-safe adjusted-undo-elt))
2716 (integerp (cdr-safe adjusted-undo-elt)))
2717 (let ((list-i (cdr ulist)))
2718 (while (markerp (car-safe (car list-i)))
2719 (push (pop list-i) selective-list)))))
2720 (let ((delta (undo-delta undo-elt)))
2721 (when (/= 0 (cdr delta))
2722 (push delta undo-deltas)))))))
2723 (pop ulist))
2724 (nreverse selective-list)))
2726 (defun undo-elt-in-region (undo-elt start end)
2727 "Determine whether UNDO-ELT falls inside the region START ... END.
2728 If it crosses the edge, we return nil.
2730 Generally this function is not useful for determining
2731 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2732 because markers can be arbitrarily relocated. Instead, pass the
2733 marker adjustment's corresponding (TEXT . POS) element."
2734 (cond ((integerp undo-elt)
2735 (and (>= undo-elt start)
2736 (<= undo-elt end)))
2737 ((eq undo-elt nil)
2739 ((atom undo-elt)
2740 nil)
2741 ((stringp (car undo-elt))
2742 ;; (TEXT . POSITION)
2743 (and (>= (abs (cdr undo-elt)) start)
2744 (<= (abs (cdr undo-elt)) end)))
2745 ((and (consp undo-elt) (markerp (car undo-elt)))
2746 ;; (MARKER . ADJUSTMENT)
2747 (<= start (car undo-elt) end))
2748 ((null (car undo-elt))
2749 ;; (nil PROPERTY VALUE BEG . END)
2750 (let ((tail (nthcdr 3 undo-elt)))
2751 (and (>= (car tail) start)
2752 (<= (cdr tail) end))))
2753 ((integerp (car undo-elt))
2754 ;; (BEGIN . END)
2755 (and (>= (car undo-elt) start)
2756 (<= (cdr undo-elt) end)))))
2758 (defun undo-elt-crosses-region (undo-elt start end)
2759 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2760 This assumes we have already decided that UNDO-ELT
2761 is not *inside* the region START...END."
2762 (declare (obsolete nil "25.1"))
2763 (cond ((atom undo-elt) nil)
2764 ((null (car undo-elt))
2765 ;; (nil PROPERTY VALUE BEG . END)
2766 (let ((tail (nthcdr 3 undo-elt)))
2767 (and (< (car tail) end)
2768 (> (cdr tail) start))))
2769 ((integerp (car undo-elt))
2770 ;; (BEGIN . END)
2771 (and (< (car undo-elt) end)
2772 (> (cdr undo-elt) start)))))
2774 (defun undo-adjust-elt (elt deltas)
2775 "Return adjustment of undo element ELT by the undo DELTAS
2776 list."
2777 (pcase elt
2778 ;; POSITION
2779 ((pred integerp)
2780 (undo-adjust-pos elt deltas))
2781 ;; (BEG . END)
2782 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2783 (undo-adjust-beg-end beg end deltas))
2784 ;; (TEXT . POSITION)
2785 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2786 (cons text (* (if (< pos 0) -1 1)
2787 (undo-adjust-pos (abs pos) deltas))))
2788 ;; (nil PROPERTY VALUE BEG . END)
2789 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2790 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2791 ;; (apply DELTA START END FUN . ARGS)
2792 ;; FIXME
2793 ;; All others return same elt
2794 (_ elt)))
2796 ;; (BEG . END) can adjust to the same positions, commonly when an
2797 ;; insertion was undone and they are out of region, for example:
2799 ;; buf pos:
2800 ;; 123456789 buffer-undo-list undo-deltas
2801 ;; --------- ---------------- -----------
2802 ;; [...]
2803 ;; abbaa (2 . 4) (2 . -2)
2804 ;; aaa ("bb" . 2) (2 . 2)
2805 ;; [...]
2807 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2808 ;; undo. Further adjustments to such an element should be the same as
2809 ;; for (TEXT . POSITION) elements. The options are:
2811 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2812 ;; analogous to marker insertion-type t.
2814 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2815 ;; marker insertion-type nil.
2817 ;; There was no strong reason to prefer one or the other, except that
2818 ;; the first is more consistent with prior undo in region behavior.
2819 (defun undo-adjust-beg-end (beg end deltas)
2820 "Return cons of adjustments to BEG and END by the undo DELTAS
2821 list."
2822 (let ((adj-beg (undo-adjust-pos beg deltas)))
2823 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2824 (cons adj-beg
2825 (max adj-beg (undo-adjust-pos end deltas t)))))
2827 (defun undo-adjust-pos (pos deltas &optional use-<)
2828 "Return adjustment of POS by the undo DELTAS list, comparing
2829 with < or <= based on USE-<."
2830 (dolist (d deltas pos)
2831 (when (if use-<
2832 (< (car d) pos)
2833 (<= (car d) pos))
2834 (setq pos
2835 ;; Don't allow pos to become less than the undo-delta
2836 ;; position. This edge case is described in the overview
2837 ;; comments.
2838 (max (car d) (- pos (cdr d)))))))
2840 ;; Return the first affected buffer position and the delta for an undo element
2841 ;; delta is defined as the change in subsequent buffer positions if we *did*
2842 ;; the undo.
2843 (defun undo-delta (undo-elt)
2844 (if (consp undo-elt)
2845 (cond ((stringp (car undo-elt))
2846 ;; (TEXT . POSITION)
2847 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2848 ((integerp (car undo-elt))
2849 ;; (BEGIN . END)
2850 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2852 '(0 . 0)))
2853 '(0 . 0)))
2855 ;;; Default undo-boundary addition
2857 ;; This section adds a new undo-boundary at either after a command is
2858 ;; called or in some cases on a timer called after a change is made in
2859 ;; any buffer.
2860 (defvar-local undo-auto--last-boundary-cause nil
2861 "Describe the cause of the last undo-boundary.
2863 If `explicit', the last boundary was caused by an explicit call to
2864 `undo-boundary', that is one not called by the code in this
2865 section.
2867 If it is equal to `timer', then the last boundary was inserted
2868 by `undo-auto--boundary-timer'.
2870 If it is equal to `command', then the last boundary was inserted
2871 automatically after a command, that is by the code defined in
2872 this section.
2874 If it is equal to a list, then the last boundary was inserted by
2875 an amalgamating command. The car of the list is the number of
2876 times an amalgamating command has been called, and the cdr are the
2877 buffers that were changed during the last command.")
2879 (defvar undo-auto-current-boundary-timer nil
2880 "Current timer which will run `undo-auto--boundary-timer' or nil.
2882 If set to non-nil, this will effectively disable the timer.")
2884 (defvar undo-auto--this-command-amalgamating nil
2885 "Non-nil if `this-command' should be amalgamated.
2886 This variable is set to nil by `undo-auto--boundaries' and is set
2887 by `undo-auto-amalgamate'." )
2889 (defun undo-auto--needs-boundary-p ()
2890 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2891 (car-safe buffer-undo-list))
2893 (defun undo-auto--last-boundary-amalgamating-number ()
2894 "Return the number of amalgamating last commands or nil.
2895 Amalgamating commands are, by default, either
2896 `self-insert-command' and `delete-char', but can be any command
2897 that calls `undo-auto-amalgamate'."
2898 (car-safe undo-auto--last-boundary-cause))
2900 (defun undo-auto--ensure-boundary (cause)
2901 "Add an `undo-boundary' to the current buffer if needed.
2902 REASON describes the reason that the boundary is being added; see
2903 `undo-auto--last-boundary' for more information."
2904 (when (and
2905 (undo-auto--needs-boundary-p))
2906 (let ((last-amalgamating
2907 (undo-auto--last-boundary-amalgamating-number)))
2908 (undo-boundary)
2909 (setq undo-auto--last-boundary-cause
2910 (if (eq 'amalgamate cause)
2911 (cons
2912 (if last-amalgamating (1+ last-amalgamating) 0)
2913 undo-auto--undoably-changed-buffers)
2914 cause)))))
2916 (defun undo-auto--boundaries (cause)
2917 "Check recently changed buffers and add a boundary if necessary.
2918 REASON describes the reason that the boundary is being added; see
2919 `undo-last-boundary' for more information."
2920 ;; (Bug #23785) All commands should ensure that there is an undo
2921 ;; boundary whether they have changed the current buffer or not.
2922 (when (eq cause 'command)
2923 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2924 (dolist (b undo-auto--undoably-changed-buffers)
2925 (when (buffer-live-p b)
2926 (with-current-buffer b
2927 (undo-auto--ensure-boundary cause))))
2928 (setq undo-auto--undoably-changed-buffers nil))
2930 (defun undo-auto--boundary-timer ()
2931 "Timer which will run `undo--auto-boundary-timer'."
2932 (setq undo-auto-current-boundary-timer nil)
2933 (undo-auto--boundaries 'timer))
2935 (defun undo-auto--boundary-ensure-timer ()
2936 "Ensure that the `undo-auto-boundary-timer' is set."
2937 (unless undo-auto-current-boundary-timer
2938 (setq undo-auto-current-boundary-timer
2939 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2941 (defvar undo-auto--undoably-changed-buffers nil
2942 "List of buffers that have changed recently.
2944 This list is maintained by `undo-auto--undoable-change' and
2945 `undo-auto--boundaries' and can be affected by changes to their
2946 default values.")
2948 (defun undo-auto--add-boundary ()
2949 "Add an `undo-boundary' in appropriate buffers."
2950 (undo-auto--boundaries
2951 (let ((amal undo-auto--this-command-amalgamating))
2952 (setq undo-auto--this-command-amalgamating nil)
2953 (if amal
2954 'amalgamate
2955 'command))))
2957 (defun undo-auto-amalgamate ()
2958 "Amalgamate undo if necessary.
2959 This function can be called before an amalgamating command. It
2960 removes the previous `undo-boundary' if a series of such calls
2961 have been made. By default `self-insert-command' and
2962 `delete-char' are the only amalgamating commands, although this
2963 function could be called by any command wishing to have this
2964 behavior."
2965 (let ((last-amalgamating-count
2966 (undo-auto--last-boundary-amalgamating-number)))
2967 (setq undo-auto--this-command-amalgamating t)
2968 (when
2969 last-amalgamating-count
2971 (and
2972 (< last-amalgamating-count 20)
2973 (eq this-command last-command))
2974 ;; Amalgamate all buffers that have changed.
2975 (dolist (b (cdr undo-auto--last-boundary-cause))
2976 (when (buffer-live-p b)
2977 (with-current-buffer
2979 (when
2980 ;; The head of `buffer-undo-list' is nil.
2981 ;; `car-safe' doesn't work because
2982 ;; `buffer-undo-list' need not be a list!
2983 (and (listp buffer-undo-list)
2984 (not (car buffer-undo-list)))
2985 (setq buffer-undo-list
2986 (cdr buffer-undo-list))))))
2987 (setq undo-auto--last-boundary-cause 0)))))
2989 (defun undo-auto--undoable-change ()
2990 "Called after every undoable buffer change."
2991 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
2992 (undo-auto--boundary-ensure-timer))
2993 ;; End auto-boundary section
2995 (defun undo-amalgamate-change-group (handle)
2996 "Amalgamate changes in change-group since HANDLE.
2997 Remove all undo boundaries between the state of HANDLE and now.
2998 HANDLE is as returned by `prepare-change-group'."
2999 (dolist (elt handle)
3000 (with-current-buffer (car elt)
3001 (setq elt (cdr elt))
3002 (when (consp buffer-undo-list)
3003 (let ((old-car (car-safe elt))
3004 (old-cdr (cdr-safe elt)))
3005 (unwind-protect
3006 (progn
3007 ;; Temporarily truncate the undo log at ELT.
3008 (when (consp elt)
3009 (setcar elt t) (setcdr elt nil))
3010 (when
3011 (or (null elt) ;The undo-log was empty.
3012 ;; `elt' is still in the log: normal case.
3013 (eq elt (last buffer-undo-list))
3014 ;; `elt' is not in the log any more, but that's because
3015 ;; the log is "all new", so we should remove all
3016 ;; boundaries from it.
3017 (not (eq (last buffer-undo-list) (last old-cdr))))
3018 (cl-callf (lambda (x) (delq nil x))
3019 (if (car buffer-undo-list)
3020 buffer-undo-list
3021 ;; Preserve the undo-boundaries at either ends of the
3022 ;; change-groups.
3023 (cdr buffer-undo-list)))))
3024 ;; Reset the modified cons cell ELT to its original content.
3025 (when (consp elt)
3026 (setcar elt old-car)
3027 (setcdr elt old-cdr))))))))
3030 (defcustom undo-ask-before-discard nil
3031 "If non-nil ask about discarding undo info for the current command.
3032 Normally, Emacs discards the undo info for the current command if
3033 it exceeds `undo-outer-limit'. But if you set this option
3034 non-nil, it asks in the echo area whether to discard the info.
3035 If you answer no, there is a slight risk that Emacs might crash, so
3036 only do it if you really want to undo the command.
3038 This option is mainly intended for debugging. You have to be
3039 careful if you use it for other purposes. Garbage collection is
3040 inhibited while the question is asked, meaning that Emacs might
3041 leak memory. So you should make sure that you do not wait
3042 excessively long before answering the question."
3043 :type 'boolean
3044 :group 'undo
3045 :version "22.1")
3047 (defvar undo-extra-outer-limit nil
3048 "If non-nil, an extra level of size that's ok in an undo item.
3049 We don't ask the user about truncating the undo list until the
3050 current item gets bigger than this amount.
3052 This variable only matters if `undo-ask-before-discard' is non-nil.")
3053 (make-variable-buffer-local 'undo-extra-outer-limit)
3055 ;; When the first undo batch in an undo list is longer than
3056 ;; undo-outer-limit, this function gets called to warn the user that
3057 ;; the undo info for the current command was discarded. Garbage
3058 ;; collection is inhibited around the call, so it had better not do a
3059 ;; lot of consing.
3060 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3061 (defun undo-outer-limit-truncate (size)
3062 (if undo-ask-before-discard
3063 (when (or (null undo-extra-outer-limit)
3064 (> size undo-extra-outer-limit))
3065 ;; Don't ask the question again unless it gets even bigger.
3066 ;; This applies, in particular, if the user quits from the question.
3067 ;; Such a quit quits out of GC, but something else will call GC
3068 ;; again momentarily. It will call this function again,
3069 ;; but we don't want to ask the question again.
3070 (setq undo-extra-outer-limit (+ size 50000))
3071 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3072 (yes-or-no-p (format-message
3073 "Buffer `%s' undo info is %d bytes long; discard it? "
3074 (buffer-name) size)))
3075 (progn (setq buffer-undo-list nil)
3076 (setq undo-extra-outer-limit nil)
3078 nil))
3079 (display-warning '(undo discard-info)
3080 (concat
3081 (format-message
3082 "Buffer `%s' undo info was %d bytes long.\n"
3083 (buffer-name) size)
3084 "The undo info was discarded because it exceeded \
3085 `undo-outer-limit'.
3087 This is normal if you executed a command that made a huge change
3088 to the buffer. In that case, to prevent similar problems in the
3089 future, set `undo-outer-limit' to a value that is large enough to
3090 cover the maximum size of normal changes you expect a single
3091 command to make, but not so large that it might exceed the
3092 maximum memory allotted to Emacs.
3094 If you did not execute any such command, the situation is
3095 probably due to a bug and you should report it.
3097 You can disable the popping up of this buffer by adding the entry
3098 \(undo discard-info) to the user option `warning-suppress-types',
3099 which is defined in the `warnings' library.\n")
3100 :warning)
3101 (setq buffer-undo-list nil)
3104 (defcustom password-word-equivalents
3105 '("password" "passcode" "passphrase" "pass phrase"
3106 ; These are sorted according to the GNU en_US locale.
3107 "암호" ; ko
3108 "パスワード" ; ja
3109 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3110 "ពាក្យសម្ងាត់" ; km
3111 "adgangskode" ; da
3112 "contraseña" ; es
3113 "contrasenya" ; ca
3114 "geslo" ; sl
3115 "hasło" ; pl
3116 "heslo" ; cs, sk
3117 "iphasiwedi" ; zu
3118 "jelszó" ; hu
3119 "lösenord" ; sv
3120 "lozinka" ; hr, sr
3121 "mật khẩu" ; vi
3122 "mot de passe" ; fr
3123 "parola" ; tr
3124 "pasahitza" ; eu
3125 "passord" ; nb
3126 "passwort" ; de
3127 "pasvorto" ; eo
3128 "salasana" ; fi
3129 "senha" ; pt
3130 "slaptažodis" ; lt
3131 "wachtwoord" ; nl
3132 "كلمة السر" ; ar
3133 "ססמה" ; he
3134 "лозинка" ; sr
3135 "пароль" ; kk, ru, uk
3136 "गुप्तशब्द" ; mr
3137 "शब्दकूट" ; hi
3138 "પાસવર્ડ" ; gu
3139 "సంకేతపదము" ; te
3140 "ਪਾਸਵਰਡ" ; pa
3141 "ಗುಪ್ತಪದ" ; kn
3142 "கடவுச்சொல்" ; ta
3143 "അടയാളവാക്ക്" ; ml
3144 "গুপ্তশব্দ" ; as
3145 "পাসওয়ার্ড" ; bn_IN
3146 "රහස්පදය" ; si
3147 "密码" ; zh_CN
3148 "密碼" ; zh_TW
3150 "List of words equivalent to \"password\".
3151 This is used by Shell mode and other parts of Emacs to recognize
3152 password prompts, including prompts in languages other than
3153 English. Different case choices should not be assumed to be
3154 included; callers should bind `case-fold-search' to t."
3155 :type '(repeat string)
3156 :version "24.4"
3157 :group 'processes)
3159 (defvar shell-command-history nil
3160 "History list for some commands that read shell commands.
3162 Maximum length of the history list is determined by the value
3163 of `history-length', which see.")
3165 (defvar shell-command-switch (purecopy "-c")
3166 "Switch used to have the shell execute its command line argument.")
3168 (defvar shell-command-default-error-buffer nil
3169 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3170 This buffer is used when `shell-command' or `shell-command-on-region'
3171 is run interactively. A value of nil means that output to stderr and
3172 stdout will be intermixed in the output stream.")
3174 (declare-function mailcap-file-default-commands "mailcap" (files))
3175 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3177 (defun minibuffer-default-add-shell-commands ()
3178 "Return a list of all commands associated with the current file.
3179 This function is used to add all related commands retrieved by `mailcap'
3180 to the end of the list of defaults just after the default value."
3181 (interactive)
3182 (let* ((filename (if (listp minibuffer-default)
3183 (car minibuffer-default)
3184 minibuffer-default))
3185 (commands (and filename (require 'mailcap nil t)
3186 (mailcap-file-default-commands (list filename)))))
3187 (setq commands (mapcar (lambda (command)
3188 (concat command " " filename))
3189 commands))
3190 (if (listp minibuffer-default)
3191 (append minibuffer-default commands)
3192 (cons minibuffer-default commands))))
3194 (declare-function shell-completion-vars "shell" ())
3196 (defvar minibuffer-local-shell-command-map
3197 (let ((map (make-sparse-keymap)))
3198 (set-keymap-parent map minibuffer-local-map)
3199 (define-key map "\t" 'completion-at-point)
3200 map)
3201 "Keymap used for completing shell commands in minibuffer.")
3203 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3204 "Read a shell command from the minibuffer.
3205 The arguments are the same as the ones of `read-from-minibuffer',
3206 except READ and KEYMAP are missing and HIST defaults
3207 to `shell-command-history'."
3208 (require 'shell)
3209 (minibuffer-with-setup-hook
3210 (lambda ()
3211 (shell-completion-vars)
3212 (set (make-local-variable 'minibuffer-default-add-function)
3213 'minibuffer-default-add-shell-commands))
3214 (apply 'read-from-minibuffer prompt initial-contents
3215 minibuffer-local-shell-command-map
3217 (or hist 'shell-command-history)
3218 args)))
3220 (defcustom async-shell-command-buffer 'confirm-new-buffer
3221 "What to do when the output buffer is used by another shell command.
3222 This option specifies how to resolve the conflict where a new command
3223 wants to direct its output to the buffer `*Async Shell Command*',
3224 but this buffer is already taken by another running shell command.
3226 The value `confirm-kill-process' is used to ask for confirmation before
3227 killing the already running process and running a new process
3228 in the same buffer, `confirm-new-buffer' for confirmation before running
3229 the command in a new buffer with a name other than the default buffer name,
3230 `new-buffer' for doing the same without confirmation,
3231 `confirm-rename-buffer' for confirmation before renaming the existing
3232 output buffer and running a new command in the default buffer,
3233 `rename-buffer' for doing the same without confirmation."
3234 :type '(choice (const :tag "Confirm killing of running command"
3235 confirm-kill-process)
3236 (const :tag "Confirm creation of a new buffer"
3237 confirm-new-buffer)
3238 (const :tag "Create a new buffer"
3239 new-buffer)
3240 (const :tag "Confirm renaming of existing buffer"
3241 confirm-rename-buffer)
3242 (const :tag "Rename the existing buffer"
3243 rename-buffer))
3244 :group 'shell
3245 :version "24.3")
3247 (defun shell-command--save-pos-or-erase ()
3248 "Store a buffer position or erase the buffer.
3249 See `shell-command-dont-erase-buffer'."
3250 (let ((sym shell-command-dont-erase-buffer)
3251 pos)
3252 (setq buffer-read-only nil)
3253 ;; Setting buffer-read-only to nil doesn't suffice
3254 ;; if some text has a non-nil read-only property,
3255 ;; which comint sometimes adds for prompts.
3256 (setq pos
3257 (cond ((eq sym 'save-point) (point))
3258 ((eq sym 'beg-last-out) (point-max))
3259 ((not sym)
3260 (let ((inhibit-read-only t))
3261 (erase-buffer) nil))))
3262 (when pos
3263 (goto-char (point-max))
3264 (push (cons (current-buffer) pos)
3265 shell-command-saved-pos))))
3267 (defun shell-command--set-point-after-cmd (&optional buffer)
3268 "Set point in BUFFER after command complete.
3269 BUFFER is the output buffer of the command; if nil, then defaults
3270 to the current BUFFER.
3271 Set point to the `cdr' of the element in `shell-command-saved-pos'
3272 whose `car' is BUFFER."
3273 (when shell-command-dont-erase-buffer
3274 (let* ((sym shell-command-dont-erase-buffer)
3275 (buf (or buffer (current-buffer)))
3276 (pos (alist-get buf shell-command-saved-pos)))
3277 (setq shell-command-saved-pos
3278 (assq-delete-all buf shell-command-saved-pos))
3279 (when (buffer-live-p buf)
3280 (let ((win (car (get-buffer-window-list buf)))
3281 (pmax (with-current-buffer buf (point-max))))
3282 (unless (and pos (memq sym '(save-point beg-last-out)))
3283 (setq pos pmax))
3284 ;; Set point in the window displaying buf, if any; otherwise
3285 ;; display buf temporary in selected frame and set the point.
3286 (if win
3287 (set-window-point win pos)
3288 (save-window-excursion
3289 (let ((win (display-buffer
3291 '(nil (inhibit-switch-frame . t)))))
3292 (set-window-point win pos)))))))))
3294 (defun async-shell-command (command &optional output-buffer error-buffer)
3295 "Execute string COMMAND asynchronously in background.
3297 Like `shell-command', but adds `&' at the end of COMMAND
3298 to execute it asynchronously.
3300 The output appears in the buffer `*Async Shell Command*'.
3301 That buffer is in shell mode.
3303 You can configure `async-shell-command-buffer' to specify what to do in
3304 case when `*Async Shell Command*' buffer is already taken by another
3305 running shell command. To run COMMAND without displaying the output
3306 in a window you can configure `display-buffer-alist' to use the action
3307 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3309 In Elisp, you will often be better served by calling `start-process'
3310 directly, since it offers more control and does not impose the use of a
3311 shell (with its need to quote arguments)."
3312 (interactive
3313 (list
3314 (read-shell-command "Async shell command: " nil nil
3315 (let ((filename
3316 (cond
3317 (buffer-file-name)
3318 ((eq major-mode 'dired-mode)
3319 (dired-get-filename nil t)))))
3320 (and filename (file-relative-name filename))))
3321 current-prefix-arg
3322 shell-command-default-error-buffer))
3323 (unless (string-match "&[ \t]*\\'" command)
3324 (setq command (concat command " &")))
3325 (shell-command command output-buffer error-buffer))
3327 (defun shell-command (command &optional output-buffer error-buffer)
3328 "Execute string COMMAND in inferior shell; display output, if any.
3329 With prefix argument, insert the COMMAND's output at point.
3331 Interactively, prompt for COMMAND in the minibuffer.
3333 If COMMAND ends in `&', execute it asynchronously.
3334 The output appears in the buffer `*Async Shell Command*'.
3335 That buffer is in shell mode. You can also use
3336 `async-shell-command' that automatically adds `&'.
3338 Otherwise, COMMAND is executed synchronously. The output appears in
3339 the buffer `*Shell Command Output*'. If the output is short enough to
3340 display in the echo area (which is determined by the variables
3341 `resize-mini-windows' and `max-mini-window-height'), it is shown
3342 there, but it is nonetheless available in buffer `*Shell Command
3343 Output*' even though that buffer is not automatically displayed.
3345 To specify a coding system for converting non-ASCII characters
3346 in the shell command output, use \\[universal-coding-system-argument] \
3347 before this command.
3349 Noninteractive callers can specify coding systems by binding
3350 `coding-system-for-read' and `coding-system-for-write'.
3352 The optional second argument OUTPUT-BUFFER, if non-nil,
3353 says to put the output in some other buffer.
3354 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3355 and insert the output there; a non-nil value of
3356 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3357 If OUTPUT-BUFFER is not a buffer and not nil, insert the output
3358 in current buffer after point leaving mark after it.
3359 This cannot be done asynchronously.
3361 If the command terminates without error, but generates output,
3362 and you did not specify \"insert it in the current buffer\",
3363 the output can be displayed in the echo area or in its buffer.
3364 If the output is short enough to display in the echo area
3365 \(determined by the variable `max-mini-window-height' if
3366 `resize-mini-windows' is non-nil), it is shown there.
3367 Otherwise,the buffer containing the output is displayed.
3369 If there is output and an error, and you did not specify \"insert it
3370 in the current buffer\", a message about the error goes at the end
3371 of the output.
3373 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3374 or buffer name to which to direct the command's standard error output.
3375 If it is nil, error output is mingled with regular output.
3376 In an interactive call, the variable `shell-command-default-error-buffer'
3377 specifies the value of ERROR-BUFFER.
3379 In Elisp, you will often be better served by calling `call-process' or
3380 `start-process' directly, since it offers more control and does not impose
3381 the use of a shell (with its need to quote arguments)."
3383 (interactive
3384 (list
3385 (read-shell-command "Shell command: " nil nil
3386 (let ((filename
3387 (cond
3388 (buffer-file-name)
3389 ((eq major-mode 'dired-mode)
3390 (dired-get-filename nil t)))))
3391 (and filename (file-relative-name filename))))
3392 current-prefix-arg
3393 shell-command-default-error-buffer))
3394 ;; Look for a handler in case default-directory is a remote file name.
3395 (let ((handler
3396 (find-file-name-handler (directory-file-name default-directory)
3397 'shell-command)))
3398 (if handler
3399 (funcall handler 'shell-command command output-buffer error-buffer)
3400 (if (and output-buffer
3401 (not (or (bufferp output-buffer) (stringp output-buffer))))
3402 ;; Output goes in current buffer.
3403 (let ((error-file
3404 (if error-buffer
3405 (make-temp-file
3406 (expand-file-name "scor"
3407 (or small-temporary-file-directory
3408 temporary-file-directory)))
3409 nil)))
3410 (barf-if-buffer-read-only)
3411 (push-mark nil t)
3412 ;; We do not use -f for csh; we will not support broken use of
3413 ;; .cshrcs. Even the BSD csh manual says to use
3414 ;; "if ($?prompt) exit" before things which are not useful
3415 ;; non-interactively. Besides, if someone wants their other
3416 ;; aliases for shell commands then they can still have them.
3417 (call-process shell-file-name nil
3418 (if error-file
3419 (list t error-file)
3421 nil shell-command-switch command)
3422 (when (and error-file (file-exists-p error-file))
3423 (if (< 0 (nth 7 (file-attributes error-file)))
3424 (with-current-buffer (get-buffer-create error-buffer)
3425 (let ((pos-from-end (- (point-max) (point))))
3426 (or (bobp)
3427 (insert "\f\n"))
3428 ;; Do no formatting while reading error file,
3429 ;; because that can run a shell command, and we
3430 ;; don't want that to cause an infinite recursion.
3431 (format-insert-file error-file nil)
3432 ;; Put point after the inserted errors.
3433 (goto-char (- (point-max) pos-from-end)))
3434 (display-buffer (current-buffer))))
3435 (delete-file error-file))
3436 ;; This is like exchange-point-and-mark, but doesn't
3437 ;; activate the mark. It is cleaner to avoid activation,
3438 ;; even though the command loop would deactivate the mark
3439 ;; because we inserted text.
3440 (goto-char (prog1 (mark t)
3441 (set-marker (mark-marker) (point)
3442 (current-buffer)))))
3443 ;; Output goes in a separate buffer.
3444 ;; Preserve the match data in case called from a program.
3445 ;; FIXME: It'd be ridiculous for an Elisp function to call
3446 ;; shell-command and assume that it won't mess the match-data!
3447 (save-match-data
3448 (if (string-match "[ \t]*&[ \t]*\\'" command)
3449 ;; Command ending with ampersand means asynchronous.
3450 (let ((buffer (get-buffer-create
3451 (or output-buffer "*Async Shell Command*")))
3452 (directory default-directory)
3453 proc)
3454 ;; Remove the ampersand.
3455 (setq command (substring command 0 (match-beginning 0)))
3456 ;; Ask the user what to do with already running process.
3457 (setq proc (get-buffer-process buffer))
3458 (when proc
3459 (cond
3460 ((eq async-shell-command-buffer 'confirm-kill-process)
3461 ;; If will kill a process, query first.
3462 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3463 (kill-process proc)
3464 (error "Shell command in progress")))
3465 ((eq async-shell-command-buffer 'confirm-new-buffer)
3466 ;; If will create a new buffer, query first.
3467 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3468 (setq buffer (generate-new-buffer
3469 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3470 output-buffer "*Async Shell Command*")))
3471 (error "Shell command in progress")))
3472 ((eq async-shell-command-buffer 'new-buffer)
3473 ;; It will create a new buffer.
3474 (setq buffer (generate-new-buffer
3475 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3476 output-buffer "*Async Shell Command*"))))
3477 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3478 ;; If will rename the buffer, query first.
3479 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3480 (progn
3481 (with-current-buffer buffer
3482 (rename-uniquely))
3483 (setq buffer (get-buffer-create
3484 (or output-buffer "*Async Shell Command*"))))
3485 (error "Shell command in progress")))
3486 ((eq async-shell-command-buffer 'rename-buffer)
3487 ;; It will rename the buffer.
3488 (with-current-buffer buffer
3489 (rename-uniquely))
3490 (setq buffer (get-buffer-create
3491 (or output-buffer "*Async Shell Command*"))))))
3492 (with-current-buffer buffer
3493 (display-buffer buffer '(nil (allow-no-window . t)))
3494 (shell-command--save-pos-or-erase)
3495 (setq default-directory directory)
3496 (setq proc (start-process "Shell" buffer shell-file-name
3497 shell-command-switch command))
3498 (setq mode-line-process '(":%s"))
3499 (require 'shell) (shell-mode)
3500 (set-process-sentinel proc 'shell-command-sentinel)
3501 ;; Use the comint filter for proper handling of carriage motion
3502 ;; (see `comint-inhibit-carriage-motion'),.
3503 (set-process-filter proc 'comint-output-filter)
3505 ;; Otherwise, command is executed synchronously.
3506 (shell-command-on-region (point) (point) command
3507 output-buffer nil error-buffer)))))))
3509 (defun display-message-or-buffer (message &optional buffer-name action frame)
3510 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3511 MESSAGE may be either a string or a buffer.
3513 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3514 for maximum height of the echo area, as defined by `max-mini-window-height'
3515 if `resize-mini-windows' is non-nil.
3517 Returns either the string shown in the echo area, or when a pop-up
3518 buffer is used, the window used to display it.
3520 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3521 name of the buffer used to display it in the case where a pop-up buffer
3522 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3523 string and it is displayed in the echo area, it is not specified whether
3524 the contents are inserted into the buffer anyway.
3526 Optional arguments ACTION and FRAME are as for `display-buffer',
3527 and are only used if a pop-up buffer is displayed."
3528 (cond ((and (stringp message) (not (string-match "\n" message)))
3529 ;; Trivial case where we can use the echo area
3530 (message "%s" message))
3531 ((and (stringp message)
3532 (= (string-match "\n" message) (1- (length message))))
3533 ;; Trivial case where we can just remove single trailing newline
3534 (message "%s" (substring message 0 (1- (length message)))))
3536 ;; General case
3537 (with-current-buffer
3538 (if (bufferp message)
3539 message
3540 (get-buffer-create (or buffer-name "*Message*")))
3542 (unless (bufferp message)
3543 (erase-buffer)
3544 (insert message))
3546 (let ((lines
3547 (if (= (buffer-size) 0)
3549 (count-screen-lines nil nil nil (minibuffer-window)))))
3550 (cond ((= lines 0))
3551 ((and (or (<= lines 1)
3552 (<= lines
3553 (if resize-mini-windows
3554 (cond ((floatp max-mini-window-height)
3555 (* (frame-height)
3556 max-mini-window-height))
3557 ((integerp max-mini-window-height)
3558 max-mini-window-height)
3561 1)))
3562 ;; Don't use the echo area if the output buffer is
3563 ;; already displayed in the selected frame.
3564 (not (get-buffer-window (current-buffer))))
3565 ;; Echo area
3566 (goto-char (point-max))
3567 (when (bolp)
3568 (backward-char 1))
3569 (message "%s" (buffer-substring (point-min) (point))))
3571 ;; Buffer
3572 (goto-char (point-min))
3573 (display-buffer (current-buffer) action frame))))))))
3576 ;; We have a sentinel to prevent insertion of a termination message
3577 ;; in the buffer itself, and to set the point in the buffer when
3578 ;; `shell-command-dont-erase-buffer' is non-nil.
3579 (defun shell-command-sentinel (process signal)
3580 (when (memq (process-status process) '(exit signal))
3581 (shell-command--set-point-after-cmd (process-buffer process))
3582 (message "%s: %s."
3583 (car (cdr (cdr (process-command process))))
3584 (substring signal 0 -1))))
3586 (defun shell-command-on-region (start end command
3587 &optional output-buffer replace
3588 error-buffer display-error-buffer
3589 region-noncontiguous-p)
3590 "Execute string COMMAND in inferior shell with region as input.
3591 Normally display output (if any) in temp buffer `*Shell Command Output*';
3592 Prefix arg means replace the region with it. Return the exit code of
3593 COMMAND.
3595 To specify a coding system for converting non-ASCII characters
3596 in the input and output to the shell command, use \\[universal-coding-system-argument]
3597 before this command. By default, the input (from the current buffer)
3598 is encoded using coding-system specified by `process-coding-system-alist',
3599 falling back to `default-process-coding-system' if no match for COMMAND
3600 is found in `process-coding-system-alist'.
3602 Noninteractive callers can specify coding systems by binding
3603 `coding-system-for-read' and `coding-system-for-write'.
3605 If the command generates output, the output may be displayed
3606 in the echo area or in a buffer.
3607 If the output is short enough to display in the echo area
3608 \(determined by the variable `max-mini-window-height' if
3609 `resize-mini-windows' is non-nil), it is shown there.
3610 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3611 The output is available in that buffer in both cases.
3613 If there is output and an error, a message about the error
3614 appears at the end of the output.
3616 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3617 command's output. If the value is a buffer or buffer name,
3618 erase that buffer and insert the output there; a non-nil value of
3619 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3620 If the value is nil, use the buffer `*Shell Command Output*'.
3621 Any other non-nil value means to insert the output in the
3622 current buffer after START.
3624 Optional fifth arg REPLACE, if non-nil, means to insert the
3625 output in place of text from START to END, putting point and mark
3626 around it.
3628 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3629 or buffer name to which to direct the command's standard error
3630 output. If nil, error output is mingled with regular output.
3631 When called interactively, `shell-command-default-error-buffer'
3632 is used for ERROR-BUFFER.
3634 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3635 display the error buffer if there were any errors. When called
3636 interactively, this is t."
3637 (interactive (let (string)
3638 (unless (mark)
3639 (user-error "The mark is not set now, so there is no region"))
3640 ;; Do this before calling region-beginning
3641 ;; and region-end, in case subprocess output
3642 ;; relocates them while we are in the minibuffer.
3643 (setq string (read-shell-command "Shell command on region: "))
3644 ;; call-interactively recognizes region-beginning and
3645 ;; region-end specially, leaving them in the history.
3646 (list (region-beginning) (region-end)
3647 string
3648 current-prefix-arg
3649 current-prefix-arg
3650 shell-command-default-error-buffer
3652 (region-noncontiguous-p))))
3653 (let ((error-file
3654 (if error-buffer
3655 (make-temp-file
3656 (expand-file-name "scor"
3657 (or small-temporary-file-directory
3658 temporary-file-directory)))
3659 nil))
3660 exit-status)
3661 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3662 (if region-noncontiguous-p
3663 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3664 output)
3665 (with-temp-buffer
3666 (insert input)
3667 (call-process-region (point-min) (point-max)
3668 shell-file-name t t
3669 nil shell-command-switch
3670 command)
3671 (setq output (split-string (buffer-string) "\n")))
3672 (goto-char start)
3673 (funcall region-insert-function output))
3674 (if (or replace
3675 (and output-buffer
3676 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3677 ;; Replace specified region with output from command.
3678 (let ((swap (and replace (< start end))))
3679 ;; Don't muck with mark unless REPLACE says we should.
3680 (goto-char start)
3681 (and replace (push-mark (point) 'nomsg))
3682 (setq exit-status
3683 (call-shell-region start end command replace
3684 (if error-file
3685 (list t error-file)
3686 t)))
3687 ;; It is rude to delete a buffer which the command is not using.
3688 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3689 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3690 ;; (kill-buffer shell-buffer)))
3691 ;; Don't muck with mark unless REPLACE says we should.
3692 (and replace swap (exchange-point-and-mark)))
3693 ;; No prefix argument: put the output in a temp buffer,
3694 ;; replacing its entire contents.
3695 (let ((buffer (get-buffer-create
3696 (or output-buffer "*Shell Command Output*"))))
3697 (unwind-protect
3698 (if (and (eq buffer (current-buffer))
3699 (or (not shell-command-dont-erase-buffer)
3700 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3701 (not (region-active-p)))))
3702 ;; If the input is the same buffer as the output,
3703 ;; delete everything but the specified region,
3704 ;; then replace that region with the output.
3705 (progn (setq buffer-read-only nil)
3706 (delete-region (max start end) (point-max))
3707 (delete-region (point-min) (min start end))
3708 (setq exit-status
3709 (call-process-region (point-min) (point-max)
3710 shell-file-name t
3711 (if error-file
3712 (list t error-file)
3714 nil shell-command-switch
3715 command)))
3716 ;; Clear the output buffer, then run the command with
3717 ;; output there.
3718 (let ((directory default-directory))
3719 (with-current-buffer buffer
3720 (if (not output-buffer)
3721 (setq default-directory directory))
3722 (shell-command--save-pos-or-erase)))
3723 (setq exit-status
3724 (call-shell-region start end command nil
3725 (if error-file
3726 (list buffer error-file)
3727 buffer))))
3728 ;; Report the output.
3729 (with-current-buffer buffer
3730 (setq mode-line-process
3731 (cond ((null exit-status)
3732 " - Error")
3733 ((stringp exit-status)
3734 (format " - Signal [%s]" exit-status))
3735 ((not (equal 0 exit-status))
3736 (format " - Exit [%d]" exit-status)))))
3737 (if (with-current-buffer buffer (> (point-max) (point-min)))
3738 ;; There's some output, display it
3739 (progn
3740 (display-message-or-buffer buffer)
3741 (shell-command--set-point-after-cmd buffer))
3742 ;; No output; error?
3743 (let ((output
3744 (if (and error-file
3745 (< 0 (nth 7 (file-attributes error-file))))
3746 (format "some error output%s"
3747 (if shell-command-default-error-buffer
3748 (format " to the \"%s\" buffer"
3749 shell-command-default-error-buffer)
3750 ""))
3751 "no output")))
3752 (cond ((null exit-status)
3753 (message "(Shell command failed with error)"))
3754 ((equal 0 exit-status)
3755 (message "(Shell command succeeded with %s)"
3756 output))
3757 ((stringp exit-status)
3758 (message "(Shell command killed by signal %s)"
3759 exit-status))
3761 (message "(Shell command failed with code %d and %s)"
3762 exit-status output))))
3763 ;; Don't kill: there might be useful info in the undo-log.
3764 ;; (kill-buffer buffer)
3765 )))))
3767 (when (and error-file (file-exists-p error-file))
3768 (if (< 0 (nth 7 (file-attributes error-file)))
3769 (with-current-buffer (get-buffer-create error-buffer)
3770 (let ((pos-from-end (- (point-max) (point))))
3771 (or (bobp)
3772 (insert "\f\n"))
3773 ;; Do no formatting while reading error file,
3774 ;; because that can run a shell command, and we
3775 ;; don't want that to cause an infinite recursion.
3776 (format-insert-file error-file nil)
3777 ;; Put point after the inserted errors.
3778 (goto-char (- (point-max) pos-from-end)))
3779 (and display-error-buffer
3780 (display-buffer (current-buffer)))))
3781 (delete-file error-file))
3782 exit-status))
3784 (defun shell-command-to-string (command)
3785 "Execute shell command COMMAND and return its output as a string."
3786 (with-output-to-string
3787 (with-current-buffer
3788 standard-output
3789 (process-file shell-file-name nil t nil shell-command-switch command))))
3791 (defun process-file (program &optional infile buffer display &rest args)
3792 "Process files synchronously in a separate process.
3793 Similar to `call-process', but may invoke a file handler based on
3794 `default-directory'. The current working directory of the
3795 subprocess is `default-directory'.
3797 File names in INFILE and BUFFER are handled normally, but file
3798 names in ARGS should be relative to `default-directory', as they
3799 are passed to the process verbatim. (This is a difference to
3800 `call-process' which does not support file handlers for INFILE
3801 and BUFFER.)
3803 Some file handlers might not support all variants, for example
3804 they might behave as if DISPLAY was nil, regardless of the actual
3805 value passed."
3806 (let ((fh (find-file-name-handler default-directory 'process-file))
3807 lc stderr-file)
3808 (unwind-protect
3809 (if fh (apply fh 'process-file program infile buffer display args)
3810 (when infile (setq lc (file-local-copy infile)))
3811 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3812 (make-temp-file "emacs")))
3813 (prog1
3814 (apply 'call-process program
3815 (or lc infile)
3816 (if stderr-file (list (car buffer) stderr-file) buffer)
3817 display args)
3818 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3819 (when stderr-file (delete-file stderr-file))
3820 (when lc (delete-file lc)))))
3822 (defvar process-file-side-effects t
3823 "Whether a call of `process-file' changes remote files.
3825 By default, this variable is always set to t, meaning that a
3826 call of `process-file' could potentially change any file on a
3827 remote host. When set to nil, a file handler could optimize
3828 its behavior with respect to remote file attribute caching.
3830 You should only ever change this variable with a let-binding;
3831 never with `setq'.")
3833 (defun start-file-process (name buffer program &rest program-args)
3834 "Start a program in a subprocess. Return the process object for it.
3836 Similar to `start-process', but may invoke a file handler based on
3837 `default-directory'. See Info node `(elisp)Magic File Names'.
3839 This handler ought to run PROGRAM, perhaps on the local host,
3840 perhaps on a remote host that corresponds to `default-directory'.
3841 In the latter case, the local part of `default-directory' becomes
3842 the working directory of the process.
3844 PROGRAM and PROGRAM-ARGS might be file names. They are not
3845 objects of file handler invocation. File handlers might not
3846 support pty association, if PROGRAM is nil."
3847 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3848 (if fh (apply fh 'start-file-process name buffer program program-args)
3849 (apply 'start-process name buffer program program-args))))
3851 ;;;; Process menu
3853 (defvar tabulated-list-format)
3854 (defvar tabulated-list-entries)
3855 (defvar tabulated-list-sort-key)
3856 (declare-function tabulated-list-init-header "tabulated-list" ())
3857 (declare-function tabulated-list-print "tabulated-list"
3858 (&optional remember-pos update))
3860 (defvar process-menu-query-only nil)
3862 (defvar process-menu-mode-map
3863 (let ((map (make-sparse-keymap)))
3864 (define-key map [?d] 'process-menu-delete-process)
3865 map))
3867 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3868 "Major mode for listing the processes called by Emacs."
3869 (setq tabulated-list-format [("Process" 15 t)
3870 ("PID" 7 t)
3871 ("Status" 7 t)
3872 ("Buffer" 15 t)
3873 ("TTY" 12 t)
3874 ("Command" 0 t)])
3875 (make-local-variable 'process-menu-query-only)
3876 (setq tabulated-list-sort-key (cons "Process" nil))
3877 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3878 (tabulated-list-init-header))
3880 (defun process-menu-delete-process ()
3881 "Kill process at point in a `list-processes' buffer."
3882 (interactive)
3883 (let ((pos (point)))
3884 (delete-process (tabulated-list-get-id))
3885 (revert-buffer)
3886 (goto-char (min pos (point-max)))
3887 (if (eobp)
3888 (forward-line -1)
3889 (beginning-of-line))))
3891 (defun list-processes--refresh ()
3892 "Recompute the list of processes for the Process List buffer.
3893 Also, delete any process that is exited or signaled."
3894 (setq tabulated-list-entries nil)
3895 (dolist (p (process-list))
3896 (cond ((memq (process-status p) '(exit signal closed))
3897 (delete-process p))
3898 ((or (not process-menu-query-only)
3899 (process-query-on-exit-flag p))
3900 (let* ((buf (process-buffer p))
3901 (type (process-type p))
3902 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
3903 (name (process-name p))
3904 (status (symbol-name (process-status p)))
3905 (buf-label (if (buffer-live-p buf)
3906 `(,(buffer-name buf)
3907 face link
3908 help-echo ,(format-message
3909 "Visit buffer `%s'"
3910 (buffer-name buf))
3911 follow-link t
3912 process-buffer ,buf
3913 action process-menu-visit-buffer)
3914 "--"))
3915 (tty (or (process-tty-name p) "--"))
3916 (cmd
3917 (if (memq type '(network serial))
3918 (let ((contact (process-contact p t)))
3919 (if (eq type 'network)
3920 (format "(%s %s)"
3921 (if (plist-get contact :type)
3922 "datagram"
3923 "network")
3924 (if (plist-get contact :server)
3925 (format "server on %s"
3927 (plist-get contact :host)
3928 (plist-get contact :local)))
3929 (format "connection to %s"
3930 (plist-get contact :host))))
3931 (format "(serial port %s%s)"
3932 (or (plist-get contact :port) "?")
3933 (let ((speed (plist-get contact :speed)))
3934 (if speed
3935 (format " at %s b/s" speed)
3936 "")))))
3937 (mapconcat 'identity (process-command p) " "))))
3938 (push (list p (vector name pid status buf-label tty cmd))
3939 tabulated-list-entries))))))
3941 (defun process-menu-visit-buffer (button)
3942 (display-buffer (button-get button 'process-buffer)))
3944 (defun list-processes (&optional query-only buffer)
3945 "Display a list of all processes that are Emacs sub-processes.
3946 If optional argument QUERY-ONLY is non-nil, only processes with
3947 the query-on-exit flag set are listed.
3948 Any process listed as exited or signaled is actually eliminated
3949 after the listing is made.
3950 Optional argument BUFFER specifies a buffer to use, instead of
3951 \"*Process List*\".
3952 The return value is always nil.
3954 This function lists only processes that were launched by Emacs. To
3955 see other processes running on the system, use `list-system-processes'."
3956 (interactive)
3957 (or (fboundp 'process-list)
3958 (error "Asynchronous subprocesses are not supported on this system"))
3959 (unless (bufferp buffer)
3960 (setq buffer (get-buffer-create "*Process List*")))
3961 (with-current-buffer buffer
3962 (process-menu-mode)
3963 (setq process-menu-query-only query-only)
3964 (list-processes--refresh)
3965 (tabulated-list-print))
3966 (display-buffer buffer)
3967 nil)
3969 ;;;; Prefix commands
3971 (setq prefix-command--needs-update nil)
3972 (setq prefix-command--last-echo nil)
3974 (defun internal-echo-keystrokes-prefix ()
3975 ;; BEWARE: Called directly from C code.
3976 ;; If the return value is non-nil, it means we are in the middle of
3977 ;; a command with prefix, such as a command invoked with prefix-arg.
3978 (if (not prefix-command--needs-update)
3979 prefix-command--last-echo
3980 (setq prefix-command--last-echo
3981 (let ((strs nil))
3982 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
3983 (lambda (fun) (push (funcall fun) strs)))
3984 (setq strs (delq nil strs))
3985 (when strs (mapconcat #'identity strs " "))))))
3987 (defvar prefix-command-echo-keystrokes-functions nil
3988 "Abnormal hook which constructs the description of the current prefix state.
3989 Each function is called with no argument, should return a string or nil.")
3991 (defun prefix-command-update ()
3992 "Update state of prefix commands.
3993 Call it whenever you change the \"prefix command state\"."
3994 (setq prefix-command--needs-update t))
3996 (defvar prefix-command-preserve-state-hook nil
3997 "Normal hook run when a command needs to preserve the prefix.")
3999 (defun prefix-command-preserve-state ()
4000 "Pass the current prefix command state to the next command.
4001 Should be called by all prefix commands.
4002 Runs `prefix-command-preserve-state-hook'."
4003 (run-hooks 'prefix-command-preserve-state-hook)
4004 ;; If the current command is a prefix command, we don't want the next (real)
4005 ;; command to have `last-command' set to, say, `universal-argument'.
4006 (setq this-command last-command)
4007 (setq real-this-command real-last-command)
4008 (prefix-command-update))
4010 (defun reset-this-command-lengths ()
4011 (declare (obsolete prefix-command-preserve-state "25.1"))
4012 nil)
4014 ;;;;; The main prefix command.
4016 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4018 (add-hook 'prefix-command-echo-keystrokes-functions
4019 #'universal-argument--description)
4020 (defun universal-argument--description ()
4021 (when prefix-arg
4022 (concat "C-u"
4023 (pcase prefix-arg
4024 (`(-) " -")
4025 (`(,(and (pred integerp) n))
4026 (let ((str ""))
4027 (while (and (> n 4) (= (mod n 4) 0))
4028 (setq str (concat str " C-u"))
4029 (setq n (/ n 4)))
4030 (if (= n 4) str (format " %s" prefix-arg))))
4031 (_ (format " %s" prefix-arg))))))
4033 (add-hook 'prefix-command-preserve-state-hook
4034 #'universal-argument--preserve)
4035 (defun universal-argument--preserve ()
4036 (setq prefix-arg current-prefix-arg))
4038 (defvar universal-argument-map
4039 (let ((map (make-sparse-keymap))
4040 (universal-argument-minus
4041 ;; For backward compatibility, minus with no modifiers is an ordinary
4042 ;; command if digits have already been entered.
4043 `(menu-item "" negative-argument
4044 :filter ,(lambda (cmd)
4045 (if (integerp prefix-arg) nil cmd)))))
4046 (define-key map [switch-frame]
4047 (lambda (e) (interactive "e")
4048 (handle-switch-frame e) (universal-argument--mode)))
4049 (define-key map [?\C-u] 'universal-argument-more)
4050 (define-key map [?-] universal-argument-minus)
4051 (define-key map [?0] 'digit-argument)
4052 (define-key map [?1] 'digit-argument)
4053 (define-key map [?2] 'digit-argument)
4054 (define-key map [?3] 'digit-argument)
4055 (define-key map [?4] 'digit-argument)
4056 (define-key map [?5] 'digit-argument)
4057 (define-key map [?6] 'digit-argument)
4058 (define-key map [?7] 'digit-argument)
4059 (define-key map [?8] 'digit-argument)
4060 (define-key map [?9] 'digit-argument)
4061 (define-key map [kp-0] 'digit-argument)
4062 (define-key map [kp-1] 'digit-argument)
4063 (define-key map [kp-2] 'digit-argument)
4064 (define-key map [kp-3] 'digit-argument)
4065 (define-key map [kp-4] 'digit-argument)
4066 (define-key map [kp-5] 'digit-argument)
4067 (define-key map [kp-6] 'digit-argument)
4068 (define-key map [kp-7] 'digit-argument)
4069 (define-key map [kp-8] 'digit-argument)
4070 (define-key map [kp-9] 'digit-argument)
4071 (define-key map [kp-subtract] universal-argument-minus)
4072 map)
4073 "Keymap used while processing \\[universal-argument].")
4075 (defun universal-argument--mode ()
4076 (prefix-command-update)
4077 (set-transient-map universal-argument-map nil))
4079 (defun universal-argument ()
4080 "Begin a numeric argument for the following command.
4081 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4082 \\[universal-argument] following the digits or minus sign ends the argument.
4083 \\[universal-argument] without digits or minus sign provides 4 as argument.
4084 Repeating \\[universal-argument] without digits or minus sign
4085 multiplies the argument by 4 each time.
4086 For some commands, just \\[universal-argument] by itself serves as a flag
4087 which is different in effect from any particular numeric argument.
4088 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4089 (interactive)
4090 (prefix-command-preserve-state)
4091 (setq prefix-arg (list 4))
4092 (universal-argument--mode))
4094 (defun universal-argument-more (arg)
4095 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4096 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4097 (interactive "P")
4098 (prefix-command-preserve-state)
4099 (setq prefix-arg (if (consp arg)
4100 (list (* 4 (car arg)))
4101 (if (eq arg '-)
4102 (list -4)
4103 arg)))
4104 (when (consp prefix-arg) (universal-argument--mode)))
4106 (defun negative-argument (arg)
4107 "Begin a negative numeric argument for the next command.
4108 \\[universal-argument] following digits or minus sign ends the argument."
4109 (interactive "P")
4110 (prefix-command-preserve-state)
4111 (setq prefix-arg (cond ((integerp arg) (- arg))
4112 ((eq arg '-) nil)
4113 (t '-)))
4114 (universal-argument--mode))
4116 (defun digit-argument (arg)
4117 "Part of the numeric argument for the next command.
4118 \\[universal-argument] following digits or minus sign ends the argument."
4119 (interactive "P")
4120 (prefix-command-preserve-state)
4121 (let* ((char (if (integerp last-command-event)
4122 last-command-event
4123 (get last-command-event 'ascii-character)))
4124 (digit (- (logand char ?\177) ?0)))
4125 (setq prefix-arg (cond ((integerp arg)
4126 (+ (* arg 10)
4127 (if (< arg 0) (- digit) digit)))
4128 ((eq arg '-)
4129 ;; Treat -0 as just -, so that -01 will work.
4130 (if (zerop digit) '- (- digit)))
4132 digit))))
4133 (universal-argument--mode))
4136 (defvar filter-buffer-substring-functions nil
4137 "This variable is a wrapper hook around `buffer-substring--filter'.
4138 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4139 (make-obsolete-variable 'filter-buffer-substring-functions
4140 'filter-buffer-substring-function "24.4")
4142 (defvar filter-buffer-substring-function #'buffer-substring--filter
4143 "Function to perform the filtering in `filter-buffer-substring'.
4144 The function is called with the same 3 arguments (BEG END DELETE)
4145 that `filter-buffer-substring' received. It should return the
4146 buffer substring between BEG and END, after filtering. If DELETE is
4147 non-nil, it should delete the text between BEG and END from the buffer.")
4149 (defvar buffer-substring-filters nil
4150 "List of filter functions for `buffer-substring--filter'.
4151 Each function must accept a single argument, a string, and return a string.
4152 The buffer substring is passed to the first function in the list,
4153 and the return value of each function is passed to the next.
4154 As a special convention, point is set to the start of the buffer text
4155 being operated on (i.e., the first argument of `buffer-substring--filter')
4156 before these functions are called.")
4157 (make-obsolete-variable 'buffer-substring-filters
4158 'filter-buffer-substring-function "24.1")
4160 (defun filter-buffer-substring (beg end &optional delete)
4161 "Return the buffer substring between BEG and END, after filtering.
4162 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4164 This calls the function that `filter-buffer-substring-function' specifies
4165 \(passing the same three arguments that it received) to do the work,
4166 and returns whatever it does. The default function does no filtering,
4167 unless a hook has been set.
4169 Use `filter-buffer-substring' instead of `buffer-substring',
4170 `buffer-substring-no-properties', or `delete-and-extract-region' when
4171 you want to allow filtering to take place. For example, major or minor
4172 modes can use `filter-buffer-substring-function' to extract characters
4173 that are special to a buffer, and should not be copied into other buffers."
4174 (funcall filter-buffer-substring-function beg end delete))
4176 (defun buffer-substring--filter (beg end &optional delete)
4177 "Default function to use for `filter-buffer-substring-function'.
4178 Its arguments and return value are as specified for `filter-buffer-substring'.
4179 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4180 \(see `with-wrapper-hook' for details about wrapper hooks),
4181 and the abnormal hook `buffer-substring-filters'.
4182 No filtering is done unless a hook says to."
4183 (subr--with-wrapper-hook-no-warnings
4184 filter-buffer-substring-functions (beg end delete)
4185 (cond
4186 ((or delete buffer-substring-filters)
4187 (save-excursion
4188 (goto-char beg)
4189 (let ((string (if delete (delete-and-extract-region beg end)
4190 (buffer-substring beg end))))
4191 (dolist (filter buffer-substring-filters)
4192 (setq string (funcall filter string)))
4193 string)))
4195 (buffer-substring beg end)))))
4198 ;;;; Window system cut and paste hooks.
4200 (defvar interprogram-cut-function #'gui-select-text
4201 "Function to call to make a killed region available to other programs.
4202 Most window systems provide a facility for cutting and pasting
4203 text between different programs, such as the clipboard on X and
4204 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4206 This variable holds a function that Emacs calls whenever text is
4207 put in the kill ring, to make the new kill available to other
4208 programs. The function takes one argument, TEXT, which is a
4209 string containing the text which should be made available.")
4211 (defvar interprogram-paste-function #'gui-selection-value
4212 "Function to call to get text cut from other programs.
4213 Most window systems provide a facility for cutting and pasting
4214 text between different programs, such as the clipboard on X and
4215 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4217 This variable holds a function that Emacs calls to obtain text
4218 that other programs have provided for pasting. The function is
4219 called with no arguments. If no other program has provided text
4220 to paste, the function should return nil (in which case the
4221 caller, usually `current-kill', should use the top of the Emacs
4222 kill ring). If another program has provided text to paste, the
4223 function should return that text as a string (in which case the
4224 caller should put this string in the kill ring as the latest
4225 kill).
4227 The function may also return a list of strings if the window
4228 system supports multiple selections. The first string will be
4229 used as the pasted text, but the other will be placed in the kill
4230 ring for easy access via `yank-pop'.
4232 Note that the function should return a string only if a program
4233 other than Emacs has provided a string for pasting; if Emacs
4234 provided the most recent string, the function should return nil.
4235 If it is difficult to tell whether Emacs or some other program
4236 provided the current string, it is probably good enough to return
4237 nil if the string is equal (according to `string=') to the last
4238 text Emacs provided.")
4242 ;;;; The kill ring data structure.
4244 (defvar kill-ring nil
4245 "List of killed text sequences.
4246 Since the kill ring is supposed to interact nicely with cut-and-paste
4247 facilities offered by window systems, use of this variable should
4248 interact nicely with `interprogram-cut-function' and
4249 `interprogram-paste-function'. The functions `kill-new',
4250 `kill-append', and `current-kill' are supposed to implement this
4251 interaction; you may want to use them instead of manipulating the kill
4252 ring directly.")
4254 (defcustom kill-ring-max 60
4255 "Maximum length of kill ring before oldest elements are thrown away."
4256 :type 'integer
4257 :group 'killing)
4259 (defvar kill-ring-yank-pointer nil
4260 "The tail of the kill ring whose car is the last thing yanked.")
4262 (defcustom save-interprogram-paste-before-kill nil
4263 "Save clipboard strings into kill ring before replacing them.
4264 When one selects something in another program to paste it into Emacs,
4265 but kills something in Emacs before actually pasting it,
4266 this selection is gone unless this variable is non-nil,
4267 in which case the other program's selection is saved in the `kill-ring'
4268 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4269 :type 'boolean
4270 :group 'killing
4271 :version "23.2")
4273 (defcustom kill-do-not-save-duplicates nil
4274 "Do not add a new string to `kill-ring' if it duplicates the last one.
4275 The comparison is done using `equal-including-properties'."
4276 :type 'boolean
4277 :group 'killing
4278 :version "23.2")
4280 (defun kill-new (string &optional replace)
4281 "Make STRING the latest kill in the kill ring.
4282 Set `kill-ring-yank-pointer' to point to it.
4283 If `interprogram-cut-function' is non-nil, apply it to STRING.
4284 Optional second argument REPLACE non-nil means that STRING will replace
4285 the front of the kill ring, rather than being added to the list.
4287 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4288 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4289 STRING.
4291 When the yank handler has a non-nil PARAM element, the original STRING
4292 argument is not used by `insert-for-yank'. However, since Lisp code
4293 may access and use elements from the kill ring directly, the STRING
4294 argument should still be a \"useful\" string for such uses."
4295 (unless (and kill-do-not-save-duplicates
4296 ;; Due to text properties such as 'yank-handler that
4297 ;; can alter the contents to yank, comparison using
4298 ;; `equal' is unsafe.
4299 (equal-including-properties string (car kill-ring)))
4300 (if (fboundp 'menu-bar-update-yank-menu)
4301 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4302 (when save-interprogram-paste-before-kill
4303 (let ((interprogram-paste (and interprogram-paste-function
4304 (funcall interprogram-paste-function))))
4305 (when interprogram-paste
4306 (dolist (s (if (listp interprogram-paste)
4307 (nreverse interprogram-paste)
4308 (list interprogram-paste)))
4309 (unless (and kill-do-not-save-duplicates
4310 (equal-including-properties s (car kill-ring)))
4311 (push s kill-ring))))))
4312 (unless (and kill-do-not-save-duplicates
4313 (equal-including-properties string (car kill-ring)))
4314 (if (and replace kill-ring)
4315 (setcar kill-ring string)
4316 (push string kill-ring)
4317 (if (> (length kill-ring) kill-ring-max)
4318 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4319 (setq kill-ring-yank-pointer kill-ring)
4320 (if interprogram-cut-function
4321 (funcall interprogram-cut-function string)))
4323 ;; It has been argued that this should work similar to `self-insert-command'
4324 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4325 (defcustom kill-append-merge-undo nil
4326 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4327 :type 'boolean
4328 :group 'killing
4329 :version "25.1")
4331 (defun kill-append (string before-p)
4332 "Append STRING to the end of the latest kill in the kill ring.
4333 If BEFORE-P is non-nil, prepend STRING to the kill.
4334 Also removes the last undo boundary in the current buffer,
4335 depending on `kill-append-merge-undo'.
4336 If `interprogram-cut-function' is set, pass the resulting kill to it."
4337 (let* ((cur (car kill-ring)))
4338 (kill-new (if before-p (concat string cur) (concat cur string))
4339 (or (= (length cur) 0)
4340 (equal nil (get-text-property 0 'yank-handler cur))))
4341 (when (and kill-append-merge-undo (not buffer-read-only))
4342 (let ((prev buffer-undo-list)
4343 (next (cdr buffer-undo-list)))
4344 ;; find the next undo boundary
4345 (while (car next)
4346 (pop next)
4347 (pop prev))
4348 ;; remove this undo boundary
4349 (when prev
4350 (setcdr prev (cdr next)))))))
4352 (defcustom yank-pop-change-selection nil
4353 "Whether rotating the kill ring changes the window system selection.
4354 If non-nil, whenever the kill ring is rotated (usually via the
4355 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4356 to copy the new kill to the window system selection."
4357 :type 'boolean
4358 :group 'killing
4359 :version "23.1")
4361 (defun current-kill (n &optional do-not-move)
4362 "Rotate the yanking point by N places, and then return that kill.
4363 If N is zero and `interprogram-paste-function' is set to a
4364 function that returns a string or a list of strings, and if that
4365 function doesn't return nil, then that string (or list) is added
4366 to the front of the kill ring and the string (or first string in
4367 the list) is returned as the latest kill.
4369 If N is not zero, and if `yank-pop-change-selection' is
4370 non-nil, use `interprogram-cut-function' to transfer the
4371 kill at the new yank point into the window system selection.
4373 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4374 move the yanking point; just return the Nth kill forward."
4376 (let ((interprogram-paste (and (= n 0)
4377 interprogram-paste-function
4378 (funcall interprogram-paste-function))))
4379 (if interprogram-paste
4380 (progn
4381 ;; Disable the interprogram cut function when we add the new
4382 ;; text to the kill ring, so Emacs doesn't try to own the
4383 ;; selection, with identical text.
4384 (let ((interprogram-cut-function nil))
4385 (if (listp interprogram-paste)
4386 (mapc 'kill-new (nreverse interprogram-paste))
4387 (kill-new interprogram-paste)))
4388 (car kill-ring))
4389 (or kill-ring (error "Kill ring is empty"))
4390 (let ((ARGth-kill-element
4391 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4392 (length kill-ring))
4393 kill-ring)))
4394 (unless do-not-move
4395 (setq kill-ring-yank-pointer ARGth-kill-element)
4396 (when (and yank-pop-change-selection
4397 (> n 0)
4398 interprogram-cut-function)
4399 (funcall interprogram-cut-function (car ARGth-kill-element))))
4400 (car ARGth-kill-element)))))
4404 ;;;; Commands for manipulating the kill ring.
4406 (defcustom kill-read-only-ok nil
4407 "Non-nil means don't signal an error for killing read-only text."
4408 :type 'boolean
4409 :group 'killing)
4411 (defun kill-region (beg end &optional region)
4412 "Kill (\"cut\") text between point and mark.
4413 This deletes the text from the buffer and saves it in the kill ring.
4414 The command \\[yank] can retrieve it from there.
4415 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4417 If you want to append the killed region to the last killed text,
4418 use \\[append-next-kill] before \\[kill-region].
4420 Any command that calls this function is a \"kill command\".
4421 If the previous command was also a kill command,
4422 the text killed this time appends to the text killed last time
4423 to make one entry in the kill ring.
4425 The killed text is filtered by `filter-buffer-substring' before it is
4426 saved in the kill ring, so the actual saved text might be different
4427 from what was killed.
4429 If the buffer is read-only, Emacs will beep and refrain from deleting
4430 the text, but put the text in the kill ring anyway. This means that
4431 you can use the killing commands to copy text from a read-only buffer.
4433 Lisp programs should use this function for killing text.
4434 (To delete text, use `delete-region'.)
4435 Supply two arguments, character positions BEG and END indicating the
4436 stretch of text to be killed. If the optional argument REGION is
4437 non-nil, the function ignores BEG and END, and kills the current
4438 region instead."
4439 ;; Pass mark first, then point, because the order matters when
4440 ;; calling `kill-append'.
4441 (interactive (list (mark) (point) 'region))
4442 (unless (and beg end)
4443 (user-error "The mark is not set now, so there is no region"))
4444 (condition-case nil
4445 (let ((string (if region
4446 (funcall region-extract-function 'delete)
4447 (filter-buffer-substring beg end 'delete))))
4448 (when string ;STRING is nil if BEG = END
4449 ;; Add that string to the kill ring, one way or another.
4450 (if (eq last-command 'kill-region)
4451 (kill-append string (< end beg))
4452 (kill-new string)))
4453 (when (or string (eq last-command 'kill-region))
4454 (setq this-command 'kill-region))
4455 (setq deactivate-mark t)
4456 nil)
4457 ((buffer-read-only text-read-only)
4458 ;; The code above failed because the buffer, or some of the characters
4459 ;; in the region, are read-only.
4460 ;; We should beep, in case the user just isn't aware of this.
4461 ;; However, there's no harm in putting
4462 ;; the region's text in the kill ring, anyway.
4463 (copy-region-as-kill beg end region)
4464 ;; Set this-command now, so it will be set even if we get an error.
4465 (setq this-command 'kill-region)
4466 ;; This should barf, if appropriate, and give us the correct error.
4467 (if kill-read-only-ok
4468 (progn (message "Read only text copied to kill ring") nil)
4469 ;; Signal an error if the buffer is read-only.
4470 (barf-if-buffer-read-only)
4471 ;; If the buffer isn't read-only, the text is.
4472 (signal 'text-read-only (list (current-buffer)))))))
4474 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4475 ;; to get two copies of the text when the user accidentally types M-w and
4476 ;; then corrects it with the intended C-w.
4477 (defun copy-region-as-kill (beg end &optional region)
4478 "Save the region as if killed, but don't kill it.
4479 In Transient Mark mode, deactivate the mark.
4480 If `interprogram-cut-function' is non-nil, also save the text for a window
4481 system cut and paste.
4483 The copied text is filtered by `filter-buffer-substring' before it is
4484 saved in the kill ring, so the actual saved text might be different
4485 from what was in the buffer.
4487 When called from Lisp, save in the kill ring the stretch of text
4488 between BEG and END, unless the optional argument REGION is
4489 non-nil, in which case ignore BEG and END, and save the current
4490 region instead.
4492 This command's old key binding has been given to `kill-ring-save'."
4493 ;; Pass mark first, then point, because the order matters when
4494 ;; calling `kill-append'.
4495 (interactive (list (mark) (point)
4496 (prefix-numeric-value current-prefix-arg)))
4497 (let ((str (if region
4498 (funcall region-extract-function nil)
4499 (filter-buffer-substring beg end))))
4500 (if (eq last-command 'kill-region)
4501 (kill-append str (< end beg))
4502 (kill-new str)))
4503 (setq deactivate-mark t)
4504 nil)
4506 (defun kill-ring-save (beg end &optional region)
4507 "Save the region as if killed, but don't kill it.
4508 In Transient Mark mode, deactivate the mark.
4509 If `interprogram-cut-function' is non-nil, also save the text for a window
4510 system cut and paste.
4512 If you want to append the killed line to the last killed text,
4513 use \\[append-next-kill] before \\[kill-ring-save].
4515 The copied text is filtered by `filter-buffer-substring' before it is
4516 saved in the kill ring, so the actual saved text might be different
4517 from what was in the buffer.
4519 When called from Lisp, save in the kill ring the stretch of text
4520 between BEG and END, unless the optional argument REGION is
4521 non-nil, in which case ignore BEG and END, and save the current
4522 region instead.
4524 This command is similar to `copy-region-as-kill', except that it gives
4525 visual feedback indicating the extent of the region being copied."
4526 ;; Pass mark first, then point, because the order matters when
4527 ;; calling `kill-append'.
4528 (interactive (list (mark) (point)
4529 (prefix-numeric-value current-prefix-arg)))
4530 (copy-region-as-kill beg end region)
4531 ;; This use of called-interactively-p is correct because the code it
4532 ;; controls just gives the user visual feedback.
4533 (if (called-interactively-p 'interactive)
4534 (indicate-copied-region)))
4536 (defun indicate-copied-region (&optional message-len)
4537 "Indicate that the region text has been copied interactively.
4538 If the mark is visible in the selected window, blink the cursor
4539 between point and mark if there is currently no active region
4540 highlighting.
4542 If the mark lies outside the selected window, display an
4543 informative message containing a sample of the copied text. The
4544 optional argument MESSAGE-LEN, if non-nil, specifies the length
4545 of this sample text; it defaults to 40."
4546 (let ((mark (mark t))
4547 (point (point))
4548 ;; Inhibit quitting so we can make a quit here
4549 ;; look like a C-g typed as a command.
4550 (inhibit-quit t))
4551 (if (pos-visible-in-window-p mark (selected-window))
4552 ;; Swap point-and-mark quickly so as to show the region that
4553 ;; was selected. Don't do it if the region is highlighted.
4554 (unless (and (region-active-p)
4555 (face-background 'region))
4556 ;; Swap point and mark.
4557 (set-marker (mark-marker) (point) (current-buffer))
4558 (goto-char mark)
4559 (sit-for blink-matching-delay)
4560 ;; Swap back.
4561 (set-marker (mark-marker) mark (current-buffer))
4562 (goto-char point)
4563 ;; If user quit, deactivate the mark
4564 ;; as C-g would as a command.
4565 (and quit-flag (region-active-p)
4566 (deactivate-mark)))
4567 (let ((len (min (abs (- mark point))
4568 (or message-len 40))))
4569 (if (< point mark)
4570 ;; Don't say "killed"; that is misleading.
4571 (message "Saved text until \"%s\""
4572 (buffer-substring-no-properties (- mark len) mark))
4573 (message "Saved text from \"%s\""
4574 (buffer-substring-no-properties mark (+ mark len))))))))
4576 (defun append-next-kill (&optional interactive)
4577 "Cause following command, if it kills, to add to previous kill.
4578 If the next command kills forward from point, the kill is
4579 appended to the previous killed text. If the command kills
4580 backward, the kill is prepended. Kill commands that act on the
4581 region, such as `kill-region', are regarded as killing forward if
4582 point is after mark, and killing backward if point is before
4583 mark.
4585 If the next command is not a kill command, `append-next-kill' has
4586 no effect.
4588 The argument is used for internal purposes; do not supply one."
4589 (interactive "p")
4590 ;; We don't use (interactive-p), since that breaks kbd macros.
4591 (if interactive
4592 (progn
4593 (setq this-command 'kill-region)
4594 (message "If the next command is a kill, it will append"))
4595 (setq last-command 'kill-region)))
4597 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4598 "Character set that matches bidirectional formatting control characters.")
4600 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4601 "Character set that matches any character except bidirectional controls.")
4603 (defun squeeze-bidi-context-1 (from to category replacement)
4604 "A subroutine of `squeeze-bidi-context'.
4605 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4606 (let ((pt (copy-marker from))
4607 (limit (copy-marker to))
4608 (old-pt 0)
4609 lim1)
4610 (setq lim1 limit)
4611 (goto-char pt)
4612 (while (< pt limit)
4613 (if (> pt old-pt)
4614 (move-marker lim1
4615 (save-excursion
4616 ;; L and R categories include embedding and
4617 ;; override controls, but we don't want to
4618 ;; replace them, because that might change
4619 ;; the visual order. Likewise with PDF and
4620 ;; isolate controls.
4621 (+ pt (skip-chars-forward
4622 bidi-directional-non-controls-chars
4623 limit)))))
4624 ;; Replace any run of non-RTL characters by a single LRM.
4625 (if (null (re-search-forward category lim1 t))
4626 ;; No more characters of CATEGORY, we are done.
4627 (setq pt limit)
4628 (replace-match replacement nil t)
4629 (move-marker pt (point)))
4630 (setq old-pt pt)
4631 ;; Skip directional controls, if any.
4632 (move-marker
4633 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4635 (defun squeeze-bidi-context (from to)
4636 "Replace characters between FROM and TO while keeping bidi context.
4638 This function replaces the region of text with as few characters
4639 as possible, while preserving the effect that region will have on
4640 bidirectional display before and after the region."
4641 (let ((start (set-marker (make-marker)
4642 (if (> from 0) from (+ (point-max) from))))
4643 (end (set-marker (make-marker) to))
4644 ;; This is for when they copy text with read-only text
4645 ;; properties.
4646 (inhibit-read-only t))
4647 (if (null (marker-position end))
4648 (setq end (point-max-marker)))
4649 ;; Replace each run of non-RTL characters with a single LRM.
4650 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4651 ;; Replace each run of non-LTR characters with a single RLM. Note
4652 ;; that the \cR category includes both the Arabic Letter (AL) and
4653 ;; R characters; here we ignore the distinction between them,
4654 ;; because that distinction only affects Arabic Number (AN)
4655 ;; characters, which are weak and don't affect the reordering.
4656 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4658 (defun line-substring-with-bidi-context (start end &optional no-properties)
4659 "Return buffer text between START and END with its bidi context.
4661 START and END are assumed to belong to the same physical line
4662 of buffer text. This function prepends and appends to the text
4663 between START and END bidi control characters that preserve the
4664 visual order of that text when it is inserted at some other place."
4665 (if (or (< start (point-min))
4666 (> end (point-max)))
4667 (signal 'args-out-of-range (list (current-buffer) start end)))
4668 (let ((buf (current-buffer))
4669 substr para-dir from to)
4670 (save-excursion
4671 (goto-char start)
4672 (setq para-dir (current-bidi-paragraph-direction))
4673 (setq from (line-beginning-position)
4674 to (line-end-position))
4675 (goto-char from)
4676 ;; If we don't have any mixed directional characters in the
4677 ;; entire line, we can just copy the substring without adding
4678 ;; any context.
4679 (if (or (looking-at-p "\\CR*$")
4680 (looking-at-p "\\CL*$"))
4681 (setq substr (if no-properties
4682 (buffer-substring-no-properties start end)
4683 (buffer-substring start end)))
4684 (setq substr
4685 (with-temp-buffer
4686 (if no-properties
4687 (insert-buffer-substring-no-properties buf from to)
4688 (insert-buffer-substring buf from to))
4689 (squeeze-bidi-context 1 (1+ (- start from)))
4690 (squeeze-bidi-context (- end to) nil)
4691 (buffer-substring 1 (point-max)))))
4693 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4694 ;; (1) force the string to have the same base embedding
4695 ;; direction as the paragraph direction at the source, no matter
4696 ;; what is the paragraph direction at destination; and (2) avoid
4697 ;; affecting the visual order of the surrounding text at
4698 ;; destination if there are characters of different
4699 ;; directionality there.
4700 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4701 substr "\x2069"))))
4703 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4704 "Return portion of current buffer between START and END with bidi context.
4706 This function works similar to `buffer-substring', but it prepends and
4707 appends to the text bidi directional control characters necessary to
4708 preserve the visual appearance of the text if it is inserted at another
4709 place. This is useful when the buffer substring includes bidirectional
4710 text and control characters that cause non-trivial reordering on display.
4711 If copied verbatim, such text can have a very different visual appearance,
4712 and can also change the visual appearance of the surrounding text at the
4713 destination of the copy.
4715 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4716 the text properties."
4717 (let (line-end substr)
4718 (if (or (< start (point-min))
4719 (> end (point-max)))
4720 (signal 'args-out-of-range (list (current-buffer) start end)))
4721 (save-excursion
4722 (goto-char start)
4723 (setq line-end (min end (line-end-position)))
4724 (while (< start end)
4725 (setq substr
4726 (concat substr
4727 (if substr "\n" "")
4728 (line-substring-with-bidi-context start line-end
4729 no-properties)))
4730 (forward-line 1)
4731 (setq start (point))
4732 (setq line-end (min end (line-end-position))))
4733 substr)))
4735 ;; Yanking.
4737 (defcustom yank-handled-properties
4738 '((font-lock-face . yank-handle-font-lock-face-property)
4739 (category . yank-handle-category-property))
4740 "List of special text property handling conditions for yanking.
4741 Each element should have the form (PROP . FUN), where PROP is a
4742 property symbol and FUN is a function. When the `yank' command
4743 inserts text into the buffer, it scans the inserted text for
4744 stretches of text that have `eq' values of the text property
4745 PROP; for each such stretch of text, FUN is called with three
4746 arguments: the property's value in that text, and the start and
4747 end positions of the text.
4749 This is done prior to removing the properties specified by
4750 `yank-excluded-properties'."
4751 :group 'killing
4752 :type '(repeat (cons (symbol :tag "property symbol")
4753 function))
4754 :version "24.3")
4756 ;; This is actually used in subr.el but defcustom does not work there.
4757 (defcustom yank-excluded-properties
4758 '(category field follow-link fontified font-lock-face help-echo
4759 intangible invisible keymap local-map mouse-face read-only
4760 yank-handler)
4761 "Text properties to discard when yanking.
4762 The value should be a list of text properties to discard or t,
4763 which means to discard all text properties.
4765 See also `yank-handled-properties'."
4766 :type '(choice (const :tag "All" t) (repeat symbol))
4767 :group 'killing
4768 :version "24.3")
4770 (defvar yank-window-start nil)
4771 (defvar yank-undo-function nil
4772 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4773 Function is called with two parameters, START and END corresponding to
4774 the value of the mark and point; it is guaranteed that START <= END.
4775 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4777 (defun yank-pop (&optional arg)
4778 "Replace just-yanked stretch of killed text with a different stretch.
4779 This command is allowed only immediately after a `yank' or a `yank-pop'.
4780 At such a time, the region contains a stretch of reinserted
4781 previously-killed text. `yank-pop' deletes that text and inserts in its
4782 place a different stretch of killed text.
4784 With no argument, the previous kill is inserted.
4785 With argument N, insert the Nth previous kill.
4786 If N is negative, this is a more recent kill.
4788 The sequence of kills wraps around, so that after the oldest one
4789 comes the newest one.
4791 This command honors the `yank-handled-properties' and
4792 `yank-excluded-properties' variables, and the `yank-handler' text
4793 property, in the way that `yank' does."
4794 (interactive "*p")
4795 (if (not (eq last-command 'yank))
4796 (user-error "Previous command was not a yank"))
4797 (setq this-command 'yank)
4798 (unless arg (setq arg 1))
4799 (let ((inhibit-read-only t)
4800 (before (< (point) (mark t))))
4801 (if before
4802 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4803 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4804 (setq yank-undo-function nil)
4805 (set-marker (mark-marker) (point) (current-buffer))
4806 (insert-for-yank (current-kill arg))
4807 ;; Set the window start back where it was in the yank command,
4808 ;; if possible.
4809 (set-window-start (selected-window) yank-window-start t)
4810 (if before
4811 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4812 ;; It is cleaner to avoid activation, even though the command
4813 ;; loop would deactivate the mark because we inserted text.
4814 (goto-char (prog1 (mark t)
4815 (set-marker (mark-marker) (point) (current-buffer))))))
4816 nil)
4818 (defun yank (&optional arg)
4819 "Reinsert (\"paste\") the last stretch of killed text.
4820 More precisely, reinsert the most recent kill, which is the
4821 stretch of killed text most recently killed OR yanked. Put point
4822 at the end, and set mark at the beginning without activating it.
4823 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4824 With argument N, reinsert the Nth most recent kill.
4826 This command honors the `yank-handled-properties' and
4827 `yank-excluded-properties' variables, and the `yank-handler' text
4828 property, as described below.
4830 Properties listed in `yank-handled-properties' are processed,
4831 then those listed in `yank-excluded-properties' are discarded.
4833 If STRING has a non-nil `yank-handler' property anywhere, the
4834 normal insert behavior is altered, and instead, for each contiguous
4835 segment of STRING that has a given value of the `yank-handler'
4836 property, that value is used as follows:
4838 The value of a `yank-handler' property must be a list of one to four
4839 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4840 FUNCTION, if non-nil, should be a function of one argument (the
4841 object to insert); FUNCTION is called instead of `insert'.
4842 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4843 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4844 PARAM may be a list of strings to insert as a rectangle). If PARAM
4845 is nil, then the current segment of STRING is used.
4846 If NOEXCLUDE is present and non-nil, the normal removal of
4847 `yank-excluded-properties' is not performed; instead FUNCTION is
4848 responsible for the removal. This may be necessary if FUNCTION
4849 adjusts point before or after inserting the object.
4850 UNDO, if present and non-nil, should be a function to be called
4851 by `yank-pop' to undo the insertion of the current PARAM. It is
4852 given two arguments, the start and end of the region. FUNCTION
4853 may set `yank-undo-function' to override UNDO.
4855 See also the command `yank-pop' (\\[yank-pop])."
4856 (interactive "*P")
4857 (setq yank-window-start (window-start))
4858 ;; If we don't get all the way thru, make last-command indicate that
4859 ;; for the following command.
4860 (setq this-command t)
4861 (push-mark (point))
4862 (insert-for-yank (current-kill (cond
4863 ((listp arg) 0)
4864 ((eq arg '-) -2)
4865 (t (1- arg)))))
4866 (if (consp arg)
4867 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4868 ;; It is cleaner to avoid activation, even though the command
4869 ;; loop would deactivate the mark because we inserted text.
4870 (goto-char (prog1 (mark t)
4871 (set-marker (mark-marker) (point) (current-buffer)))))
4872 ;; If we do get all the way thru, make this-command indicate that.
4873 (if (eq this-command t)
4874 (setq this-command 'yank))
4875 nil)
4877 (defun rotate-yank-pointer (arg)
4878 "Rotate the yanking point in the kill ring.
4879 With ARG, rotate that many kills forward (or backward, if negative)."
4880 (interactive "p")
4881 (current-kill arg))
4883 ;; Some kill commands.
4885 ;; Internal subroutine of delete-char
4886 (defun kill-forward-chars (arg)
4887 (if (listp arg) (setq arg (car arg)))
4888 (if (eq arg '-) (setq arg -1))
4889 (kill-region (point) (+ (point) arg)))
4891 ;; Internal subroutine of backward-delete-char
4892 (defun kill-backward-chars (arg)
4893 (if (listp arg) (setq arg (car arg)))
4894 (if (eq arg '-) (setq arg -1))
4895 (kill-region (point) (- (point) arg)))
4897 (defcustom backward-delete-char-untabify-method 'untabify
4898 "The method for untabifying when deleting backward.
4899 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4900 `hungry' -- delete all whitespace, both tabs and spaces;
4901 `all' -- delete all whitespace, including tabs, spaces and newlines;
4902 nil -- just delete one character."
4903 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4904 :version "20.3"
4905 :group 'killing)
4907 (defun backward-delete-char-untabify (arg &optional killp)
4908 "Delete characters backward, changing tabs into spaces.
4909 The exact behavior depends on `backward-delete-char-untabify-method'.
4910 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4911 Interactively, ARG is the prefix arg (default 1)
4912 and KILLP is t if a prefix arg was specified."
4913 (interactive "*p\nP")
4914 (when (eq backward-delete-char-untabify-method 'untabify)
4915 (let ((count arg))
4916 (save-excursion
4917 (while (and (> count 0) (not (bobp)))
4918 (if (= (preceding-char) ?\t)
4919 (let ((col (current-column)))
4920 (forward-char -1)
4921 (setq col (- col (current-column)))
4922 (insert-char ?\s col)
4923 (delete-char 1)))
4924 (forward-char -1)
4925 (setq count (1- count))))))
4926 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4927 ((eq backward-delete-char-untabify-method 'all)
4928 " \t\n\r")))
4929 (n (if skip
4930 (let* ((oldpt (point))
4931 (wh (- oldpt (save-excursion
4932 (skip-chars-backward skip)
4933 (constrain-to-field nil oldpt)))))
4934 (+ arg (if (zerop wh) 0 (1- wh))))
4935 arg)))
4936 ;; Avoid warning about delete-backward-char
4937 (with-no-warnings (delete-backward-char n killp))))
4939 (defun zap-to-char (arg char)
4940 "Kill up to and including ARGth occurrence of CHAR.
4941 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4942 Goes backward if ARG is negative; error if CHAR not found."
4943 (interactive (list (prefix-numeric-value current-prefix-arg)
4944 (read-char "Zap to char: " t)))
4945 ;; Avoid "obsolete" warnings for translation-table-for-input.
4946 (with-no-warnings
4947 (if (char-table-p translation-table-for-input)
4948 (setq char (or (aref translation-table-for-input char) char))))
4949 (kill-region (point) (progn
4950 (search-forward (char-to-string char) nil nil arg)
4951 (point))))
4953 ;; kill-line and its subroutines.
4955 (defcustom kill-whole-line nil
4956 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4957 :type 'boolean
4958 :group 'killing)
4960 (defun kill-line (&optional arg)
4961 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4962 With prefix argument ARG, kill that many lines from point.
4963 Negative arguments kill lines backward.
4964 With zero argument, kills the text before point on the current line.
4966 When calling from a program, nil means \"no arg\",
4967 a number counts as a prefix arg.
4969 To kill a whole line, when point is not at the beginning, type \
4970 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4972 If `show-trailing-whitespace' is non-nil, this command will just
4973 kill the rest of the current line, even if there are no nonblanks
4974 there.
4976 If option `kill-whole-line' is non-nil, then this command kills the whole line
4977 including its terminating newline, when used at the beginning of a line
4978 with no argument. As a consequence, you can always kill a whole line
4979 by typing \\[move-beginning-of-line] \\[kill-line].
4981 If you want to append the killed line to the last killed text,
4982 use \\[append-next-kill] before \\[kill-line].
4984 If the buffer is read-only, Emacs will beep and refrain from deleting
4985 the line, but put the line in the kill ring anyway. This means that
4986 you can use this command to copy text from a read-only buffer.
4987 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4988 even beep.)"
4989 (interactive "P")
4990 (kill-region (point)
4991 ;; It is better to move point to the other end of the kill
4992 ;; before killing. That way, in a read-only buffer, point
4993 ;; moves across the text that is copied to the kill ring.
4994 ;; The choice has no effect on undo now that undo records
4995 ;; the value of point from before the command was run.
4996 (progn
4997 (if arg
4998 (forward-visible-line (prefix-numeric-value arg))
4999 (if (eobp)
5000 (signal 'end-of-buffer nil))
5001 (let ((end
5002 (save-excursion
5003 (end-of-visible-line) (point))))
5004 (if (or (save-excursion
5005 ;; If trailing whitespace is visible,
5006 ;; don't treat it as nothing.
5007 (unless show-trailing-whitespace
5008 (skip-chars-forward " \t" end))
5009 (= (point) end))
5010 (and kill-whole-line (bolp)))
5011 (forward-visible-line 1)
5012 (goto-char end))))
5013 (point))))
5015 (defun kill-whole-line (&optional arg)
5016 "Kill current line.
5017 With prefix ARG, kill that many lines starting from the current line.
5018 If ARG is negative, kill backward. Also kill the preceding newline.
5019 \(This is meant to make \\[repeat] work well with negative arguments.)
5020 If ARG is zero, kill current line but exclude the trailing newline."
5021 (interactive "p")
5022 (or arg (setq arg 1))
5023 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5024 (signal 'end-of-buffer nil))
5025 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5026 (signal 'beginning-of-buffer nil))
5027 (unless (eq last-command 'kill-region)
5028 (kill-new "")
5029 (setq last-command 'kill-region))
5030 (cond ((zerop arg)
5031 ;; We need to kill in two steps, because the previous command
5032 ;; could have been a kill command, in which case the text
5033 ;; before point needs to be prepended to the current kill
5034 ;; ring entry and the text after point appended. Also, we
5035 ;; need to use save-excursion to avoid copying the same text
5036 ;; twice to the kill ring in read-only buffers.
5037 (save-excursion
5038 (kill-region (point) (progn (forward-visible-line 0) (point))))
5039 (kill-region (point) (progn (end-of-visible-line) (point))))
5040 ((< arg 0)
5041 (save-excursion
5042 (kill-region (point) (progn (end-of-visible-line) (point))))
5043 (kill-region (point)
5044 (progn (forward-visible-line (1+ arg))
5045 (unless (bobp) (backward-char))
5046 (point))))
5048 (save-excursion
5049 (kill-region (point) (progn (forward-visible-line 0) (point))))
5050 (kill-region (point)
5051 (progn (forward-visible-line arg) (point))))))
5053 (defun forward-visible-line (arg)
5054 "Move forward by ARG lines, ignoring currently invisible newlines only.
5055 If ARG is negative, move backward -ARG lines.
5056 If ARG is zero, move to the beginning of the current line."
5057 (condition-case nil
5058 (if (> arg 0)
5059 (progn
5060 (while (> arg 0)
5061 (or (zerop (forward-line 1))
5062 (signal 'end-of-buffer nil))
5063 ;; If the newline we just skipped is invisible,
5064 ;; don't count it.
5065 (let ((prop
5066 (get-char-property (1- (point)) 'invisible)))
5067 (if (if (eq buffer-invisibility-spec t)
5068 prop
5069 (or (memq prop buffer-invisibility-spec)
5070 (assq prop buffer-invisibility-spec)))
5071 (setq arg (1+ arg))))
5072 (setq arg (1- arg)))
5073 ;; If invisible text follows, and it is a number of complete lines,
5074 ;; skip it.
5075 (let ((opoint (point)))
5076 (while (and (not (eobp))
5077 (let ((prop
5078 (get-char-property (point) 'invisible)))
5079 (if (eq buffer-invisibility-spec t)
5080 prop
5081 (or (memq prop buffer-invisibility-spec)
5082 (assq prop buffer-invisibility-spec)))))
5083 (goto-char
5084 (if (get-text-property (point) 'invisible)
5085 (or (next-single-property-change (point) 'invisible)
5086 (point-max))
5087 (next-overlay-change (point)))))
5088 (unless (bolp)
5089 (goto-char opoint))))
5090 (let ((first t))
5091 (while (or first (<= arg 0))
5092 (if first
5093 (beginning-of-line)
5094 (or (zerop (forward-line -1))
5095 (signal 'beginning-of-buffer nil)))
5096 ;; If the newline we just moved to is invisible,
5097 ;; don't count it.
5098 (unless (bobp)
5099 (let ((prop
5100 (get-char-property (1- (point)) 'invisible)))
5101 (unless (if (eq buffer-invisibility-spec t)
5102 prop
5103 (or (memq prop buffer-invisibility-spec)
5104 (assq prop buffer-invisibility-spec)))
5105 (setq arg (1+ arg)))))
5106 (setq first nil))
5107 ;; If invisible text follows, and it is a number of complete lines,
5108 ;; skip it.
5109 (let ((opoint (point)))
5110 (while (and (not (bobp))
5111 (let ((prop
5112 (get-char-property (1- (point)) 'invisible)))
5113 (if (eq buffer-invisibility-spec t)
5114 prop
5115 (or (memq prop buffer-invisibility-spec)
5116 (assq prop buffer-invisibility-spec)))))
5117 (goto-char
5118 (if (get-text-property (1- (point)) 'invisible)
5119 (or (previous-single-property-change (point) 'invisible)
5120 (point-min))
5121 (previous-overlay-change (point)))))
5122 (unless (bolp)
5123 (goto-char opoint)))))
5124 ((beginning-of-buffer end-of-buffer)
5125 nil)))
5127 (defun end-of-visible-line ()
5128 "Move to end of current visible line."
5129 (end-of-line)
5130 ;; If the following character is currently invisible,
5131 ;; skip all characters with that same `invisible' property value,
5132 ;; then find the next newline.
5133 (while (and (not (eobp))
5134 (save-excursion
5135 (skip-chars-forward "^\n")
5136 (let ((prop
5137 (get-char-property (point) 'invisible)))
5138 (if (eq buffer-invisibility-spec t)
5139 prop
5140 (or (memq prop buffer-invisibility-spec)
5141 (assq prop buffer-invisibility-spec))))))
5142 (skip-chars-forward "^\n")
5143 (if (get-text-property (point) 'invisible)
5144 (goto-char (or (next-single-property-change (point) 'invisible)
5145 (point-max)))
5146 (goto-char (next-overlay-change (point))))
5147 (end-of-line)))
5149 (defun insert-buffer (buffer)
5150 "Insert after point the contents of BUFFER.
5151 Puts mark after the inserted text.
5152 BUFFER may be a buffer or a buffer name."
5153 (declare (interactive-only insert-buffer-substring))
5154 (interactive
5155 (list
5156 (progn
5157 (barf-if-buffer-read-only)
5158 (read-buffer "Insert buffer: "
5159 (if (eq (selected-window) (next-window))
5160 (other-buffer (current-buffer))
5161 (window-buffer (next-window)))
5162 t))))
5163 (push-mark
5164 (save-excursion
5165 (insert-buffer-substring (get-buffer buffer))
5166 (point)))
5167 nil)
5169 (defun append-to-buffer (buffer start end)
5170 "Append to specified buffer the text of the region.
5171 It is inserted into that buffer before its point.
5173 When calling from a program, give three arguments:
5174 BUFFER (or buffer name), START and END.
5175 START and END specify the portion of the current buffer to be copied."
5176 (interactive
5177 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5178 (region-beginning) (region-end)))
5179 (let* ((oldbuf (current-buffer))
5180 (append-to (get-buffer-create buffer))
5181 (windows (get-buffer-window-list append-to t t))
5182 point)
5183 (save-excursion
5184 (with-current-buffer append-to
5185 (setq point (point))
5186 (barf-if-buffer-read-only)
5187 (insert-buffer-substring oldbuf start end)
5188 (dolist (window windows)
5189 (when (= (window-point window) point)
5190 (set-window-point window (point))))))))
5192 (defun prepend-to-buffer (buffer start end)
5193 "Prepend to specified buffer the text of the region.
5194 It is inserted into that buffer after its point.
5196 When calling from a program, give three arguments:
5197 BUFFER (or buffer name), START and END.
5198 START and END specify the portion of the current buffer to be copied."
5199 (interactive "BPrepend to buffer: \nr")
5200 (let ((oldbuf (current-buffer)))
5201 (with-current-buffer (get-buffer-create buffer)
5202 (barf-if-buffer-read-only)
5203 (save-excursion
5204 (insert-buffer-substring oldbuf start end)))))
5206 (defun copy-to-buffer (buffer start end)
5207 "Copy to specified buffer the text of the region.
5208 It is inserted into that buffer, replacing existing text there.
5210 When calling from a program, give three arguments:
5211 BUFFER (or buffer name), START and END.
5212 START and END specify the portion of the current buffer to be copied."
5213 (interactive "BCopy to buffer: \nr")
5214 (let ((oldbuf (current-buffer)))
5215 (with-current-buffer (get-buffer-create buffer)
5216 (barf-if-buffer-read-only)
5217 (erase-buffer)
5218 (save-excursion
5219 (insert-buffer-substring oldbuf start end)))))
5221 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5223 (defvar activate-mark-hook nil
5224 "Hook run when the mark becomes active.
5225 It is also run at the end of a command, if the mark is active and
5226 it is possible that the region may have changed.")
5228 (defvar deactivate-mark-hook nil
5229 "Hook run when the mark becomes inactive.")
5231 (defun mark (&optional force)
5232 "Return this buffer's mark value as integer, or nil if never set.
5234 In Transient Mark mode, this function signals an error if
5235 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5236 or the argument FORCE is non-nil, it disregards whether the mark
5237 is active, and returns an integer or nil in the usual way.
5239 If you are using this in an editing command, you are most likely making
5240 a mistake; see the documentation of `set-mark'."
5241 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5242 (marker-position (mark-marker))
5243 (signal 'mark-inactive nil)))
5245 ;; Behind display-selections-p.
5247 (defun deactivate-mark (&optional force)
5248 "Deactivate the mark.
5249 If Transient Mark mode is disabled, this function normally does
5250 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5252 Deactivating the mark sets `mark-active' to nil, updates the
5253 primary selection according to `select-active-regions', and runs
5254 `deactivate-mark-hook'.
5256 If Transient Mark mode was temporarily enabled, reset the value
5257 of the variable `transient-mark-mode'; if this causes Transient
5258 Mark mode to be disabled, don't change `mark-active' to nil or
5259 run `deactivate-mark-hook'."
5260 (when (or (region-active-p) force)
5261 (when (and (if (eq select-active-regions 'only)
5262 (eq (car-safe transient-mark-mode) 'only)
5263 select-active-regions)
5264 (region-active-p)
5265 (display-selections-p))
5266 ;; The var `saved-region-selection', if non-nil, is the text in
5267 ;; the region prior to the last command modifying the buffer.
5268 ;; Set the selection to that, or to the current region.
5269 (cond (saved-region-selection
5270 (if (gui-backend-selection-owner-p 'PRIMARY)
5271 (gui-set-selection 'PRIMARY saved-region-selection))
5272 (setq saved-region-selection nil))
5273 ;; If another program has acquired the selection, region
5274 ;; deactivation should not clobber it (Bug#11772).
5275 ((and (/= (region-beginning) (region-end))
5276 (or (gui-backend-selection-owner-p 'PRIMARY)
5277 (null (gui-backend-selection-exists-p 'PRIMARY))))
5278 (gui-set-selection 'PRIMARY
5279 (funcall region-extract-function nil)))))
5280 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5281 (cond
5282 ((eq (car-safe transient-mark-mode) 'only)
5283 (setq transient-mark-mode (cdr transient-mark-mode))
5284 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5285 (kill-local-variable 'transient-mark-mode)))
5286 ((eq transient-mark-mode 'lambda)
5287 (kill-local-variable 'transient-mark-mode)))
5288 (setq mark-active nil)
5289 (run-hooks 'deactivate-mark-hook)
5290 (redisplay--update-region-highlight (selected-window))))
5292 (defun activate-mark (&optional no-tmm)
5293 "Activate the mark.
5294 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5295 (when (mark t)
5296 (unless (region-active-p)
5297 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5298 (setq mark-active t)
5299 (unless (or transient-mark-mode no-tmm)
5300 (setq-local transient-mark-mode 'lambda))
5301 (run-hooks 'activate-mark-hook))))
5303 (defun set-mark (pos)
5304 "Set this buffer's mark to POS. Don't use this function!
5305 That is to say, don't use this function unless you want
5306 the user to see that the mark has moved, and you want the previous
5307 mark position to be lost.
5309 Normally, when a new mark is set, the old one should go on the stack.
5310 This is why most applications should use `push-mark', not `set-mark'.
5312 Novice Emacs Lisp programmers often try to use the mark for the wrong
5313 purposes. The mark saves a location for the user's convenience.
5314 Most editing commands should not alter the mark.
5315 To remember a location for internal use in the Lisp program,
5316 store it in a Lisp variable. Example:
5318 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5319 (if pos
5320 (progn
5321 (set-marker (mark-marker) pos (current-buffer))
5322 (activate-mark 'no-tmm))
5323 ;; Normally we never clear mark-active except in Transient Mark mode.
5324 ;; But when we actually clear out the mark value too, we must
5325 ;; clear mark-active in any mode.
5326 (deactivate-mark t)
5327 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5328 ;; it should never be nil if the mark is nil.
5329 (setq mark-active nil)
5330 (set-marker (mark-marker) nil)))
5332 (defun save-mark-and-excursion--save ()
5333 (cons
5334 (let ((mark (mark-marker)))
5335 (and (marker-position mark) (copy-marker mark)))
5336 mark-active))
5338 (defun save-mark-and-excursion--restore (saved-mark-info)
5339 (let ((saved-mark (car saved-mark-info))
5340 (omark (marker-position (mark-marker)))
5341 (nmark nil)
5342 (saved-mark-active (cdr saved-mark-info)))
5343 ;; Mark marker
5344 (if (null saved-mark)
5345 (set-marker (mark-marker) nil)
5346 (setf nmark (marker-position saved-mark))
5347 (set-marker (mark-marker) nmark)
5348 (set-marker saved-mark nil))
5349 ;; Mark active
5350 (let ((cur-mark-active mark-active))
5351 (setq mark-active saved-mark-active)
5352 ;; If mark is active now, and either was not active or was at a
5353 ;; different place, run the activate hook.
5354 (if saved-mark-active
5355 (when (or (not cur-mark-active)
5356 (not (eq omark nmark)))
5357 (run-hooks 'activate-mark-hook))
5358 ;; If mark has ceased to be active, run deactivate hook.
5359 (when cur-mark-active
5360 (run-hooks 'deactivate-mark-hook))))))
5362 (defmacro save-mark-and-excursion (&rest body)
5363 "Like `save-excursion', but also save and restore the mark state.
5364 This macro does what `save-excursion' did before Emacs 25.1."
5365 (declare (indent 0) (debug t))
5366 (let ((saved-marker-sym (make-symbol "saved-marker")))
5367 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5368 (unwind-protect
5369 (save-excursion ,@body)
5370 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5372 (defcustom use-empty-active-region nil
5373 "Whether \"region-aware\" commands should act on empty regions.
5374 If nil, region-aware commands treat the empty region as inactive.
5375 If non-nil, region-aware commands treat the region as active as
5376 long as the mark is active, even if the region is empty.
5378 Region-aware commands are those that act on the region if it is
5379 active and Transient Mark mode is enabled, and on the text near
5380 point otherwise."
5381 :type 'boolean
5382 :version "23.1"
5383 :group 'editing-basics)
5385 (defun use-region-p ()
5386 "Return t if the region is active and it is appropriate to act on it.
5387 This is used by commands that act specially on the region under
5388 Transient Mark mode.
5390 The return value is t if Transient Mark mode is enabled and the
5391 mark is active; furthermore, if `use-empty-active-region' is nil,
5392 the region must not be empty. Otherwise, the return value is nil.
5394 For some commands, it may be appropriate to ignore the value of
5395 `use-empty-active-region'; in that case, use `region-active-p'."
5396 (and (region-active-p)
5397 (or use-empty-active-region (> (region-end) (region-beginning)))))
5399 (defun region-active-p ()
5400 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5402 Some commands act specially on the region when Transient Mark
5403 mode is enabled. Usually, such commands should use
5404 `use-region-p' instead of this function, because `use-region-p'
5405 also checks the value of `use-empty-active-region'."
5406 (and transient-mark-mode mark-active
5407 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5408 ;; without the mark being set (e.g. bug#17324). We really should fix
5409 ;; that problem, but in the mean time, let's make sure we don't say the
5410 ;; region is active when there's no mark.
5411 (progn (cl-assert (mark)) t)))
5413 (defun region-bounds ()
5414 "Return the boundaries of the region as a list of (START . END) positions."
5415 (funcall region-extract-function 'bounds))
5417 (defun region-noncontiguous-p ()
5418 "Return non-nil if the region contains several pieces.
5419 An example is a rectangular region handled as a list of
5420 separate contiguous regions for each line."
5421 (> (length (region-bounds)) 1))
5423 (defvar redisplay-unhighlight-region-function
5424 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5426 (defvar redisplay-highlight-region-function
5427 (lambda (start end window rol)
5428 (if (not (overlayp rol))
5429 (let ((nrol (make-overlay start end)))
5430 (funcall redisplay-unhighlight-region-function rol)
5431 (overlay-put nrol 'window window)
5432 (overlay-put nrol 'face 'region)
5433 ;; Normal priority so that a large region doesn't hide all the
5434 ;; overlays within it, but high secondary priority so that if it
5435 ;; ends/starts in the middle of a small overlay, that small overlay
5436 ;; won't hide the region's boundaries.
5437 (overlay-put nrol 'priority '(nil . 100))
5438 nrol)
5439 (unless (and (eq (overlay-buffer rol) (current-buffer))
5440 (eq (overlay-start rol) start)
5441 (eq (overlay-end rol) end))
5442 (move-overlay rol start end (current-buffer)))
5443 rol)))
5445 (defun redisplay--update-region-highlight (window)
5446 (let ((rol (window-parameter window 'internal-region-overlay)))
5447 (if (not (and (region-active-p)
5448 (or highlight-nonselected-windows
5449 (eq window (selected-window))
5450 (and (window-minibuffer-p)
5451 (eq window (minibuffer-selected-window))))))
5452 (funcall redisplay-unhighlight-region-function rol)
5453 (let* ((pt (window-point window))
5454 (mark (mark))
5455 (start (min pt mark))
5456 (end (max pt mark))
5457 (new
5458 (funcall redisplay-highlight-region-function
5459 start end window rol)))
5460 (unless (equal new rol)
5461 (set-window-parameter window 'internal-region-overlay
5462 new))))))
5464 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5465 "Hook run just before redisplay.
5466 It is called in each window that is to be redisplayed. It takes one argument,
5467 which is the window that will be redisplayed. When run, the `current-buffer'
5468 is set to the buffer displayed in that window.")
5470 (defun redisplay--pre-redisplay-functions (windows)
5471 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5472 (if (null windows)
5473 (with-current-buffer (window-buffer (selected-window))
5474 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5475 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5476 (with-current-buffer (window-buffer win)
5477 (run-hook-with-args 'pre-redisplay-functions win))))))
5479 (add-function :before pre-redisplay-function
5480 #'redisplay--pre-redisplay-functions)
5483 (defvar-local mark-ring nil
5484 "The list of former marks of the current buffer, most recent first.")
5485 (put 'mark-ring 'permanent-local t)
5487 (defcustom mark-ring-max 16
5488 "Maximum size of mark ring. Start discarding off end if gets this big."
5489 :type 'integer
5490 :group 'editing-basics)
5492 (defvar global-mark-ring nil
5493 "The list of saved global marks, most recent first.")
5495 (defcustom global-mark-ring-max 16
5496 "Maximum size of global mark ring. \
5497 Start discarding off end if gets this big."
5498 :type 'integer
5499 :group 'editing-basics)
5501 (defun pop-to-mark-command ()
5502 "Jump to mark, and pop a new position for mark off the ring.
5503 \(Does not affect global mark ring)."
5504 (interactive)
5505 (if (null (mark t))
5506 (user-error "No mark set in this buffer")
5507 (if (= (point) (mark t))
5508 (message "Mark popped"))
5509 (goto-char (mark t))
5510 (pop-mark)))
5512 (defun push-mark-command (arg &optional nomsg)
5513 "Set mark at where point is.
5514 If no prefix ARG and mark is already set there, just activate it.
5515 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5516 (interactive "P")
5517 (let ((mark (mark t)))
5518 (if (or arg (null mark) (/= mark (point)))
5519 (push-mark nil nomsg t)
5520 (activate-mark 'no-tmm)
5521 (unless nomsg
5522 (message "Mark activated")))))
5524 (defcustom set-mark-command-repeat-pop nil
5525 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5526 That means that C-u \\[set-mark-command] \\[set-mark-command]
5527 will pop the mark twice, and
5528 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5529 will pop the mark three times.
5531 A value of nil means \\[set-mark-command]'s behavior does not change
5532 after C-u \\[set-mark-command]."
5533 :type 'boolean
5534 :group 'editing-basics)
5536 (defun set-mark-command (arg)
5537 "Set the mark where point is, and activate it; or jump to the mark.
5538 Setting the mark also alters the region, which is the text
5539 between point and mark; this is the closest equivalent in
5540 Emacs to what some editors call the \"selection\".
5542 With no prefix argument, set the mark at point, and push the
5543 old mark position on local mark ring. Also push the new mark on
5544 global mark ring, if the previous mark was set in another buffer.
5546 When Transient Mark Mode is off, immediately repeating this
5547 command activates `transient-mark-mode' temporarily.
5549 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5550 jump to the mark, and set the mark from
5551 position popped off the local mark ring (this does not affect the global
5552 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5553 mark ring (see `pop-global-mark').
5555 If `set-mark-command-repeat-pop' is non-nil, repeating
5556 the \\[set-mark-command] command with no prefix argument pops the next position
5557 off the local (or global) mark ring and jumps there.
5559 With \\[universal-argument] \\[universal-argument] as prefix
5560 argument, unconditionally set mark where point is, even if
5561 `set-mark-command-repeat-pop' is non-nil.
5563 Novice Emacs Lisp programmers often try to use the mark for the wrong
5564 purposes. See the documentation of `set-mark' for more information."
5565 (interactive "P")
5566 (cond ((eq transient-mark-mode 'lambda)
5567 (kill-local-variable 'transient-mark-mode))
5568 ((eq (car-safe transient-mark-mode) 'only)
5569 (deactivate-mark)))
5570 (cond
5571 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5572 (push-mark-command nil))
5573 ((not (eq this-command 'set-mark-command))
5574 (if arg
5575 (pop-to-mark-command)
5576 (push-mark-command t)))
5577 ((and set-mark-command-repeat-pop
5578 (eq last-command 'pop-global-mark)
5579 (not arg))
5580 (setq this-command 'pop-global-mark)
5581 (pop-global-mark))
5582 ((or (and set-mark-command-repeat-pop
5583 (eq last-command 'pop-to-mark-command))
5584 arg)
5585 (setq this-command 'pop-to-mark-command)
5586 (pop-to-mark-command))
5587 ((eq last-command 'set-mark-command)
5588 (if (region-active-p)
5589 (progn
5590 (deactivate-mark)
5591 (message "Mark deactivated"))
5592 (activate-mark)
5593 (message "Mark activated")))
5595 (push-mark-command nil))))
5597 (defun push-mark (&optional location nomsg activate)
5598 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5599 If the last global mark pushed was not in the current buffer,
5600 also push LOCATION on the global mark ring.
5601 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5603 Novice Emacs Lisp programmers often try to use the mark for the wrong
5604 purposes. See the documentation of `set-mark' for more information.
5606 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5607 (unless (null (mark t))
5608 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5609 (when (> (length mark-ring) mark-ring-max)
5610 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5611 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5612 (set-marker (mark-marker) (or location (point)) (current-buffer))
5613 ;; Now push the mark on the global mark ring.
5614 (if (and global-mark-ring
5615 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5616 ;; The last global mark pushed was in this same buffer.
5617 ;; Don't push another one.
5619 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5620 (when (> (length global-mark-ring) global-mark-ring-max)
5621 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5622 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5623 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5624 (message "Mark set"))
5625 (if (or activate (not transient-mark-mode))
5626 (set-mark (mark t)))
5627 nil)
5629 (defun pop-mark ()
5630 "Pop off mark ring into the buffer's actual mark.
5631 Does not set point. Does nothing if mark ring is empty."
5632 (when mark-ring
5633 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5634 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5635 (move-marker (car mark-ring) nil)
5636 (if (null (mark t)) (ding))
5637 (setq mark-ring (cdr mark-ring)))
5638 (deactivate-mark))
5640 (define-obsolete-function-alias
5641 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5642 (defun exchange-point-and-mark (&optional arg)
5643 "Put the mark where point is now, and point where the mark is now.
5644 This command works even when the mark is not active,
5645 and it reactivates the mark.
5647 If Transient Mark mode is on, a prefix ARG deactivates the mark
5648 if it is active, and otherwise avoids reactivating it. If
5649 Transient Mark mode is off, a prefix ARG enables Transient Mark
5650 mode temporarily."
5651 (interactive "P")
5652 (let ((omark (mark t))
5653 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5654 (if (null omark)
5655 (user-error "No mark set in this buffer"))
5656 (set-mark (point))
5657 (goto-char omark)
5658 (cond (temp-highlight
5659 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5660 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5661 (not (or arg (region-active-p))))
5662 (deactivate-mark))
5663 (t (activate-mark)))
5664 nil))
5666 (defcustom shift-select-mode t
5667 "When non-nil, shifted motion keys activate the mark momentarily.
5669 While the mark is activated in this way, any shift-translated point
5670 motion key extends the region, and if Transient Mark mode was off, it
5671 is temporarily turned on. Furthermore, the mark will be deactivated
5672 by any subsequent point motion key that was not shift-translated, or
5673 by any action that normally deactivates the mark in Transient Mark mode.
5675 See `this-command-keys-shift-translated' for the meaning of
5676 shift-translation."
5677 :type 'boolean
5678 :group 'editing-basics)
5680 (defun handle-shift-selection ()
5681 "Activate/deactivate mark depending on invocation thru shift translation.
5682 This function is called by `call-interactively' when a command
5683 with a `^' character in its `interactive' spec is invoked, before
5684 running the command itself.
5686 If `shift-select-mode' is enabled and the command was invoked
5687 through shift translation, set the mark and activate the region
5688 temporarily, unless it was already set in this way. See
5689 `this-command-keys-shift-translated' for the meaning of shift
5690 translation.
5692 Otherwise, if the region has been activated temporarily,
5693 deactivate it, and restore the variable `transient-mark-mode' to
5694 its earlier value."
5695 (cond ((and shift-select-mode this-command-keys-shift-translated)
5696 (unless (and mark-active
5697 (eq (car-safe transient-mark-mode) 'only))
5698 (setq-local transient-mark-mode
5699 (cons 'only
5700 (unless (eq transient-mark-mode 'lambda)
5701 transient-mark-mode)))
5702 (push-mark nil nil t)))
5703 ((eq (car-safe transient-mark-mode) 'only)
5704 (setq transient-mark-mode (cdr transient-mark-mode))
5705 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5706 (kill-local-variable 'transient-mark-mode))
5707 (deactivate-mark))))
5709 (define-minor-mode transient-mark-mode
5710 "Toggle Transient Mark mode.
5711 With a prefix argument ARG, enable Transient Mark mode if ARG is
5712 positive, and disable it otherwise. If called from Lisp, enable
5713 Transient Mark mode if ARG is omitted or nil.
5715 Transient Mark mode is a global minor mode. When enabled, the
5716 region is highlighted with the `region' face whenever the mark
5717 is active. The mark is \"deactivated\" by changing the buffer,
5718 and after certain other operations that set the mark but whose
5719 main purpose is something else--for example, incremental search,
5720 \\[beginning-of-buffer], and \\[end-of-buffer].
5722 You can also deactivate the mark by typing \\[keyboard-quit] or
5723 \\[keyboard-escape-quit].
5725 Many commands change their behavior when Transient Mark mode is
5726 in effect and the mark is active, by acting on the region instead
5727 of their usual default part of the buffer's text. Examples of
5728 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5729 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5730 To see the documentation of commands which are sensitive to the
5731 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5732 or \"mark.*active\" at the prompt."
5733 :global t
5734 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5735 :variable (default-value 'transient-mark-mode))
5737 (defvar widen-automatically t
5738 "Non-nil means it is ok for commands to call `widen' when they want to.
5739 Some commands will do this in order to go to positions outside
5740 the current accessible part of the buffer.
5742 If `widen-automatically' is nil, these commands will do something else
5743 as a fallback, and won't change the buffer bounds.")
5745 (defvar non-essential nil
5746 "Whether the currently executing code is performing an essential task.
5747 This variable should be non-nil only when running code which should not
5748 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5749 user for a password when we are simply scanning a set of files in the
5750 background or displaying possible completions before the user even asked
5751 for it.")
5753 (defun pop-global-mark ()
5754 "Pop off global mark ring and jump to the top location."
5755 (interactive)
5756 ;; Pop entries which refer to non-existent buffers.
5757 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5758 (setq global-mark-ring (cdr global-mark-ring)))
5759 (or global-mark-ring
5760 (error "No global mark set"))
5761 (let* ((marker (car global-mark-ring))
5762 (buffer (marker-buffer marker))
5763 (position (marker-position marker)))
5764 (setq global-mark-ring (nconc (cdr global-mark-ring)
5765 (list (car global-mark-ring))))
5766 (set-buffer buffer)
5767 (or (and (>= position (point-min))
5768 (<= position (point-max)))
5769 (if widen-automatically
5770 (widen)
5771 (error "Global mark position is outside accessible part of buffer")))
5772 (goto-char position)
5773 (switch-to-buffer buffer)))
5775 (defcustom next-line-add-newlines nil
5776 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5777 :type 'boolean
5778 :version "21.1"
5779 :group 'editing-basics)
5781 (defun next-line (&optional arg try-vscroll)
5782 "Move cursor vertically down ARG lines.
5783 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5784 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5785 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5786 function will not vscroll.
5788 ARG defaults to 1.
5790 If there is no character in the target line exactly under the current column,
5791 the cursor is positioned after the character in that line which spans this
5792 column, or at the end of the line if it is not long enough.
5793 If there is no line in the buffer after this one, behavior depends on the
5794 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5795 to create a line, and moves the cursor to that line. Otherwise it moves the
5796 cursor to the end of the buffer.
5798 If the variable `line-move-visual' is non-nil, this command moves
5799 by display lines. Otherwise, it moves by buffer lines, without
5800 taking variable-width characters or continued lines into account.
5801 See \\[next-logical-line] for a command that always moves by buffer lines.
5803 The command \\[set-goal-column] can be used to create
5804 a semipermanent goal column for this command.
5805 Then instead of trying to move exactly vertically (or as close as possible),
5806 this command moves to the specified goal column (or as close as possible).
5807 The goal column is stored in the variable `goal-column', which is nil
5808 when there is no goal column. Note that setting `goal-column'
5809 overrides `line-move-visual' and causes this command to move by buffer
5810 lines rather than by display lines."
5811 (declare (interactive-only forward-line))
5812 (interactive "^p\np")
5813 (or arg (setq arg 1))
5814 (if (and next-line-add-newlines (= arg 1))
5815 (if (save-excursion (end-of-line) (eobp))
5816 ;; When adding a newline, don't expand an abbrev.
5817 (let ((abbrev-mode nil))
5818 (end-of-line)
5819 (insert (if use-hard-newlines hard-newline "\n")))
5820 (line-move arg nil nil try-vscroll))
5821 (if (called-interactively-p 'interactive)
5822 (condition-case err
5823 (line-move arg nil nil try-vscroll)
5824 ((beginning-of-buffer end-of-buffer)
5825 (signal (car err) (cdr err))))
5826 (line-move arg nil nil try-vscroll)))
5827 nil)
5829 (defun previous-line (&optional arg try-vscroll)
5830 "Move cursor vertically up ARG lines.
5831 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5832 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5833 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5834 function will not vscroll.
5836 ARG defaults to 1.
5838 If there is no character in the target line exactly over the current column,
5839 the cursor is positioned after the character in that line which spans this
5840 column, or at the end of the line if it is not long enough.
5842 If the variable `line-move-visual' is non-nil, this command moves
5843 by display lines. Otherwise, it moves by buffer lines, without
5844 taking variable-width characters or continued lines into account.
5845 See \\[previous-logical-line] for a command that always moves by buffer lines.
5847 The command \\[set-goal-column] can be used to create
5848 a semipermanent goal column for this command.
5849 Then instead of trying to move exactly vertically (or as close as possible),
5850 this command moves to the specified goal column (or as close as possible).
5851 The goal column is stored in the variable `goal-column', which is nil
5852 when there is no goal column. Note that setting `goal-column'
5853 overrides `line-move-visual' and causes this command to move by buffer
5854 lines rather than by display lines."
5855 (declare (interactive-only
5856 "use `forward-line' with negative argument instead."))
5857 (interactive "^p\np")
5858 (or arg (setq arg 1))
5859 (if (called-interactively-p 'interactive)
5860 (condition-case err
5861 (line-move (- arg) nil nil try-vscroll)
5862 ((beginning-of-buffer end-of-buffer)
5863 (signal (car err) (cdr err))))
5864 (line-move (- arg) nil nil try-vscroll))
5865 nil)
5867 (defcustom track-eol nil
5868 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5869 This means moving to the end of each line moved onto.
5870 The beginning of a blank line does not count as the end of a line.
5871 This has no effect when the variable `line-move-visual' is non-nil."
5872 :type 'boolean
5873 :group 'editing-basics)
5875 (defcustom goal-column nil
5876 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5877 A non-nil setting overrides the variable `line-move-visual', which see."
5878 :type '(choice integer
5879 (const :tag "None" nil))
5880 :group 'editing-basics)
5881 (make-variable-buffer-local 'goal-column)
5883 (defvar temporary-goal-column 0
5884 "Current goal column for vertical motion.
5885 It is the column where point was at the start of the current run
5886 of vertical motion commands.
5888 When moving by visual lines via the function `line-move-visual', it is a cons
5889 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5890 divided by the default column width, and HSCROLL is the number of
5891 columns by which window is scrolled from left margin.
5893 When the `track-eol' feature is doing its job, the value is
5894 `most-positive-fixnum'.")
5896 (defcustom line-move-ignore-invisible t
5897 "Non-nil means commands that move by lines ignore invisible newlines.
5898 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5899 as if newlines that are invisible didn't exist, and count
5900 only visible newlines. Thus, moving across across 2 newlines
5901 one of which is invisible will be counted as a one-line move.
5902 Also, a non-nil value causes invisible text to be ignored when
5903 counting columns for the purposes of keeping point in the same
5904 column by \\[next-line] and \\[previous-line].
5906 Outline mode sets this."
5907 :type 'boolean
5908 :group 'editing-basics)
5910 (defcustom line-move-visual t
5911 "When non-nil, `line-move' moves point by visual lines.
5912 This movement is based on where the cursor is displayed on the
5913 screen, instead of relying on buffer contents alone. It takes
5914 into account variable-width characters and line continuation.
5915 If nil, `line-move' moves point by logical lines.
5916 A non-nil setting of `goal-column' overrides the value of this variable
5917 and forces movement by logical lines.
5918 A window that is horizontally scrolled also forces movement by logical
5919 lines."
5920 :type 'boolean
5921 :group 'editing-basics
5922 :version "23.1")
5924 ;; Only used if display-graphic-p.
5925 (declare-function font-info "font.c" (name &optional frame))
5927 (defun default-font-height ()
5928 "Return the height in pixels of the current buffer's default face font.
5930 If the default font is remapped (see `face-remapping-alist'), the
5931 function returns the height of the remapped face."
5932 (let ((default-font (face-font 'default)))
5933 (cond
5934 ((and (display-multi-font-p)
5935 ;; Avoid calling font-info if the frame's default font was
5936 ;; not changed since the frame was created. That's because
5937 ;; font-info is expensive for some fonts, see bug #14838.
5938 (not (string= (frame-parameter nil 'font) default-font)))
5939 (aref (font-info default-font) 3))
5940 (t (frame-char-height)))))
5942 (defun default-font-width ()
5943 "Return the width in pixels of the current buffer's default face font.
5945 If the default font is remapped (see `face-remapping-alist'), the
5946 function returns the width of the remapped face."
5947 (let ((default-font (face-font 'default)))
5948 (cond
5949 ((and (display-multi-font-p)
5950 ;; Avoid calling font-info if the frame's default font was
5951 ;; not changed since the frame was created. That's because
5952 ;; font-info is expensive for some fonts, see bug #14838.
5953 (not (string= (frame-parameter nil 'font) default-font)))
5954 (let* ((info (font-info (face-font 'default)))
5955 (width (aref info 11)))
5956 (if (> width 0)
5957 width
5958 (aref info 10))))
5959 (t (frame-char-width)))))
5961 (defun default-line-height ()
5962 "Return the pixel height of current buffer's default-face text line.
5964 The value includes `line-spacing', if any, defined for the buffer
5965 or the frame."
5966 (let ((dfh (default-font-height))
5967 (lsp (if (display-graphic-p)
5968 (or line-spacing
5969 (default-value 'line-spacing)
5970 (frame-parameter nil 'line-spacing)
5972 0)))
5973 (if (floatp lsp)
5974 (setq lsp (truncate (* (frame-char-height) lsp))))
5975 (+ dfh lsp)))
5977 (defun window-screen-lines ()
5978 "Return the number of screen lines in the text area of the selected window.
5980 This is different from `window-text-height' in that this function counts
5981 lines in units of the height of the font used by the default face displayed
5982 in the window, not in units of the frame's default font, and also accounts
5983 for `line-spacing', if any, defined for the window's buffer or frame.
5985 The value is a floating-point number."
5986 (let ((edges (window-inside-pixel-edges))
5987 (dlh (default-line-height)))
5988 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5990 ;; Returns non-nil if partial move was done.
5991 (defun line-move-partial (arg noerror &optional _to-end)
5992 (if (< arg 0)
5993 ;; Move backward (up).
5994 ;; If already vscrolled, reduce vscroll
5995 (let ((vs (window-vscroll nil t))
5996 (dlh (default-line-height)))
5997 (when (> vs dlh)
5998 (set-window-vscroll nil (- vs dlh) t)))
6000 ;; Move forward (down).
6001 (let* ((lh (window-line-height -1))
6002 (rowh (car lh))
6003 (vpos (nth 1 lh))
6004 (ypos (nth 2 lh))
6005 (rbot (nth 3 lh))
6006 (this-lh (window-line-height))
6007 (this-height (car this-lh))
6008 (this-ypos (nth 2 this-lh))
6009 (dlh (default-line-height))
6010 (wslines (window-screen-lines))
6011 (edges (window-inside-pixel-edges))
6012 (winh (- (nth 3 edges) (nth 1 edges) 1))
6013 py vs last-line)
6014 (if (> (mod wslines 1.0) 0.0)
6015 (setq wslines (round (+ wslines 0.5))))
6016 (when (or (null lh)
6017 (>= rbot dlh)
6018 (<= ypos (- dlh))
6019 (null this-lh)
6020 (<= this-ypos (- dlh)))
6021 (unless lh
6022 (let ((wend (pos-visible-in-window-p t nil t)))
6023 (setq rbot (nth 3 wend)
6024 rowh (nth 4 wend)
6025 vpos (nth 5 wend))))
6026 (unless this-lh
6027 (let ((wstart (pos-visible-in-window-p nil nil t)))
6028 (setq this-ypos (nth 2 wstart)
6029 this-height (nth 4 wstart))))
6030 (setq py
6031 (or (nth 1 this-lh)
6032 (let ((ppos (posn-at-point))
6033 col-row)
6034 (setq col-row (posn-actual-col-row ppos))
6035 (if col-row
6036 (- (cdr col-row) (window-vscroll))
6037 (cdr (posn-col-row ppos))))))
6038 ;; VPOS > 0 means the last line is only partially visible.
6039 ;; But if the part that is visible is at least as tall as the
6040 ;; default font, that means the line is actually fully
6041 ;; readable, and something like line-spacing is hidden. So in
6042 ;; that case we accept the last line in the window as still
6043 ;; visible, and consider the margin as starting one line
6044 ;; later.
6045 (if (and vpos (> vpos 0))
6046 (if (and rowh
6047 (>= rowh (default-font-height))
6048 (< rowh dlh))
6049 (setq last-line (min (- wslines scroll-margin) vpos))
6050 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6051 (cond
6052 ;; If last line of window is fully visible, and vscrolling
6053 ;; more would make this line invisible, move forward.
6054 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6055 (null this-height)
6056 (<= this-height dlh))
6057 (or (null rbot) (= rbot 0)))
6058 nil)
6059 ;; If cursor is not in the bottom scroll margin, and the
6060 ;; current line is is not too tall, move forward.
6061 ((and (or (null this-height) (<= this-height winh))
6062 vpos
6063 (> vpos 0)
6064 (< py last-line))
6065 nil)
6066 ;; When already vscrolled, we vscroll some more if we can,
6067 ;; or clear vscroll and move forward at end of tall image.
6068 ((> vs 0)
6069 (when (or (and rbot (> rbot 0))
6070 (and this-height (> this-height dlh)))
6071 (set-window-vscroll nil (+ vs dlh) t)))
6072 ;; If cursor just entered the bottom scroll margin, move forward,
6073 ;; but also optionally vscroll one line so redisplay won't recenter.
6074 ((and vpos
6075 (> vpos 0)
6076 (= py last-line))
6077 ;; Don't vscroll if the partially-visible line at window
6078 ;; bottom is not too tall (a.k.a. "just one more text
6079 ;; line"): in that case, we do want redisplay to behave
6080 ;; normally, i.e. recenter or whatever.
6082 ;; Note: ROWH + RBOT from the value returned by
6083 ;; pos-visible-in-window-p give the total height of the
6084 ;; partially-visible glyph row at the end of the window. As
6085 ;; we are dealing with floats, we disregard sub-pixel
6086 ;; discrepancies between that and DLH.
6087 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6088 (set-window-vscroll nil dlh t))
6089 (line-move-1 arg noerror)
6091 ;; If there are lines above the last line, scroll-up one line.
6092 ((and vpos (> vpos 0))
6093 (scroll-up 1)
6095 ;; Finally, start vscroll.
6097 (set-window-vscroll nil dlh t)))))))
6100 ;; This is like line-move-1 except that it also performs
6101 ;; vertical scrolling of tall images if appropriate.
6102 ;; That is not really a clean thing to do, since it mixes
6103 ;; scrolling with cursor motion. But so far we don't have
6104 ;; a cleaner solution to the problem of making C-n do something
6105 ;; useful given a tall image.
6106 (defun line-move (arg &optional noerror _to-end try-vscroll)
6107 "Move forward ARG lines.
6108 If NOERROR, don't signal an error if we can't move ARG lines.
6109 TO-END is unused.
6110 TRY-VSCROLL controls whether to vscroll tall lines: if either
6111 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6112 not vscroll."
6113 (if noninteractive
6114 (line-move-1 arg noerror)
6115 (unless (and auto-window-vscroll try-vscroll
6116 ;; Only vscroll for single line moves
6117 (= (abs arg) 1)
6118 ;; Under scroll-conservatively, the display engine
6119 ;; does this better.
6120 (zerop scroll-conservatively)
6121 ;; But don't vscroll in a keyboard macro.
6122 (not defining-kbd-macro)
6123 (not executing-kbd-macro)
6124 (line-move-partial arg noerror))
6125 (set-window-vscroll nil 0 t)
6126 (if (and line-move-visual
6127 ;; Display-based column are incompatible with goal-column.
6128 (not goal-column)
6129 ;; When the text in the window is scrolled to the left,
6130 ;; display-based motion doesn't make sense (because each
6131 ;; logical line occupies exactly one screen line).
6132 (not (> (window-hscroll) 0))
6133 ;; Likewise when the text _was_ scrolled to the left
6134 ;; when the current run of vertical motion commands
6135 ;; started.
6136 (not (and (memq last-command
6137 `(next-line previous-line ,this-command))
6138 auto-hscroll-mode
6139 (numberp temporary-goal-column)
6140 (>= temporary-goal-column
6141 (- (window-width) hscroll-margin)))))
6142 (prog1 (line-move-visual arg noerror)
6143 ;; If we moved into a tall line, set vscroll to make
6144 ;; scrolling through tall images more smooth.
6145 (let ((lh (line-pixel-height))
6146 (edges (window-inside-pixel-edges))
6147 (dlh (default-line-height))
6148 winh)
6149 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6150 (if (and (< arg 0)
6151 (< (point) (window-start))
6152 (> lh winh))
6153 (set-window-vscroll
6155 (- lh dlh) t))))
6156 (line-move-1 arg noerror)))))
6158 ;; Display-based alternative to line-move-1.
6159 ;; Arg says how many lines to move. The value is t if we can move the
6160 ;; specified number of lines.
6161 (defun line-move-visual (arg &optional noerror)
6162 "Move ARG lines forward.
6163 If NOERROR, don't signal an error if we can't move that many lines."
6164 (let ((opoint (point))
6165 (hscroll (window-hscroll))
6166 target-hscroll)
6167 ;; Check if the previous command was a line-motion command, or if
6168 ;; we were called from some other command.
6169 (if (and (consp temporary-goal-column)
6170 (memq last-command `(next-line previous-line ,this-command)))
6171 ;; If so, there's no need to reset `temporary-goal-column',
6172 ;; but we may need to hscroll.
6173 (if (or (/= (cdr temporary-goal-column) hscroll)
6174 (> (cdr temporary-goal-column) 0))
6175 (setq target-hscroll (cdr temporary-goal-column)))
6176 ;; Otherwise, we should reset `temporary-goal-column'.
6177 (let ((posn (posn-at-point))
6178 x-pos)
6179 (cond
6180 ;; Handle the `overflow-newline-into-fringe' case:
6181 ((eq (nth 1 posn) 'right-fringe)
6182 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
6183 ((car (posn-x-y posn))
6184 (setq x-pos (car (posn-x-y posn)))
6185 ;; In R2L lines, the X pixel coordinate is measured from the
6186 ;; left edge of the window, but columns are still counted
6187 ;; from the logical-order beginning of the line, i.e. from
6188 ;; the right edge in this case. We need to adjust for that.
6189 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6190 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6191 (setq temporary-goal-column
6192 (cons (/ (float x-pos)
6193 (frame-char-width))
6194 hscroll)))
6195 (executing-kbd-macro
6196 ;; When we move beyond the first/last character visible in
6197 ;; the window, posn-at-point will return nil, so we need to
6198 ;; approximate the goal column as below.
6199 (setq temporary-goal-column
6200 (mod (current-column) (window-text-width)))))))
6201 (if target-hscroll
6202 (set-window-hscroll (selected-window) target-hscroll))
6203 ;; vertical-motion can move more than it was asked to if it moves
6204 ;; across display strings with newlines. We don't want to ring
6205 ;; the bell and announce beginning/end of buffer in that case.
6206 (or (and (or (and (>= arg 0)
6207 (>= (vertical-motion
6208 (cons (or goal-column
6209 (if (consp temporary-goal-column)
6210 (car temporary-goal-column)
6211 temporary-goal-column))
6212 arg))
6213 arg))
6214 (and (< arg 0)
6215 (<= (vertical-motion
6216 (cons (or goal-column
6217 (if (consp temporary-goal-column)
6218 (car temporary-goal-column)
6219 temporary-goal-column))
6220 arg))
6221 arg)))
6222 (or (>= arg 0)
6223 (/= (point) opoint)
6224 ;; If the goal column lies on a display string,
6225 ;; `vertical-motion' advances the cursor to the end
6226 ;; of the string. For arg < 0, this can cause the
6227 ;; cursor to get stuck. (Bug#3020).
6228 (= (vertical-motion arg) arg)))
6229 (unless noerror
6230 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6231 nil)))))
6233 ;; This is the guts of next-line and previous-line.
6234 ;; Arg says how many lines to move.
6235 ;; The value is t if we can move the specified number of lines.
6236 (defun line-move-1 (arg &optional noerror _to-end)
6237 ;; Don't run any point-motion hooks, and disregard intangibility,
6238 ;; for intermediate positions.
6239 (let ((inhibit-point-motion-hooks t)
6240 (opoint (point))
6241 (orig-arg arg))
6242 (if (consp temporary-goal-column)
6243 (setq temporary-goal-column (+ (car temporary-goal-column)
6244 (cdr temporary-goal-column))))
6245 (unwind-protect
6246 (progn
6247 (if (not (memq last-command '(next-line previous-line)))
6248 (setq temporary-goal-column
6249 (if (and track-eol (eolp)
6250 ;; Don't count beg of empty line as end of line
6251 ;; unless we just did explicit end-of-line.
6252 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6253 most-positive-fixnum
6254 (current-column))))
6256 (if (not (or (integerp selective-display)
6257 line-move-ignore-invisible))
6258 ;; Use just newline characters.
6259 ;; Set ARG to 0 if we move as many lines as requested.
6260 (or (if (> arg 0)
6261 (progn (if (> arg 1) (forward-line (1- arg)))
6262 ;; This way of moving forward ARG lines
6263 ;; verifies that we have a newline after the last one.
6264 ;; It doesn't get confused by intangible text.
6265 (end-of-line)
6266 (if (zerop (forward-line 1))
6267 (setq arg 0)))
6268 (and (zerop (forward-line arg))
6269 (bolp)
6270 (setq arg 0)))
6271 (unless noerror
6272 (signal (if (< arg 0)
6273 'beginning-of-buffer
6274 'end-of-buffer)
6275 nil)))
6276 ;; Move by arg lines, but ignore invisible ones.
6277 (let (done)
6278 (while (and (> arg 0) (not done))
6279 ;; If the following character is currently invisible,
6280 ;; skip all characters with that same `invisible' property value.
6281 (while (and (not (eobp)) (invisible-p (point)))
6282 (goto-char (next-char-property-change (point))))
6283 ;; Move a line.
6284 ;; We don't use `end-of-line', since we want to escape
6285 ;; from field boundaries occurring exactly at point.
6286 (goto-char (constrain-to-field
6287 (let ((inhibit-field-text-motion t))
6288 (line-end-position))
6289 (point) t t
6290 'inhibit-line-move-field-capture))
6291 ;; If there's no invisibility here, move over the newline.
6292 (cond
6293 ((eobp)
6294 (if (not noerror)
6295 (signal 'end-of-buffer nil)
6296 (setq done t)))
6297 ((and (> arg 1) ;; Use vertical-motion for last move
6298 (not (integerp selective-display))
6299 (not (invisible-p (point))))
6300 ;; We avoid vertical-motion when possible
6301 ;; because that has to fontify.
6302 (forward-line 1))
6303 ;; Otherwise move a more sophisticated way.
6304 ((zerop (vertical-motion 1))
6305 (if (not noerror)
6306 (signal 'end-of-buffer nil)
6307 (setq done t))))
6308 (unless done
6309 (setq arg (1- arg))))
6310 ;; The logic of this is the same as the loop above,
6311 ;; it just goes in the other direction.
6312 (while (and (< arg 0) (not done))
6313 ;; For completely consistency with the forward-motion
6314 ;; case, we should call beginning-of-line here.
6315 ;; However, if point is inside a field and on a
6316 ;; continued line, the call to (vertical-motion -1)
6317 ;; below won't move us back far enough; then we return
6318 ;; to the same column in line-move-finish, and point
6319 ;; gets stuck -- cyd
6320 (forward-line 0)
6321 (cond
6322 ((bobp)
6323 (if (not noerror)
6324 (signal 'beginning-of-buffer nil)
6325 (setq done t)))
6326 ((and (< arg -1) ;; Use vertical-motion for last move
6327 (not (integerp selective-display))
6328 (not (invisible-p (1- (point)))))
6329 (forward-line -1))
6330 ((zerop (vertical-motion -1))
6331 (if (not noerror)
6332 (signal 'beginning-of-buffer nil)
6333 (setq done t))))
6334 (unless done
6335 (setq arg (1+ arg))
6336 (while (and ;; Don't move over previous invis lines
6337 ;; if our target is the middle of this line.
6338 (or (zerop (or goal-column temporary-goal-column))
6339 (< arg 0))
6340 (not (bobp)) (invisible-p (1- (point))))
6341 (goto-char (previous-char-property-change (point))))))))
6342 ;; This is the value the function returns.
6343 (= arg 0))
6345 (cond ((> arg 0)
6346 ;; If we did not move down as far as desired, at least go
6347 ;; to end of line. Be sure to call point-entered and
6348 ;; point-left-hooks.
6349 (let* ((npoint (prog1 (line-end-position)
6350 (goto-char opoint)))
6351 (inhibit-point-motion-hooks nil))
6352 (goto-char npoint)))
6353 ((< arg 0)
6354 ;; If we did not move up as far as desired,
6355 ;; at least go to beginning of line.
6356 (let* ((npoint (prog1 (line-beginning-position)
6357 (goto-char opoint)))
6358 (inhibit-point-motion-hooks nil))
6359 (goto-char npoint)))
6361 (line-move-finish (or goal-column temporary-goal-column)
6362 opoint (> orig-arg 0)))))))
6364 (defun line-move-finish (column opoint forward)
6365 (let ((repeat t))
6366 (while repeat
6367 ;; Set REPEAT to t to repeat the whole thing.
6368 (setq repeat nil)
6370 (let (new
6371 (old (point))
6372 (line-beg (line-beginning-position))
6373 (line-end
6374 ;; Compute the end of the line
6375 ;; ignoring effectively invisible newlines.
6376 (save-excursion
6377 ;; Like end-of-line but ignores fields.
6378 (skip-chars-forward "^\n")
6379 (while (and (not (eobp)) (invisible-p (point)))
6380 (goto-char (next-char-property-change (point)))
6381 (skip-chars-forward "^\n"))
6382 (point))))
6384 ;; Move to the desired column.
6385 (line-move-to-column (truncate column))
6387 ;; Corner case: suppose we start out in a field boundary in
6388 ;; the middle of a continued line. When we get to
6389 ;; line-move-finish, point is at the start of a new *screen*
6390 ;; line but the same text line; then line-move-to-column would
6391 ;; move us backwards. Test using C-n with point on the "x" in
6392 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6393 (and forward
6394 (< (point) old)
6395 (goto-char old))
6397 (setq new (point))
6399 ;; Process intangibility within a line.
6400 ;; With inhibit-point-motion-hooks bound to nil, a call to
6401 ;; goto-char moves point past intangible text.
6403 ;; However, inhibit-point-motion-hooks controls both the
6404 ;; intangibility and the point-entered/point-left hooks. The
6405 ;; following hack avoids calling the point-* hooks
6406 ;; unnecessarily. Note that we move *forward* past intangible
6407 ;; text when the initial and final points are the same.
6408 (goto-char new)
6409 (let ((inhibit-point-motion-hooks nil))
6410 (goto-char new)
6412 ;; If intangibility moves us to a different (later) place
6413 ;; in the same line, use that as the destination.
6414 (if (<= (point) line-end)
6415 (setq new (point))
6416 ;; If that position is "too late",
6417 ;; try the previous allowable position.
6418 ;; See if it is ok.
6419 (backward-char)
6420 (if (if forward
6421 ;; If going forward, don't accept the previous
6422 ;; allowable position if it is before the target line.
6423 (< line-beg (point))
6424 ;; If going backward, don't accept the previous
6425 ;; allowable position if it is still after the target line.
6426 (<= (point) line-end))
6427 (setq new (point))
6428 ;; As a last resort, use the end of the line.
6429 (setq new line-end))))
6431 ;; Now move to the updated destination, processing fields
6432 ;; as well as intangibility.
6433 (goto-char opoint)
6434 (let ((inhibit-point-motion-hooks nil))
6435 (goto-char
6436 ;; Ignore field boundaries if the initial and final
6437 ;; positions have the same `field' property, even if the
6438 ;; fields are non-contiguous. This seems to be "nicer"
6439 ;; behavior in many situations.
6440 (if (eq (get-char-property new 'field)
6441 (get-char-property opoint 'field))
6443 (constrain-to-field new opoint t t
6444 'inhibit-line-move-field-capture))))
6446 ;; If all this moved us to a different line,
6447 ;; retry everything within that new line.
6448 (when (or (< (point) line-beg) (> (point) line-end))
6449 ;; Repeat the intangibility and field processing.
6450 (setq repeat t))))))
6452 (defun line-move-to-column (col)
6453 "Try to find column COL, considering invisibility.
6454 This function works only in certain cases,
6455 because what we really need is for `move-to-column'
6456 and `current-column' to be able to ignore invisible text."
6457 (if (zerop col)
6458 (beginning-of-line)
6459 (move-to-column col))
6461 (when (and line-move-ignore-invisible
6462 (not (bolp)) (invisible-p (1- (point))))
6463 (let ((normal-location (point))
6464 (normal-column (current-column)))
6465 ;; If the following character is currently invisible,
6466 ;; skip all characters with that same `invisible' property value.
6467 (while (and (not (eobp))
6468 (invisible-p (point)))
6469 (goto-char (next-char-property-change (point))))
6470 ;; Have we advanced to a larger column position?
6471 (if (> (current-column) normal-column)
6472 ;; We have made some progress towards the desired column.
6473 ;; See if we can make any further progress.
6474 (line-move-to-column (+ (current-column) (- col normal-column)))
6475 ;; Otherwise, go to the place we originally found
6476 ;; and move back over invisible text.
6477 ;; that will get us to the same place on the screen
6478 ;; but with a more reasonable buffer position.
6479 (goto-char normal-location)
6480 (let ((line-beg
6481 ;; We want the real line beginning, so it's consistent
6482 ;; with bolp below, otherwise we might infloop.
6483 (let ((inhibit-field-text-motion t))
6484 (line-beginning-position))))
6485 (while (and (not (bolp)) (invisible-p (1- (point))))
6486 (goto-char (previous-char-property-change (point) line-beg))))))))
6488 (defun move-end-of-line (arg)
6489 "Move point to end of current line as displayed.
6490 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6491 If point reaches the beginning or end of buffer, it stops there.
6493 To ignore the effects of the `intangible' text or overlay
6494 property, bind `inhibit-point-motion-hooks' to t.
6495 If there is an image in the current line, this function
6496 disregards newlines that are part of the text on which the image
6497 rests."
6498 (interactive "^p")
6499 (or arg (setq arg 1))
6500 (let (done)
6501 (while (not done)
6502 (let ((newpos
6503 (save-excursion
6504 (let ((goal-column 0)
6505 (line-move-visual nil))
6506 (and (line-move arg t)
6507 ;; With bidi reordering, we may not be at bol,
6508 ;; so make sure we are.
6509 (skip-chars-backward "^\n")
6510 (not (bobp))
6511 (progn
6512 (while (and (not (bobp)) (invisible-p (1- (point))))
6513 (goto-char (previous-single-char-property-change
6514 (point) 'invisible)))
6515 (backward-char 1)))
6516 (point)))))
6517 (goto-char newpos)
6518 (if (and (> (point) newpos)
6519 (eq (preceding-char) ?\n))
6520 (backward-char 1)
6521 (if (and (> (point) newpos) (not (eobp))
6522 (not (eq (following-char) ?\n)))
6523 ;; If we skipped something intangible and now we're not
6524 ;; really at eol, keep going.
6525 (setq arg 1)
6526 (setq done t)))))))
6528 (defun move-beginning-of-line (arg)
6529 "Move point to beginning of current line as displayed.
6530 \(If there's an image in the line, this disregards newlines
6531 which are part of the text that the image rests on.)
6533 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6534 If point reaches the beginning or end of buffer, it stops there.
6535 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6536 (interactive "^p")
6537 (or arg (setq arg 1))
6539 (let ((orig (point))
6540 first-vis first-vis-field-value)
6542 ;; Move by lines, if ARG is not 1 (the default).
6543 (if (/= arg 1)
6544 (let ((line-move-visual nil))
6545 (line-move (1- arg) t)))
6547 ;; Move to beginning-of-line, ignoring fields and invisible text.
6548 (skip-chars-backward "^\n")
6549 (while (and (not (bobp)) (invisible-p (1- (point))))
6550 (goto-char (previous-char-property-change (point)))
6551 (skip-chars-backward "^\n"))
6553 ;; Now find first visible char in the line.
6554 (while (and (< (point) orig) (invisible-p (point)))
6555 (goto-char (next-char-property-change (point) orig)))
6556 (setq first-vis (point))
6558 ;; See if fields would stop us from reaching FIRST-VIS.
6559 (setq first-vis-field-value
6560 (constrain-to-field first-vis orig (/= arg 1) t nil))
6562 (goto-char (if (/= first-vis-field-value first-vis)
6563 ;; If yes, obey them.
6564 first-vis-field-value
6565 ;; Otherwise, move to START with attention to fields.
6566 ;; (It is possible that fields never matter in this case.)
6567 (constrain-to-field (point) orig
6568 (/= arg 1) t nil)))))
6571 ;; Many people have said they rarely use this feature, and often type
6572 ;; it by accident. Maybe it shouldn't even be on a key.
6573 (put 'set-goal-column 'disabled t)
6575 (defun set-goal-column (arg)
6576 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6577 Those commands will move to this position in the line moved to
6578 rather than trying to keep the same horizontal position.
6579 With a non-nil argument ARG, clears out the goal column
6580 so that \\[next-line] and \\[previous-line] resume vertical motion.
6581 The goal column is stored in the variable `goal-column'.
6582 This is a buffer-local setting."
6583 (interactive "P")
6584 (if arg
6585 (progn
6586 (setq goal-column nil)
6587 (message "No goal column"))
6588 (setq goal-column (current-column))
6589 ;; The older method below can be erroneous if `set-goal-column' is bound
6590 ;; to a sequence containing %
6591 ;;(message (substitute-command-keys
6592 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6593 ;;goal-column)
6594 (message "%s"
6595 (concat
6596 (format "Goal column %d " goal-column)
6597 (substitute-command-keys
6598 "(use \\[set-goal-column] with an arg to unset it)")))
6601 nil)
6603 ;;; Editing based on visual lines, as opposed to logical lines.
6605 (defun end-of-visual-line (&optional n)
6606 "Move point to end of current visual line.
6607 With argument N not nil or 1, move forward N - 1 visual lines first.
6608 If point reaches the beginning or end of buffer, it stops there.
6609 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6610 (interactive "^p")
6611 (or n (setq n 1))
6612 (if (/= n 1)
6613 (let ((line-move-visual t))
6614 (line-move (1- n) t)))
6615 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6616 ;; constrain to field boundaries, so we don't either.
6617 (vertical-motion (cons (window-width) 0)))
6619 (defun beginning-of-visual-line (&optional n)
6620 "Move point to beginning of current visual line.
6621 With argument N not nil or 1, move forward N - 1 visual lines first.
6622 If point reaches the beginning or end of buffer, it stops there.
6623 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6624 (interactive "^p")
6625 (or n (setq n 1))
6626 (let ((opoint (point)))
6627 (if (/= n 1)
6628 (let ((line-move-visual t))
6629 (line-move (1- n) t)))
6630 (vertical-motion 0)
6631 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6632 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6634 (defun kill-visual-line (&optional arg)
6635 "Kill the rest of the visual line.
6636 With prefix argument ARG, kill that many visual lines from point.
6637 If ARG is negative, kill visual lines backward.
6638 If ARG is zero, kill the text before point on the current visual
6639 line.
6641 If you want to append the killed line to the last killed text,
6642 use \\[append-next-kill] before \\[kill-line].
6644 If the buffer is read-only, Emacs will beep and refrain from deleting
6645 the line, but put the line in the kill ring anyway. This means that
6646 you can use this command to copy text from a read-only buffer.
6647 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6648 even beep.)"
6649 (interactive "P")
6650 ;; Like in `kill-line', it's better to move point to the other end
6651 ;; of the kill before killing.
6652 (let ((opoint (point))
6653 (kill-whole-line (and kill-whole-line (bolp))))
6654 (if arg
6655 (vertical-motion (prefix-numeric-value arg))
6656 (end-of-visual-line 1)
6657 (if (= (point) opoint)
6658 (vertical-motion 1)
6659 ;; Skip any trailing whitespace at the end of the visual line.
6660 ;; We used to do this only if `show-trailing-whitespace' is
6661 ;; nil, but that's wrong; the correct thing would be to check
6662 ;; whether the trailing whitespace is highlighted. But, it's
6663 ;; OK to just do this unconditionally.
6664 (skip-chars-forward " \t")))
6665 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
6666 (1+ (point))
6667 (point)))))
6669 (defun next-logical-line (&optional arg try-vscroll)
6670 "Move cursor vertically down ARG lines.
6671 This is identical to `next-line', except that it always moves
6672 by logical lines instead of visual lines, ignoring the value of
6673 the variable `line-move-visual'."
6674 (interactive "^p\np")
6675 (let ((line-move-visual nil))
6676 (with-no-warnings
6677 (next-line arg try-vscroll))))
6679 (defun previous-logical-line (&optional arg try-vscroll)
6680 "Move cursor vertically up ARG lines.
6681 This is identical to `previous-line', except that it always moves
6682 by logical lines instead of visual lines, ignoring the value of
6683 the variable `line-move-visual'."
6684 (interactive "^p\np")
6685 (let ((line-move-visual nil))
6686 (with-no-warnings
6687 (previous-line arg try-vscroll))))
6689 (defgroup visual-line nil
6690 "Editing based on visual lines."
6691 :group 'convenience
6692 :version "23.1")
6694 (defvar visual-line-mode-map
6695 (let ((map (make-sparse-keymap)))
6696 (define-key map [remap kill-line] 'kill-visual-line)
6697 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6698 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6699 ;; These keybindings interfere with xterm function keys. Are
6700 ;; there any other suitable bindings?
6701 ;; (define-key map "\M-[" 'previous-logical-line)
6702 ;; (define-key map "\M-]" 'next-logical-line)
6703 map))
6705 (defcustom visual-line-fringe-indicators '(nil nil)
6706 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6707 The value should be a list of the form (LEFT RIGHT), where LEFT
6708 and RIGHT are symbols representing the bitmaps to display, to
6709 indicate wrapped lines, in the left and right fringes respectively.
6710 See also `fringe-indicator-alist'.
6711 The default is not to display fringe indicators for wrapped lines.
6712 This variable does not affect fringe indicators displayed for
6713 other purposes."
6714 :type '(list (choice (const :tag "Hide left indicator" nil)
6715 (const :tag "Left curly arrow" left-curly-arrow)
6716 (symbol :tag "Other bitmap"))
6717 (choice (const :tag "Hide right indicator" nil)
6718 (const :tag "Right curly arrow" right-curly-arrow)
6719 (symbol :tag "Other bitmap")))
6720 :set (lambda (symbol value)
6721 (dolist (buf (buffer-list))
6722 (with-current-buffer buf
6723 (when (and (boundp 'visual-line-mode)
6724 (symbol-value 'visual-line-mode))
6725 (setq fringe-indicator-alist
6726 (cons (cons 'continuation value)
6727 (assq-delete-all
6728 'continuation
6729 (copy-tree fringe-indicator-alist)))))))
6730 (set-default symbol value)))
6732 (defvar visual-line--saved-state nil)
6734 (define-minor-mode visual-line-mode
6735 "Toggle visual line based editing (Visual Line mode).
6736 With a prefix argument ARG, enable Visual Line mode if ARG is
6737 positive, and disable it otherwise. If called from Lisp, enable
6738 the mode if ARG is omitted or nil.
6740 When Visual Line mode is enabled, `word-wrap' is turned on in
6741 this buffer, and simple editing commands are redefined to act on
6742 visual lines, not logical lines. See Info node `Visual Line
6743 Mode' for details."
6744 :keymap visual-line-mode-map
6745 :group 'visual-line
6746 :lighter " Wrap"
6747 (if visual-line-mode
6748 (progn
6749 (set (make-local-variable 'visual-line--saved-state) nil)
6750 ;; Save the local values of some variables, to be restored if
6751 ;; visual-line-mode is turned off.
6752 (dolist (var '(line-move-visual truncate-lines
6753 truncate-partial-width-windows
6754 word-wrap fringe-indicator-alist))
6755 (if (local-variable-p var)
6756 (push (cons var (symbol-value var))
6757 visual-line--saved-state)))
6758 (set (make-local-variable 'line-move-visual) t)
6759 (set (make-local-variable 'truncate-partial-width-windows) nil)
6760 (setq truncate-lines nil
6761 word-wrap t
6762 fringe-indicator-alist
6763 (cons (cons 'continuation visual-line-fringe-indicators)
6764 fringe-indicator-alist)))
6765 (kill-local-variable 'line-move-visual)
6766 (kill-local-variable 'word-wrap)
6767 (kill-local-variable 'truncate-lines)
6768 (kill-local-variable 'truncate-partial-width-windows)
6769 (kill-local-variable 'fringe-indicator-alist)
6770 (dolist (saved visual-line--saved-state)
6771 (set (make-local-variable (car saved)) (cdr saved)))
6772 (kill-local-variable 'visual-line--saved-state)))
6774 (defun turn-on-visual-line-mode ()
6775 (visual-line-mode 1))
6777 (define-globalized-minor-mode global-visual-line-mode
6778 visual-line-mode turn-on-visual-line-mode)
6781 (defun transpose-chars (arg)
6782 "Interchange characters around point, moving forward one character.
6783 With prefix arg ARG, effect is to take character before point
6784 and drag it forward past ARG other characters (backward if ARG negative).
6785 If no argument and at end of line, the previous two chars are exchanged."
6786 (interactive "*P")
6787 (when (and (null arg) (eolp) (not (bobp))
6788 (not (get-text-property (1- (point)) 'read-only)))
6789 (forward-char -1))
6790 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6792 (defun transpose-words (arg)
6793 "Interchange words around point, leaving point at end of them.
6794 With prefix arg ARG, effect is to take word before or around point
6795 and drag it forward past ARG other words (backward if ARG negative).
6796 If ARG is zero, the words around or after point and around or after mark
6797 are interchanged."
6798 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6799 (interactive "*p")
6800 (transpose-subr 'forward-word arg))
6802 (defun transpose-sexps (arg)
6803 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6804 Unlike `transpose-words', point must be between the two sexps and not
6805 in the middle of a sexp to be transposed.
6806 With non-zero prefix arg ARG, effect is to take the sexp before point
6807 and drag it forward past ARG other sexps (backward if ARG is negative).
6808 If ARG is zero, the sexps ending at or after point and at or after mark
6809 are interchanged."
6810 (interactive "*p")
6811 (transpose-subr
6812 (lambda (arg)
6813 ;; Here we should try to simulate the behavior of
6814 ;; (cons (progn (forward-sexp x) (point))
6815 ;; (progn (forward-sexp (- x)) (point)))
6816 ;; Except that we don't want to rely on the second forward-sexp
6817 ;; putting us back to where we want to be, since forward-sexp-function
6818 ;; might do funny things like infix-precedence.
6819 (if (if (> arg 0)
6820 (looking-at "\\sw\\|\\s_")
6821 (and (not (bobp))
6822 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6823 ;; Jumping over a symbol. We might be inside it, mind you.
6824 (progn (funcall (if (> arg 0)
6825 'skip-syntax-backward 'skip-syntax-forward)
6826 "w_")
6827 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6828 ;; Otherwise, we're between sexps. Take a step back before jumping
6829 ;; to make sure we'll obey the same precedence no matter which direction
6830 ;; we're going.
6831 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6832 (cons (save-excursion (forward-sexp arg) (point))
6833 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6834 (not (zerop (funcall (if (> arg 0)
6835 'skip-syntax-forward
6836 'skip-syntax-backward)
6837 ".")))))
6838 (point)))))
6839 arg 'special))
6841 (defun transpose-lines (arg)
6842 "Exchange current line and previous line, leaving point after both.
6843 With argument ARG, takes previous line and moves it past ARG lines.
6844 With argument 0, interchanges line point is in with line mark is in."
6845 (interactive "*p")
6846 (transpose-subr (function
6847 (lambda (arg)
6848 (if (> arg 0)
6849 (progn
6850 ;; Move forward over ARG lines,
6851 ;; but create newlines if necessary.
6852 (setq arg (forward-line arg))
6853 (if (/= (preceding-char) ?\n)
6854 (setq arg (1+ arg)))
6855 (if (> arg 0)
6856 (newline arg)))
6857 (forward-line arg))))
6858 arg))
6860 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6861 ;; which seems inconsistent with the ARG /= 0 case.
6862 ;; FIXME document SPECIAL.
6863 (defun transpose-subr (mover arg &optional special)
6864 "Subroutine to do the work of transposing objects.
6865 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6866 moves forward by units of the given object (e.g. forward-sentence,
6867 forward-paragraph). If ARG is zero, exchanges the current object
6868 with the one containing mark. If ARG is an integer, moves the
6869 current object past ARG following (if ARG is positive) or
6870 preceding (if ARG is negative) objects, leaving point after the
6871 current object."
6872 (let ((aux (if special mover
6873 (lambda (x)
6874 (cons (progn (funcall mover x) (point))
6875 (progn (funcall mover (- x)) (point))))))
6876 pos1 pos2)
6877 (cond
6878 ((= arg 0)
6879 (save-excursion
6880 (setq pos1 (funcall aux 1))
6881 (goto-char (or (mark) (error "No mark set in this buffer")))
6882 (setq pos2 (funcall aux 1))
6883 (transpose-subr-1 pos1 pos2))
6884 (exchange-point-and-mark))
6885 ((> arg 0)
6886 (setq pos1 (funcall aux -1))
6887 (setq pos2 (funcall aux arg))
6888 (transpose-subr-1 pos1 pos2)
6889 (goto-char (car pos2)))
6891 (setq pos1 (funcall aux -1))
6892 (goto-char (car pos1))
6893 (setq pos2 (funcall aux arg))
6894 (transpose-subr-1 pos1 pos2)
6895 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6897 (defun transpose-subr-1 (pos1 pos2)
6898 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6899 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6900 (when (> (car pos1) (car pos2))
6901 (let ((swap pos1))
6902 (setq pos1 pos2 pos2 swap)))
6903 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6904 (atomic-change-group
6905 ;; This sequence of insertions attempts to preserve marker
6906 ;; positions at the start and end of the transposed objects.
6907 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6908 (len1 (- (cdr pos1) (car pos1)))
6909 (len2 (length word))
6910 (boundary (make-marker)))
6911 (set-marker boundary (car pos2))
6912 (goto-char (cdr pos1))
6913 (insert-before-markers word)
6914 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6915 (goto-char boundary)
6916 (insert word)
6917 (goto-char (+ boundary len1))
6918 (delete-region (point) (+ (point) len2))
6919 (set-marker boundary nil))))
6921 (defun backward-word (&optional arg)
6922 "Move backward until encountering the beginning of a word.
6923 With argument ARG, do this that many times.
6924 If ARG is omitted or nil, move point backward one word.
6926 The word boundaries are normally determined by the buffer's syntax
6927 table, but `find-word-boundary-function-table', such as set up
6928 by `subword-mode', can change that. If a Lisp program needs to
6929 move by words determined strictly by the syntax table, it should
6930 use `backward-word-strictly' instead."
6931 (interactive "^p")
6932 (forward-word (- (or arg 1))))
6934 (defun mark-word (&optional arg allow-extend)
6935 "Set mark ARG words away from point.
6936 The place mark goes is the same place \\[forward-word] would
6937 move to with the same argument.
6938 Interactively, if this command is repeated
6939 or (in Transient Mark mode) if the mark is active,
6940 it marks the next ARG words after the ones already marked."
6941 (interactive "P\np")
6942 (cond ((and allow-extend
6943 (or (and (eq last-command this-command) (mark t))
6944 (region-active-p)))
6945 (setq arg (if arg (prefix-numeric-value arg)
6946 (if (< (mark) (point)) -1 1)))
6947 (set-mark
6948 (save-excursion
6949 (goto-char (mark))
6950 (forward-word arg)
6951 (point))))
6953 (push-mark
6954 (save-excursion
6955 (forward-word (prefix-numeric-value arg))
6956 (point))
6957 nil t))))
6959 (defun kill-word (arg)
6960 "Kill characters forward until encountering the end of a word.
6961 With argument ARG, do this that many times."
6962 (interactive "p")
6963 (kill-region (point) (progn (forward-word arg) (point))))
6965 (defun backward-kill-word (arg)
6966 "Kill characters backward until encountering the beginning of a word.
6967 With argument ARG, do this that many times."
6968 (interactive "p")
6969 (kill-word (- arg)))
6971 (defun current-word (&optional strict really-word)
6972 "Return the word at or near point, as a string.
6973 The return value includes no text properties.
6975 If optional arg STRICT is non-nil, return nil unless point is
6976 within or adjacent to a word, otherwise look for a word within
6977 point's line. If there is no word anywhere on point's line, the
6978 value is nil regardless of STRICT.
6980 By default, this function treats as a single word any sequence of
6981 characters that have either word or symbol syntax. If optional
6982 arg REALLY-WORD is non-nil, only characters of word syntax can
6983 constitute a word."
6984 (save-excursion
6985 (let* ((oldpoint (point)) (start (point)) (end (point))
6986 (syntaxes (if really-word "w" "w_"))
6987 (not-syntaxes (concat "^" syntaxes)))
6988 (skip-syntax-backward syntaxes) (setq start (point))
6989 (goto-char oldpoint)
6990 (skip-syntax-forward syntaxes) (setq end (point))
6991 (when (and (eq start oldpoint) (eq end oldpoint)
6992 ;; Point is neither within nor adjacent to a word.
6993 (not strict))
6994 ;; Look for preceding word in same line.
6995 (skip-syntax-backward not-syntaxes (line-beginning-position))
6996 (if (bolp)
6997 ;; No preceding word in same line.
6998 ;; Look for following word in same line.
6999 (progn
7000 (skip-syntax-forward not-syntaxes (line-end-position))
7001 (setq start (point))
7002 (skip-syntax-forward syntaxes)
7003 (setq end (point)))
7004 (setq end (point))
7005 (skip-syntax-backward syntaxes)
7006 (setq start (point))))
7007 ;; If we found something nonempty, return it as a string.
7008 (unless (= start end)
7009 (buffer-substring-no-properties start end)))))
7011 (defcustom fill-prefix nil
7012 "String for filling to insert at front of new line, or nil for none."
7013 :type '(choice (const :tag "None" nil)
7014 string)
7015 :group 'fill)
7016 (make-variable-buffer-local 'fill-prefix)
7017 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
7019 (defcustom auto-fill-inhibit-regexp nil
7020 "Regexp to match lines which should not be auto-filled."
7021 :type '(choice (const :tag "None" nil)
7022 regexp)
7023 :group 'fill)
7025 (defun do-auto-fill ()
7026 "The default value for `normal-auto-fill-function'.
7027 This is the default auto-fill function, some major modes use a different one.
7028 Returns t if it really did any work."
7029 (let (fc justify give-up
7030 (fill-prefix fill-prefix))
7031 (if (or (not (setq justify (current-justification)))
7032 (null (setq fc (current-fill-column)))
7033 (and (eq justify 'left)
7034 (<= (current-column) fc))
7035 (and auto-fill-inhibit-regexp
7036 (save-excursion (beginning-of-line)
7037 (looking-at auto-fill-inhibit-regexp))))
7038 nil ;; Auto-filling not required
7039 (if (memq justify '(full center right))
7040 (save-excursion (unjustify-current-line)))
7042 ;; Choose a fill-prefix automatically.
7043 (when (and adaptive-fill-mode
7044 (or (null fill-prefix) (string= fill-prefix "")))
7045 (let ((prefix
7046 (fill-context-prefix
7047 (save-excursion (fill-forward-paragraph -1) (point))
7048 (save-excursion (fill-forward-paragraph 1) (point)))))
7049 (and prefix (not (equal prefix ""))
7050 ;; Use auto-indentation rather than a guessed empty prefix.
7051 (not (and fill-indent-according-to-mode
7052 (string-match "\\`[ \t]*\\'" prefix)))
7053 (setq fill-prefix prefix))))
7055 (while (and (not give-up) (> (current-column) fc))
7056 ;; Determine where to split the line.
7057 (let* (after-prefix
7058 (fill-point
7059 (save-excursion
7060 (beginning-of-line)
7061 (setq after-prefix (point))
7062 (and fill-prefix
7063 (looking-at (regexp-quote fill-prefix))
7064 (setq after-prefix (match-end 0)))
7065 (move-to-column (1+ fc))
7066 (fill-move-to-break-point after-prefix)
7067 (point))))
7069 ;; See whether the place we found is any good.
7070 (if (save-excursion
7071 (goto-char fill-point)
7072 (or (bolp)
7073 ;; There is no use breaking at end of line.
7074 (save-excursion (skip-chars-forward " ") (eolp))
7075 ;; It is futile to split at the end of the prefix
7076 ;; since we would just insert the prefix again.
7077 (and after-prefix (<= (point) after-prefix))
7078 ;; Don't split right after a comment starter
7079 ;; since we would just make another comment starter.
7080 (and comment-start-skip
7081 (let ((limit (point)))
7082 (beginning-of-line)
7083 (and (re-search-forward comment-start-skip
7084 limit t)
7085 (eq (point) limit))))))
7086 ;; No good place to break => stop trying.
7087 (setq give-up t)
7088 ;; Ok, we have a useful place to break the line. Do it.
7089 (let ((prev-column (current-column)))
7090 ;; If point is at the fill-point, do not `save-excursion'.
7091 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7092 ;; point will end up before it rather than after it.
7093 (if (save-excursion
7094 (skip-chars-backward " \t")
7095 (= (point) fill-point))
7096 (default-indent-new-line t)
7097 (save-excursion
7098 (goto-char fill-point)
7099 (default-indent-new-line t)))
7100 ;; Now do justification, if required
7101 (if (not (eq justify 'left))
7102 (save-excursion
7103 (end-of-line 0)
7104 (justify-current-line justify nil t)))
7105 ;; If making the new line didn't reduce the hpos of
7106 ;; the end of the line, then give up now;
7107 ;; trying again will not help.
7108 (if (>= (current-column) prev-column)
7109 (setq give-up t))))))
7110 ;; Justify last line.
7111 (justify-current-line justify t t)
7112 t)))
7114 (defvar comment-line-break-function 'comment-indent-new-line
7115 "Mode-specific function which line breaks and continues a comment.
7116 This function is called during auto-filling when a comment syntax
7117 is defined.
7118 The function should take a single optional argument, which is a flag
7119 indicating whether it should use soft newlines.")
7121 (defun default-indent-new-line (&optional soft)
7122 "Break line at point and indent.
7123 If a comment syntax is defined, call `comment-indent-new-line'.
7125 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7126 unless optional argument SOFT is non-nil."
7127 (interactive)
7128 (if comment-start
7129 (funcall comment-line-break-function soft)
7130 ;; Insert the newline before removing empty space so that markers
7131 ;; get preserved better.
7132 (if soft (insert-and-inherit ?\n) (newline 1))
7133 (save-excursion (forward-char -1) (delete-horizontal-space))
7134 (delete-horizontal-space)
7136 (if (and fill-prefix (not adaptive-fill-mode))
7137 ;; Blindly trust a non-adaptive fill-prefix.
7138 (progn
7139 (indent-to-left-margin)
7140 (insert-before-markers-and-inherit fill-prefix))
7142 (cond
7143 ;; If there's an adaptive prefix, use it unless we're inside
7144 ;; a comment and the prefix is not a comment starter.
7145 (fill-prefix
7146 (indent-to-left-margin)
7147 (insert-and-inherit fill-prefix))
7148 ;; If we're not inside a comment, just try to indent.
7149 (t (indent-according-to-mode))))))
7151 (defvar normal-auto-fill-function 'do-auto-fill
7152 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7153 Some major modes set this.")
7155 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7156 ;; `functions' and `hooks' are usually unsafe to set, but setting
7157 ;; auto-fill-function to nil in a file-local setting is safe and
7158 ;; can be useful to prevent auto-filling.
7159 (put 'auto-fill-function 'safe-local-variable 'null)
7161 (define-minor-mode auto-fill-mode
7162 "Toggle automatic line breaking (Auto Fill mode).
7163 With a prefix argument ARG, enable Auto Fill mode if ARG is
7164 positive, and disable it otherwise. If called from Lisp, enable
7165 the mode if ARG is omitted or nil.
7167 When Auto Fill mode is enabled, inserting a space at a column
7168 beyond `current-fill-column' automatically breaks the line at a
7169 previous space.
7171 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7172 non-nil.
7174 The value of `normal-auto-fill-function' specifies the function to use
7175 for `auto-fill-function' when turning Auto Fill mode on."
7176 :variable (auto-fill-function
7177 . (lambda (v) (setq auto-fill-function
7178 (if v normal-auto-fill-function)))))
7180 ;; This holds a document string used to document auto-fill-mode.
7181 (defun auto-fill-function ()
7182 "Automatically break line at a previous space, in insertion of text."
7183 nil)
7185 (defun turn-on-auto-fill ()
7186 "Unconditionally turn on Auto Fill mode."
7187 (auto-fill-mode 1))
7189 (defun turn-off-auto-fill ()
7190 "Unconditionally turn off Auto Fill mode."
7191 (auto-fill-mode -1))
7193 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7195 (defun set-fill-column (arg)
7196 "Set `fill-column' to specified argument.
7197 Use \\[universal-argument] followed by a number to specify a column.
7198 Just \\[universal-argument] as argument means to use the current column."
7199 (interactive
7200 (list (or current-prefix-arg
7201 ;; We used to use current-column silently, but C-x f is too easily
7202 ;; typed as a typo for C-x C-f, so we turned it into an error and
7203 ;; now an interactive prompt.
7204 (read-number "Set fill-column to: " (current-column)))))
7205 (if (consp arg)
7206 (setq arg (current-column)))
7207 (if (not (integerp arg))
7208 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7209 (error "set-fill-column requires an explicit argument")
7210 (message "Fill column set to %d (was %d)" arg fill-column)
7211 (setq fill-column arg)))
7213 (defun set-selective-display (arg)
7214 "Set `selective-display' to ARG; clear it if no arg.
7215 When the value of `selective-display' is a number > 0,
7216 lines whose indentation is >= that value are not displayed.
7217 The variable `selective-display' has a separate value for each buffer."
7218 (interactive "P")
7219 (if (eq selective-display t)
7220 (error "selective-display already in use for marked lines"))
7221 (let ((current-vpos
7222 (save-restriction
7223 (narrow-to-region (point-min) (point))
7224 (goto-char (window-start))
7225 (vertical-motion (window-height)))))
7226 (setq selective-display
7227 (and arg (prefix-numeric-value arg)))
7228 (recenter current-vpos))
7229 (set-window-start (selected-window) (window-start))
7230 (princ "selective-display set to " t)
7231 (prin1 selective-display t)
7232 (princ "." t))
7234 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7236 (defun toggle-truncate-lines (&optional arg)
7237 "Toggle truncating of long lines for the current buffer.
7238 When truncating is off, long lines are folded.
7239 With prefix argument ARG, truncate long lines if ARG is positive,
7240 otherwise fold them. Note that in side-by-side windows, this
7241 command has no effect if `truncate-partial-width-windows' is
7242 non-nil."
7243 (interactive "P")
7244 (setq truncate-lines
7245 (if (null arg)
7246 (not truncate-lines)
7247 (> (prefix-numeric-value arg) 0)))
7248 (force-mode-line-update)
7249 (unless truncate-lines
7250 (let ((buffer (current-buffer)))
7251 (walk-windows (lambda (window)
7252 (if (eq buffer (window-buffer window))
7253 (set-window-hscroll window 0)))
7254 nil t)))
7255 (message "Truncate long lines %s"
7256 (if truncate-lines "enabled" "disabled")))
7258 (defun toggle-word-wrap (&optional arg)
7259 "Toggle whether to use word-wrapping for continuation lines.
7260 With prefix argument ARG, wrap continuation lines at word boundaries
7261 if ARG is positive, otherwise wrap them at the right screen edge.
7262 This command toggles the value of `word-wrap'. It has no effect
7263 if long lines are truncated."
7264 (interactive "P")
7265 (setq word-wrap
7266 (if (null arg)
7267 (not word-wrap)
7268 (> (prefix-numeric-value arg) 0)))
7269 (force-mode-line-update)
7270 (message "Word wrapping %s"
7271 (if word-wrap "enabled" "disabled")))
7273 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7274 "The string displayed in the mode line when in overwrite mode.")
7275 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7276 "The string displayed in the mode line when in binary overwrite mode.")
7278 (define-minor-mode overwrite-mode
7279 "Toggle Overwrite mode.
7280 With a prefix argument ARG, enable Overwrite mode if ARG is
7281 positive, and disable it otherwise. If called from Lisp, enable
7282 the mode if ARG is omitted or nil.
7284 When Overwrite mode is enabled, printing characters typed in
7285 replace existing text on a one-for-one basis, rather than pushing
7286 it to the right. At the end of a line, such characters extend
7287 the line. Before a tab, such characters insert until the tab is
7288 filled in. \\[quoted-insert] still inserts characters in
7289 overwrite mode; this is supposed to make it easier to insert
7290 characters when necessary."
7291 :variable (overwrite-mode
7292 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7294 (define-minor-mode binary-overwrite-mode
7295 "Toggle Binary Overwrite mode.
7296 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7297 is positive, and disable it otherwise. If called from Lisp,
7298 enable the mode if ARG is omitted or nil.
7300 When Binary Overwrite mode is enabled, printing characters typed
7301 in replace existing text. Newlines are not treated specially, so
7302 typing at the end of a line joins the line to the next, with the
7303 typed character between them. Typing before a tab character
7304 simply replaces the tab with the character typed.
7305 \\[quoted-insert] replaces the text at the cursor, just as
7306 ordinary typing characters do.
7308 Note that Binary Overwrite mode is not its own minor mode; it is
7309 a specialization of overwrite mode, entered by setting the
7310 `overwrite-mode' variable to `overwrite-mode-binary'."
7311 :variable (overwrite-mode
7312 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7314 (define-minor-mode line-number-mode
7315 "Toggle line number display in the mode line (Line Number mode).
7316 With a prefix argument ARG, enable Line Number mode if ARG is
7317 positive, and disable it otherwise. If called from Lisp, enable
7318 the mode if ARG is omitted or nil.
7320 Line numbers do not appear for very large buffers and buffers
7321 with very long lines; see variables `line-number-display-limit'
7322 and `line-number-display-limit-width'."
7323 :init-value t :global t :group 'mode-line)
7325 (define-minor-mode column-number-mode
7326 "Toggle column number display in the mode line (Column Number mode).
7327 With a prefix argument ARG, enable Column Number mode if ARG is
7328 positive, and disable it otherwise.
7330 If called from Lisp, enable the mode if ARG is omitted or nil."
7331 :global t :group 'mode-line)
7333 (define-minor-mode size-indication-mode
7334 "Toggle buffer size display in the mode line (Size Indication mode).
7335 With a prefix argument ARG, enable Size Indication mode if ARG is
7336 positive, and disable it otherwise.
7338 If called from Lisp, enable the mode if ARG is omitted or nil."
7339 :global t :group 'mode-line)
7341 (define-minor-mode auto-save-mode
7342 "Toggle auto-saving in the current buffer (Auto Save mode).
7343 With a prefix argument ARG, enable Auto Save mode if ARG is
7344 positive, and disable it otherwise.
7346 If called from Lisp, enable the mode if ARG is omitted or nil."
7347 :variable ((and buffer-auto-save-file-name
7348 ;; If auto-save is off because buffer has shrunk,
7349 ;; then toggling should turn it on.
7350 (>= buffer-saved-size 0))
7351 . (lambda (val)
7352 (setq buffer-auto-save-file-name
7353 (cond
7354 ((null val) nil)
7355 ((and buffer-file-name auto-save-visited-file-name
7356 (not buffer-read-only))
7357 buffer-file-name)
7358 (t (make-auto-save-file-name))))))
7359 ;; If -1 was stored here, to temporarily turn off saving,
7360 ;; turn it back on.
7361 (and (< buffer-saved-size 0)
7362 (setq buffer-saved-size 0)))
7364 (defgroup paren-blinking nil
7365 "Blinking matching of parens and expressions."
7366 :prefix "blink-matching-"
7367 :group 'paren-matching)
7369 (defcustom blink-matching-paren t
7370 "Non-nil means show matching open-paren when close-paren is inserted.
7371 If t, highlight the paren. If `jump', briefly move cursor to its
7372 position. If `jump-offscreen', move cursor there even if the
7373 position is off screen. With any other non-nil value, the
7374 off-screen position of the opening paren will be shown in the
7375 echo area."
7376 :type '(choice
7377 (const :tag "Disable" nil)
7378 (const :tag "Highlight" t)
7379 (const :tag "Move cursor" jump)
7380 (const :tag "Move cursor, even if off screen" jump-offscreen))
7381 :group 'paren-blinking)
7383 (defcustom blink-matching-paren-on-screen t
7384 "Non-nil means show matching open-paren when it is on screen.
7385 If nil, don't show it (but the open-paren can still be shown
7386 in the echo area when it is off screen).
7388 This variable has no effect if `blink-matching-paren' is nil.
7389 \(In that case, the open-paren is never shown.)
7390 It is also ignored if `show-paren-mode' is enabled."
7391 :type 'boolean
7392 :group 'paren-blinking)
7394 (defcustom blink-matching-paren-distance (* 100 1024)
7395 "If non-nil, maximum distance to search backwards for matching open-paren.
7396 If nil, search stops at the beginning of the accessible portion of the buffer."
7397 :version "23.2" ; 25->100k
7398 :type '(choice (const nil) integer)
7399 :group 'paren-blinking)
7401 (defcustom blink-matching-delay 1
7402 "Time in seconds to delay after showing a matching paren."
7403 :type 'number
7404 :group 'paren-blinking)
7406 (defcustom blink-matching-paren-dont-ignore-comments nil
7407 "If nil, `blink-matching-paren' ignores comments.
7408 More precisely, when looking for the matching parenthesis,
7409 it skips the contents of comments that end before point."
7410 :type 'boolean
7411 :group 'paren-blinking)
7413 (defun blink-matching-check-mismatch (start end)
7414 "Return whether or not START...END are matching parens.
7415 END is the current point and START is the blink position.
7416 START might be nil if no matching starter was found.
7417 Returns non-nil if we find there is a mismatch."
7418 (let* ((end-syntax (syntax-after (1- end)))
7419 (matching-paren (and (consp end-syntax)
7420 (eq (syntax-class end-syntax) 5)
7421 (cdr end-syntax))))
7422 ;; For self-matched chars like " and $, we can't know when they're
7423 ;; mismatched or unmatched, so we can only do it for parens.
7424 (when matching-paren
7425 (not (and start
7427 (eq (char-after start) matching-paren)
7428 ;; The cdr might hold a new paren-class info rather than
7429 ;; a matching-char info, in which case the two CDRs
7430 ;; should match.
7431 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7433 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7434 "Function to check parentheses mismatches.
7435 The function takes two arguments (START and END) where START is the
7436 position just before the opening token and END is the position right after.
7437 START can be nil, if it was not found.
7438 The function should return non-nil if the two tokens do not match.")
7440 (defvar blink-matching--overlay
7441 (let ((ol (make-overlay (point) (point) nil t)))
7442 (overlay-put ol 'face 'show-paren-match)
7443 (delete-overlay ol)
7445 "Overlay used to highlight the matching paren.")
7447 (defun blink-matching-open ()
7448 "Momentarily highlight the beginning of the sexp before point."
7449 (interactive)
7450 (when (and (not (bobp))
7451 blink-matching-paren)
7452 (let* ((oldpos (point))
7453 (message-log-max nil) ; Don't log messages about paren matching.
7454 (blinkpos
7455 (save-excursion
7456 (save-restriction
7457 (if blink-matching-paren-distance
7458 (narrow-to-region
7459 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7460 (- (point) blink-matching-paren-distance))
7461 oldpos))
7462 (let ((parse-sexp-ignore-comments
7463 (and parse-sexp-ignore-comments
7464 (not blink-matching-paren-dont-ignore-comments))))
7465 (condition-case ()
7466 (progn
7467 (syntax-propertize (point))
7468 (forward-sexp -1)
7469 ;; backward-sexp skips backward over prefix chars,
7470 ;; so move back to the matching paren.
7471 (while (and (< (point) (1- oldpos))
7472 (let ((code (syntax-after (point))))
7473 (or (eq (syntax-class code) 6)
7474 (eq (logand 1048576 (car code))
7475 1048576))))
7476 (forward-char 1))
7477 (point))
7478 (error nil))))))
7479 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7480 (cond
7481 (mismatch
7482 (if blinkpos
7483 (if (minibufferp)
7484 (minibuffer-message "Mismatched parentheses")
7485 (message "Mismatched parentheses"))
7486 (if (minibufferp)
7487 (minibuffer-message "No matching parenthesis found")
7488 (message "No matching parenthesis found"))))
7489 ((not blinkpos) nil)
7490 ((or
7491 (eq blink-matching-paren 'jump-offscreen)
7492 (pos-visible-in-window-p blinkpos))
7493 ;; Matching open within window, temporarily move to or highlight
7494 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7495 ;; is non-nil.
7496 (and blink-matching-paren-on-screen
7497 (not show-paren-mode)
7498 (if (memq blink-matching-paren '(jump jump-offscreen))
7499 (save-excursion
7500 (goto-char blinkpos)
7501 (sit-for blink-matching-delay))
7502 (unwind-protect
7503 (progn
7504 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7505 (current-buffer))
7506 (sit-for blink-matching-delay))
7507 (delete-overlay blink-matching--overlay)))))
7509 (let ((open-paren-line-string
7510 (save-excursion
7511 (goto-char blinkpos)
7512 ;; Show what precedes the open in its line, if anything.
7513 (cond
7514 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7515 (buffer-substring (line-beginning-position)
7516 (1+ blinkpos)))
7517 ;; Show what follows the open in its line, if anything.
7518 ((save-excursion
7519 (forward-char 1)
7520 (skip-chars-forward " \t")
7521 (not (eolp)))
7522 (buffer-substring blinkpos
7523 (line-end-position)))
7524 ;; Otherwise show the previous nonblank line,
7525 ;; if there is one.
7526 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7527 (concat
7528 (buffer-substring (progn
7529 (skip-chars-backward "\n \t")
7530 (line-beginning-position))
7531 (progn (end-of-line)
7532 (skip-chars-backward " \t")
7533 (point)))
7534 ;; Replace the newline and other whitespace with `...'.
7535 "..."
7536 (buffer-substring blinkpos (1+ blinkpos))))
7537 ;; There is nothing to show except the char itself.
7538 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7539 (minibuffer-message
7540 "Matches %s"
7541 (substring-no-properties open-paren-line-string))))))))
7543 (defvar blink-paren-function 'blink-matching-open
7544 "Function called, if non-nil, whenever a close parenthesis is inserted.
7545 More precisely, a char with closeparen syntax is self-inserted.")
7547 (defun blink-paren-post-self-insert-function ()
7548 (when (and (eq (char-before) last-command-event) ; Sanity check.
7549 (memq (char-syntax last-command-event) '(?\) ?\$))
7550 blink-paren-function
7551 (not executing-kbd-macro)
7552 (not noninteractive)
7553 ;; Verify an even number of quoting characters precede the close.
7554 ;; FIXME: Also check if this parenthesis closes a comment as
7555 ;; can happen in Pascal and SML.
7556 (= 1 (logand 1 (- (point)
7557 (save-excursion
7558 (forward-char -1)
7559 (skip-syntax-backward "/\\")
7560 (point))))))
7561 (funcall blink-paren-function)))
7563 (put 'blink-paren-post-self-insert-function 'priority 100)
7565 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7566 ;; Most likely, this hook is nil, so this arg doesn't matter,
7567 ;; but I use it as a reminder that this function usually
7568 ;; likes to be run after others since it does
7569 ;; `sit-for'. That's also the reason it get a `priority' prop
7570 ;; of 100.
7571 'append)
7573 ;; This executes C-g typed while Emacs is waiting for a command.
7574 ;; Quitting out of a program does not go through here;
7575 ;; that happens in the maybe_quit function at the C code level.
7576 (defun keyboard-quit ()
7577 "Signal a `quit' condition.
7578 During execution of Lisp code, this character causes a quit directly.
7579 At top-level, as an editor command, this simply beeps."
7580 (interactive)
7581 ;; Avoid adding the region to the window selection.
7582 (setq saved-region-selection nil)
7583 (let (select-active-regions)
7584 (deactivate-mark))
7585 (if (fboundp 'kmacro-keyboard-quit)
7586 (kmacro-keyboard-quit))
7587 (when completion-in-region-mode
7588 (completion-in-region-mode -1))
7589 ;; Force the next redisplay cycle to remove the "Def" indicator from
7590 ;; all the mode lines.
7591 (if defining-kbd-macro
7592 (force-mode-line-update t))
7593 (setq defining-kbd-macro nil)
7594 (let ((debug-on-quit nil))
7595 (signal 'quit nil)))
7597 (defvar buffer-quit-function nil
7598 "Function to call to \"quit\" the current buffer, or nil if none.
7599 \\[keyboard-escape-quit] calls this function when its more local actions
7600 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7602 (defun keyboard-escape-quit ()
7603 "Exit the current \"mode\" (in a generalized sense of the word).
7604 This command can exit an interactive command such as `query-replace',
7605 can clear out a prefix argument or a region,
7606 can get out of the minibuffer or other recursive edit,
7607 cancel the use of the current buffer (for special-purpose buffers),
7608 or go back to just one window (by deleting all but the selected window)."
7609 (interactive)
7610 (cond ((eq last-command 'mode-exited) nil)
7611 ((region-active-p)
7612 (deactivate-mark))
7613 ((> (minibuffer-depth) 0)
7614 (abort-recursive-edit))
7615 (current-prefix-arg
7616 nil)
7617 ((> (recursion-depth) 0)
7618 (exit-recursive-edit))
7619 (buffer-quit-function
7620 (funcall buffer-quit-function))
7621 ((not (one-window-p t))
7622 (delete-other-windows))
7623 ((string-match "^ \\*" (buffer-name (current-buffer)))
7624 (bury-buffer))))
7626 (defun play-sound-file (file &optional volume device)
7627 "Play sound stored in FILE.
7628 VOLUME and DEVICE correspond to the keywords of the sound
7629 specification for `play-sound'."
7630 (interactive "fPlay sound file: ")
7631 (let ((sound (list :file file)))
7632 (if volume
7633 (plist-put sound :volume volume))
7634 (if device
7635 (plist-put sound :device device))
7636 (push 'sound sound)
7637 (play-sound sound)))
7640 (defcustom read-mail-command 'rmail
7641 "Your preference for a mail reading package.
7642 This is used by some keybindings which support reading mail.
7643 See also `mail-user-agent' concerning sending mail."
7644 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7645 (function-item :tag "Gnus" :format "%t\n" gnus)
7646 (function-item :tag "Emacs interface to MH"
7647 :format "%t\n" mh-rmail)
7648 (function :tag "Other"))
7649 :version "21.1"
7650 :group 'mail)
7652 (defcustom mail-user-agent 'message-user-agent
7653 "Your preference for a mail composition package.
7654 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7655 outgoing email message. This variable lets you specify which
7656 mail-sending package you prefer.
7658 Valid values include:
7660 `message-user-agent' -- use the Message package.
7661 See Info node `(message)'.
7662 `sendmail-user-agent' -- use the Mail package.
7663 See Info node `(emacs)Sending Mail'.
7664 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7665 See Info node `(mh-e)'.
7666 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7667 paraphernalia if Gnus is running, particularly
7668 the Gcc: header for archiving.
7670 Additional valid symbols may be available; check with the author of
7671 your package for details. The function should return non-nil if it
7672 succeeds.
7674 See also `read-mail-command' concerning reading mail."
7675 :type '(radio (function-item :tag "Message package"
7676 :format "%t\n"
7677 message-user-agent)
7678 (function-item :tag "Mail package"
7679 :format "%t\n"
7680 sendmail-user-agent)
7681 (function-item :tag "Emacs interface to MH"
7682 :format "%t\n"
7683 mh-e-user-agent)
7684 (function-item :tag "Message with full Gnus features"
7685 :format "%t\n"
7686 gnus-user-agent)
7687 (function :tag "Other"))
7688 :version "23.2" ; sendmail->message
7689 :group 'mail)
7691 (defcustom compose-mail-user-agent-warnings t
7692 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7693 If the value of `mail-user-agent' is the default, and the user
7694 appears to have customizations applying to the old default,
7695 `compose-mail' issues a warning."
7696 :type 'boolean
7697 :version "23.2"
7698 :group 'mail)
7700 (defun rfc822-goto-eoh ()
7701 "If the buffer starts with a mail header, move point to the header's end.
7702 Otherwise, moves to `point-min'.
7703 The end of the header is the start of the next line, if there is one,
7704 else the end of the last line. This function obeys RFC822."
7705 (goto-char (point-min))
7706 (when (re-search-forward
7707 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7708 (goto-char (match-beginning 0))))
7710 ;; Used by Rmail (e.g., rmail-forward).
7711 (defvar mail-encode-mml nil
7712 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7713 the outgoing message before sending it.")
7715 (defun compose-mail (&optional to subject other-headers continue
7716 switch-function yank-action send-actions
7717 return-action)
7718 "Start composing a mail message to send.
7719 This uses the user's chosen mail composition package
7720 as selected with the variable `mail-user-agent'.
7721 The optional arguments TO and SUBJECT specify recipients
7722 and the initial Subject field, respectively.
7724 OTHER-HEADERS is an alist specifying additional
7725 header fields. Elements look like (HEADER . VALUE) where both
7726 HEADER and VALUE are strings.
7728 CONTINUE, if non-nil, says to continue editing a message already
7729 being composed. Interactively, CONTINUE is the prefix argument.
7731 SWITCH-FUNCTION, if non-nil, is a function to use to
7732 switch to and display the buffer used for mail composition.
7734 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7735 to insert the raw text of the message being replied to.
7736 It has the form (FUNCTION . ARGS). The user agent will apply
7737 FUNCTION to ARGS, to insert the raw text of the original message.
7738 \(The user agent will also run `mail-citation-hook', *after* the
7739 original text has been inserted in this way.)
7741 SEND-ACTIONS is a list of actions to call when the message is sent.
7742 Each action has the form (FUNCTION . ARGS).
7744 RETURN-ACTION, if non-nil, is an action for returning to the
7745 caller. It has the form (FUNCTION . ARGS). The function is
7746 called after the mail has been sent or put aside, and the mail
7747 buffer buried."
7748 (interactive
7749 (list nil nil nil current-prefix-arg))
7751 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7752 ;; from sendmail-user-agent to message-user-agent. Some users may
7753 ;; encounter incompatibilities. This hack tries to detect problems
7754 ;; and warn about them.
7755 (and compose-mail-user-agent-warnings
7756 (eq mail-user-agent 'message-user-agent)
7757 (let (warn-vars)
7758 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7759 mail-yank-hooks mail-archive-file-name
7760 mail-default-reply-to mail-mailing-lists
7761 mail-self-blind))
7762 (and (boundp var)
7763 (symbol-value var)
7764 (push var warn-vars)))
7765 (when warn-vars
7766 (display-warning 'mail
7767 (format-message "\
7768 The default mail mode is now Message mode.
7769 You have the following Mail mode variable%s customized:
7770 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7771 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7772 (if (> (length warn-vars) 1) "s" "")
7773 (mapconcat 'symbol-name
7774 warn-vars " "))))))
7776 (let ((function (get mail-user-agent 'composefunc)))
7777 (funcall function to subject other-headers continue switch-function
7778 yank-action send-actions return-action)))
7780 (defun compose-mail-other-window (&optional to subject other-headers continue
7781 yank-action send-actions
7782 return-action)
7783 "Like \\[compose-mail], but edit the outgoing message in another window."
7784 (interactive (list nil nil nil current-prefix-arg))
7785 (compose-mail to subject other-headers continue
7786 'switch-to-buffer-other-window yank-action send-actions
7787 return-action))
7789 (defun compose-mail-other-frame (&optional to subject other-headers continue
7790 yank-action send-actions
7791 return-action)
7792 "Like \\[compose-mail], but edit the outgoing message in another frame."
7793 (interactive (list nil nil nil current-prefix-arg))
7794 (compose-mail to subject other-headers continue
7795 'switch-to-buffer-other-frame yank-action send-actions
7796 return-action))
7799 (defvar set-variable-value-history nil
7800 "History of values entered with `set-variable'.
7802 Maximum length of the history list is determined by the value
7803 of `history-length', which see.")
7805 (defun set-variable (variable value &optional make-local)
7806 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7807 VARIABLE should be a user option variable name, a Lisp variable
7808 meant to be customized by users. You should enter VALUE in Lisp syntax,
7809 so if you want VALUE to be a string, you must surround it with doublequotes.
7810 VALUE is used literally, not evaluated.
7812 If VARIABLE has a `variable-interactive' property, that is used as if
7813 it were the arg to `interactive' (which see) to interactively read VALUE.
7815 If VARIABLE has been defined with `defcustom', then the type information
7816 in the definition is used to check that VALUE is valid.
7818 Note that this function is at heart equivalent to the basic `set' function.
7819 For a variable defined with `defcustom', it does not pay attention to
7820 any :set property that the variable might have (if you want that, use
7821 \\[customize-set-variable] instead).
7823 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7824 (interactive
7825 (let* ((default-var (variable-at-point))
7826 (var (if (custom-variable-p default-var)
7827 (read-variable (format "Set variable (default %s): " default-var)
7828 default-var)
7829 (read-variable "Set variable: ")))
7830 (minibuffer-help-form '(describe-variable var))
7831 (prop (get var 'variable-interactive))
7832 (obsolete (car (get var 'byte-obsolete-variable)))
7833 (prompt (format "Set %s %s to value: " var
7834 (cond ((local-variable-p var)
7835 "(buffer-local)")
7836 ((or current-prefix-arg
7837 (local-variable-if-set-p var))
7838 "buffer-locally")
7839 (t "globally"))))
7840 (val (progn
7841 (when obsolete
7842 (message (concat "`%S' is obsolete; "
7843 (if (symbolp obsolete) "use `%S' instead" "%s"))
7844 var obsolete)
7845 (sit-for 3))
7846 (if prop
7847 ;; Use VAR's `variable-interactive' property
7848 ;; as an interactive spec for prompting.
7849 (call-interactively `(lambda (arg)
7850 (interactive ,prop)
7851 arg))
7852 (read-from-minibuffer prompt nil
7853 read-expression-map t
7854 'set-variable-value-history
7855 (format "%S" (symbol-value var)))))))
7856 (list var val current-prefix-arg)))
7858 (and (custom-variable-p variable)
7859 (not (get variable 'custom-type))
7860 (custom-load-symbol variable))
7861 (let ((type (get variable 'custom-type)))
7862 (when type
7863 ;; Match with custom type.
7864 (require 'cus-edit)
7865 (setq type (widget-convert type))
7866 (unless (widget-apply type :match value)
7867 (user-error "Value `%S' does not match type %S of %S"
7868 value (car type) variable))))
7870 (if make-local
7871 (make-local-variable variable))
7873 (set variable value)
7875 ;; Force a thorough redisplay for the case that the variable
7876 ;; has an effect on the display, like `tab-width' has.
7877 (force-mode-line-update))
7879 ;; Define the major mode for lists of completions.
7881 (defvar completion-list-mode-map
7882 (let ((map (make-sparse-keymap)))
7883 (define-key map [mouse-2] 'choose-completion)
7884 (define-key map [follow-link] 'mouse-face)
7885 (define-key map [down-mouse-2] nil)
7886 (define-key map "\C-m" 'choose-completion)
7887 (define-key map "\e\e\e" 'delete-completion-window)
7888 (define-key map [left] 'previous-completion)
7889 (define-key map [right] 'next-completion)
7890 (define-key map [?\t] 'next-completion)
7891 (define-key map [backtab] 'previous-completion)
7892 (define-key map "q" 'quit-window)
7893 (define-key map "z" 'kill-this-buffer)
7894 map)
7895 "Local map for completion list buffers.")
7897 ;; Completion mode is suitable only for specially formatted data.
7898 (put 'completion-list-mode 'mode-class 'special)
7900 (defvar completion-reference-buffer nil
7901 "Record the buffer that was current when the completion list was requested.
7902 This is a local variable in the completion list buffer.
7903 Initial value is nil to avoid some compiler warnings.")
7905 (defvar completion-no-auto-exit nil
7906 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7907 This also applies to other functions such as `choose-completion'.")
7909 (defvar completion-base-position nil
7910 "Position of the base of the text corresponding to the shown completions.
7911 This variable is used in the *Completions* buffers.
7912 Its value is a list of the form (START END) where START is the place
7913 where the completion should be inserted and END (if non-nil) is the end
7914 of the text to replace. If END is nil, point is used instead.")
7916 (defvar completion-list-insert-choice-function #'completion--replace
7917 "Function to use to insert the text chosen in *Completions*.
7918 Called with three arguments (BEG END TEXT), it should replace the text
7919 between BEG and END with TEXT. Expected to be set buffer-locally
7920 in the *Completions* buffer.")
7922 (defvar completion-base-size nil
7923 "Number of chars before point not involved in completion.
7924 This is a local variable in the completion list buffer.
7925 It refers to the chars in the minibuffer if completing in the
7926 minibuffer, or in `completion-reference-buffer' otherwise.
7927 Only characters in the field at point are included.
7929 If nil, Emacs determines which part of the tail end of the
7930 buffer's text is involved in completion by comparing the text
7931 directly.")
7932 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7934 (defun delete-completion-window ()
7935 "Delete the completion list window.
7936 Go to the window from which completion was requested."
7937 (interactive)
7938 (let ((buf completion-reference-buffer))
7939 (if (one-window-p t)
7940 (if (window-dedicated-p) (delete-frame))
7941 (delete-window (selected-window))
7942 (if (get-buffer-window buf)
7943 (select-window (get-buffer-window buf))))))
7945 (defun previous-completion (n)
7946 "Move to the previous item in the completion list."
7947 (interactive "p")
7948 (next-completion (- n)))
7950 (defun next-completion (n)
7951 "Move to the next item in the completion list.
7952 With prefix argument N, move N items (negative N means move backward)."
7953 (interactive "p")
7954 (let ((beg (point-min)) (end (point-max)))
7955 (while (and (> n 0) (not (eobp)))
7956 ;; If in a completion, move to the end of it.
7957 (when (get-text-property (point) 'mouse-face)
7958 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7959 ;; Move to start of next one.
7960 (unless (get-text-property (point) 'mouse-face)
7961 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7962 (setq n (1- n)))
7963 (while (and (< n 0) (not (bobp)))
7964 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7965 ;; If in a completion, move to the start of it.
7966 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7967 (goto-char (previous-single-property-change
7968 (point) 'mouse-face nil beg)))
7969 ;; Move to end of the previous completion.
7970 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7971 (goto-char (previous-single-property-change
7972 (point) 'mouse-face nil beg)))
7973 ;; Move to the start of that one.
7974 (goto-char (previous-single-property-change
7975 (point) 'mouse-face nil beg))
7976 (setq n (1+ n))))))
7978 (defun choose-completion (&optional event)
7979 "Choose the completion at point.
7980 If EVENT, use EVENT's position to determine the starting position."
7981 (interactive (list last-nonmenu-event))
7982 ;; In case this is run via the mouse, give temporary modes such as
7983 ;; isearch a chance to turn off.
7984 (run-hooks 'mouse-leave-buffer-hook)
7985 (with-current-buffer (window-buffer (posn-window (event-start event)))
7986 (let ((buffer completion-reference-buffer)
7987 (base-size completion-base-size)
7988 (base-position completion-base-position)
7989 (insert-function completion-list-insert-choice-function)
7990 (choice
7991 (save-excursion
7992 (goto-char (posn-point (event-start event)))
7993 (let (beg end)
7994 (cond
7995 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7996 (setq end (point) beg (1+ (point))))
7997 ((and (not (bobp))
7998 (get-text-property (1- (point)) 'mouse-face))
7999 (setq end (1- (point)) beg (point)))
8000 (t (error "No completion here")))
8001 (setq beg (previous-single-property-change beg 'mouse-face))
8002 (setq end (or (next-single-property-change end 'mouse-face)
8003 (point-max)))
8004 (buffer-substring-no-properties beg end)))))
8006 (unless (buffer-live-p buffer)
8007 (error "Destination buffer is dead"))
8008 (quit-window nil (posn-window (event-start event)))
8010 (with-current-buffer buffer
8011 (choose-completion-string
8012 choice buffer
8013 (or base-position
8014 (when base-size
8015 ;; Someone's using old completion code that doesn't know
8016 ;; about base-position yet.
8017 (list (+ base-size (field-beginning))))
8018 ;; If all else fails, just guess.
8019 (list (choose-completion-guess-base-position choice)))
8020 insert-function)))))
8022 ;; Delete the longest partial match for STRING
8023 ;; that can be found before POINT.
8024 (defun choose-completion-guess-base-position (string)
8025 (save-excursion
8026 (let ((opoint (point))
8027 len)
8028 ;; Try moving back by the length of the string.
8029 (goto-char (max (- (point) (length string))
8030 (minibuffer-prompt-end)))
8031 ;; See how far back we were actually able to move. That is the
8032 ;; upper bound on how much we can match and delete.
8033 (setq len (- opoint (point)))
8034 (if completion-ignore-case
8035 (setq string (downcase string)))
8036 (while (and (> len 0)
8037 (let ((tail (buffer-substring (point) opoint)))
8038 (if completion-ignore-case
8039 (setq tail (downcase tail)))
8040 (not (string= tail (substring string 0 len)))))
8041 (setq len (1- len))
8042 (forward-char 1))
8043 (point))))
8045 (defun choose-completion-delete-max-match (string)
8046 (declare (obsolete choose-completion-guess-base-position "23.2"))
8047 (delete-region (choose-completion-guess-base-position string) (point)))
8049 (defvar choose-completion-string-functions nil
8050 "Functions that may override the normal insertion of a completion choice.
8051 These functions are called in order with three arguments:
8052 CHOICE - the string to insert in the buffer,
8053 BUFFER - the buffer in which the choice should be inserted,
8054 BASE-POSITION - where to insert the completion.
8056 If a function in the list returns non-nil, that function is supposed
8057 to have inserted the CHOICE in the BUFFER, and possibly exited
8058 the minibuffer; no further functions will be called.
8060 If all functions in the list return nil, that means to use
8061 the default method of inserting the completion in BUFFER.")
8063 (defun choose-completion-string (choice &optional
8064 buffer base-position insert-function)
8065 "Switch to BUFFER and insert the completion choice CHOICE.
8066 BASE-POSITION says where to insert the completion.
8067 INSERT-FUNCTION says how to insert the completion and falls
8068 back on `completion-list-insert-choice-function' when nil."
8070 ;; If BUFFER is the minibuffer, exit the minibuffer
8071 ;; unless it is reading a file name and CHOICE is a directory,
8072 ;; or completion-no-auto-exit is non-nil.
8074 ;; Some older code may call us passing `base-size' instead of
8075 ;; `base-position'. It's difficult to make any use of `base-size',
8076 ;; so we just ignore it.
8077 (unless (consp base-position)
8078 (message "Obsolete `base-size' passed to choose-completion-string")
8079 (setq base-position nil))
8081 (let* ((buffer (or buffer completion-reference-buffer))
8082 (mini-p (minibufferp buffer)))
8083 ;; If BUFFER is a minibuffer, barf unless it's the currently
8084 ;; active minibuffer.
8085 (if (and mini-p
8086 (not (and (active-minibuffer-window)
8087 (equal buffer
8088 (window-buffer (active-minibuffer-window))))))
8089 (error "Minibuffer is not active for completion")
8090 ;; Set buffer so buffer-local choose-completion-string-functions works.
8091 (set-buffer buffer)
8092 (unless (run-hook-with-args-until-success
8093 'choose-completion-string-functions
8094 ;; The fourth arg used to be `mini-p' but was useless
8095 ;; (since minibufferp can be used on the `buffer' arg)
8096 ;; and indeed unused. The last used to be `base-size', so we
8097 ;; keep it to try and avoid breaking old code.
8098 choice buffer base-position nil)
8099 ;; This remove-text-properties should be unnecessary since `choice'
8100 ;; comes from buffer-substring-no-properties.
8101 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8102 ;; Insert the completion into the buffer where it was requested.
8103 (funcall (or insert-function completion-list-insert-choice-function)
8104 (or (car base-position) (point))
8105 (or (cadr base-position) (point))
8106 choice)
8107 ;; Update point in the window that BUFFER is showing in.
8108 (let ((window (get-buffer-window buffer t)))
8109 (set-window-point window (point)))
8110 ;; If completing for the minibuffer, exit it with this choice.
8111 (and (not completion-no-auto-exit)
8112 (minibufferp buffer)
8113 minibuffer-completion-table
8114 ;; If this is reading a file name, and the file name chosen
8115 ;; is a directory, don't exit the minibuffer.
8116 (let* ((result (buffer-substring (field-beginning) (point)))
8117 (bounds
8118 (completion-boundaries result minibuffer-completion-table
8119 minibuffer-completion-predicate
8120 "")))
8121 (if (eq (car bounds) (length result))
8122 ;; The completion chosen leads to a new set of completions
8123 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8124 (let ((mini (active-minibuffer-window)))
8125 (select-window mini)
8126 (when minibuffer-auto-raise
8127 (raise-frame (window-frame mini))))
8128 (exit-minibuffer))))))))
8130 (define-derived-mode completion-list-mode nil "Completion List"
8131 "Major mode for buffers showing lists of possible completions.
8132 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8133 to select the completion near point.
8134 Or click to select one with the mouse.
8136 \\{completion-list-mode-map}"
8137 (set (make-local-variable 'completion-base-size) nil))
8139 (defun completion-list-mode-finish ()
8140 "Finish setup of the completions buffer.
8141 Called from `temp-buffer-show-hook'."
8142 (when (eq major-mode 'completion-list-mode)
8143 (setq buffer-read-only t)))
8145 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8148 ;; Variables and faces used in `completion-setup-function'.
8150 (defcustom completion-show-help t
8151 "Non-nil means show help message in *Completions* buffer."
8152 :type 'boolean
8153 :version "22.1"
8154 :group 'completion)
8156 ;; This function goes in completion-setup-hook, so that it is called
8157 ;; after the text of the completion list buffer is written.
8158 (defun completion-setup-function ()
8159 (let* ((mainbuf (current-buffer))
8160 (base-dir
8161 ;; FIXME: This is a bad hack. We try to set the default-directory
8162 ;; in the *Completions* buffer so that the relative file names
8163 ;; displayed there can be treated as valid file names, independently
8164 ;; from the completion context. But this suffers from many problems:
8165 ;; - It's not clear when the completions are file names. With some
8166 ;; completion tables (e.g. bzr revision specs), the listed
8167 ;; completions can mix file names and other things.
8168 ;; - It doesn't pay attention to possible quoting.
8169 ;; - With fancy completion styles, the code below will not always
8170 ;; find the right base directory.
8171 (if minibuffer-completing-file-name
8172 (file-name-as-directory
8173 (expand-file-name
8174 (buffer-substring (minibuffer-prompt-end)
8175 (- (point) (or completion-base-size 0))))))))
8176 (with-current-buffer standard-output
8177 (let ((base-size completion-base-size) ;Read before killing localvars.
8178 (base-position completion-base-position)
8179 (insert-fun completion-list-insert-choice-function))
8180 (completion-list-mode)
8181 (set (make-local-variable 'completion-base-size) base-size)
8182 (set (make-local-variable 'completion-base-position) base-position)
8183 (set (make-local-variable 'completion-list-insert-choice-function)
8184 insert-fun))
8185 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8186 (if base-dir (setq default-directory base-dir))
8187 ;; Maybe insert help string.
8188 (when completion-show-help
8189 (goto-char (point-min))
8190 (if (display-mouse-p)
8191 (insert "Click on a completion to select it.\n"))
8192 (insert (substitute-command-keys
8193 "In this buffer, type \\[choose-completion] to \
8194 select the completion near point.\n\n"))))))
8196 (add-hook 'completion-setup-hook 'completion-setup-function)
8198 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8199 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8201 (defun switch-to-completions ()
8202 "Select the completion list window."
8203 (interactive)
8204 (let ((window (or (get-buffer-window "*Completions*" 0)
8205 ;; Make sure we have a completions window.
8206 (progn (minibuffer-completion-help)
8207 (get-buffer-window "*Completions*" 0)))))
8208 (when window
8209 (select-window window)
8210 ;; In the new buffer, go to the first completion.
8211 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8212 (when (bobp)
8213 (next-completion 1)))))
8215 ;;; Support keyboard commands to turn on various modifiers.
8217 ;; These functions -- which are not commands -- each add one modifier
8218 ;; to the following event.
8220 (defun event-apply-alt-modifier (_ignore-prompt)
8221 "\\<function-key-map>Add the Alt modifier to the following event.
8222 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8223 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8224 (defun event-apply-super-modifier (_ignore-prompt)
8225 "\\<function-key-map>Add the Super modifier to the following event.
8226 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8227 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8228 (defun event-apply-hyper-modifier (_ignore-prompt)
8229 "\\<function-key-map>Add the Hyper modifier to the following event.
8230 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8231 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8232 (defun event-apply-shift-modifier (_ignore-prompt)
8233 "\\<function-key-map>Add the Shift modifier to the following event.
8234 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8235 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8236 (defun event-apply-control-modifier (_ignore-prompt)
8237 "\\<function-key-map>Add the Ctrl modifier to the following event.
8238 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8239 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8240 (defun event-apply-meta-modifier (_ignore-prompt)
8241 "\\<function-key-map>Add the Meta modifier to the following event.
8242 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8243 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8245 (defun event-apply-modifier (event symbol lshiftby prefix)
8246 "Apply a modifier flag to event EVENT.
8247 SYMBOL is the name of this modifier, as a symbol.
8248 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8249 PREFIX is the string that represents this modifier in an event type symbol."
8250 (if (numberp event)
8251 (cond ((eq symbol 'control)
8252 (if (and (<= (downcase event) ?z)
8253 (>= (downcase event) ?a))
8254 (- (downcase event) ?a -1)
8255 (if (and (<= (downcase event) ?Z)
8256 (>= (downcase event) ?A))
8257 (- (downcase event) ?A -1)
8258 (logior (lsh 1 lshiftby) event))))
8259 ((eq symbol 'shift)
8260 (if (and (<= (downcase event) ?z)
8261 (>= (downcase event) ?a))
8262 (upcase event)
8263 (logior (lsh 1 lshiftby) event)))
8265 (logior (lsh 1 lshiftby) event)))
8266 (if (memq symbol (event-modifiers event))
8267 event
8268 (let ((event-type (if (symbolp event) event (car event))))
8269 (setq event-type (intern (concat prefix (symbol-name event-type))))
8270 (if (symbolp event)
8271 event-type
8272 (cons event-type (cdr event)))))))
8274 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8275 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8276 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8277 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8278 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8279 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8281 ;;;; Keypad support.
8283 ;; Make the keypad keys act like ordinary typing keys. If people add
8284 ;; bindings for the function key symbols, then those bindings will
8285 ;; override these, so this shouldn't interfere with any existing
8286 ;; bindings.
8288 ;; Also tell read-char how to handle these keys.
8289 (mapc
8290 (lambda (keypad-normal)
8291 (let ((keypad (nth 0 keypad-normal))
8292 (normal (nth 1 keypad-normal)))
8293 (put keypad 'ascii-character normal)
8294 (define-key function-key-map (vector keypad) (vector normal))))
8295 ;; See also kp-keys bound in bindings.el.
8296 '((kp-space ?\s)
8297 (kp-tab ?\t)
8298 (kp-enter ?\r)
8299 (kp-separator ?,)
8300 (kp-equal ?=)
8301 ;; Do the same for various keys that are represented as symbols under
8302 ;; GUIs but naturally correspond to characters.
8303 (backspace 127)
8304 (delete 127)
8305 (tab ?\t)
8306 (linefeed ?\n)
8307 (clear ?\C-l)
8308 (return ?\C-m)
8309 (escape ?\e)
8312 ;;;;
8313 ;;;; forking a twin copy of a buffer.
8314 ;;;;
8316 (defvar clone-buffer-hook nil
8317 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8319 (defvar clone-indirect-buffer-hook nil
8320 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8322 (defun clone-process (process &optional newname)
8323 "Create a twin copy of PROCESS.
8324 If NEWNAME is nil, it defaults to PROCESS' name;
8325 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8326 If PROCESS is associated with a buffer, the new process will be associated
8327 with the current buffer instead.
8328 Returns nil if PROCESS has already terminated."
8329 (setq newname (or newname (process-name process)))
8330 (if (string-match "<[0-9]+>\\'" newname)
8331 (setq newname (substring newname 0 (match-beginning 0))))
8332 (when (memq (process-status process) '(run stop open))
8333 (let* ((process-connection-type (process-tty-name process))
8334 (new-process
8335 (if (memq (process-status process) '(open))
8336 (let ((args (process-contact process t)))
8337 (setq args (plist-put args :name newname))
8338 (setq args (plist-put args :buffer
8339 (if (process-buffer process)
8340 (current-buffer))))
8341 (apply 'make-network-process args))
8342 (apply 'start-process newname
8343 (if (process-buffer process) (current-buffer))
8344 (process-command process)))))
8345 (set-process-query-on-exit-flag
8346 new-process (process-query-on-exit-flag process))
8347 (set-process-inherit-coding-system-flag
8348 new-process (process-inherit-coding-system-flag process))
8349 (set-process-filter new-process (process-filter process))
8350 (set-process-sentinel new-process (process-sentinel process))
8351 (set-process-plist new-process (copy-sequence (process-plist process)))
8352 new-process)))
8354 ;; things to maybe add (currently partly covered by `funcall mode'):
8355 ;; - syntax-table
8356 ;; - overlays
8357 (defun clone-buffer (&optional newname display-flag)
8358 "Create and return a twin copy of the current buffer.
8359 Unlike an indirect buffer, the new buffer can be edited
8360 independently of the old one (if it is not read-only).
8361 NEWNAME is the name of the new buffer. It may be modified by
8362 adding or incrementing <N> at the end as necessary to create a
8363 unique buffer name. If nil, it defaults to the name of the
8364 current buffer, with the proper suffix. If DISPLAY-FLAG is
8365 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8366 clone a file-visiting buffer, or a buffer whose major mode symbol
8367 has a non-nil `no-clone' property, results in an error.
8369 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8370 current buffer with appropriate suffix. However, if a prefix
8371 argument is given, then the command prompts for NEWNAME in the
8372 minibuffer.
8374 This runs the normal hook `clone-buffer-hook' in the new buffer
8375 after it has been set up properly in other respects."
8376 (interactive
8377 (progn
8378 (if buffer-file-name
8379 (error "Cannot clone a file-visiting buffer"))
8380 (if (get major-mode 'no-clone)
8381 (error "Cannot clone a buffer in %s mode" mode-name))
8382 (list (if current-prefix-arg
8383 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8384 t)))
8385 (if buffer-file-name
8386 (error "Cannot clone a file-visiting buffer"))
8387 (if (get major-mode 'no-clone)
8388 (error "Cannot clone a buffer in %s mode" mode-name))
8389 (setq newname (or newname (buffer-name)))
8390 (if (string-match "<[0-9]+>\\'" newname)
8391 (setq newname (substring newname 0 (match-beginning 0))))
8392 (let ((buf (current-buffer))
8393 (ptmin (point-min))
8394 (ptmax (point-max))
8395 (pt (point))
8396 (mk (if mark-active (mark t)))
8397 (modified (buffer-modified-p))
8398 (mode major-mode)
8399 (lvars (buffer-local-variables))
8400 (process (get-buffer-process (current-buffer)))
8401 (new (generate-new-buffer (or newname (buffer-name)))))
8402 (save-restriction
8403 (widen)
8404 (with-current-buffer new
8405 (insert-buffer-substring buf)))
8406 (with-current-buffer new
8407 (narrow-to-region ptmin ptmax)
8408 (goto-char pt)
8409 (if mk (set-mark mk))
8410 (set-buffer-modified-p modified)
8412 ;; Clone the old buffer's process, if any.
8413 (when process (clone-process process))
8415 ;; Now set up the major mode.
8416 (funcall mode)
8418 ;; Set up other local variables.
8419 (mapc (lambda (v)
8420 (condition-case () ;in case var is read-only
8421 (if (symbolp v)
8422 (makunbound v)
8423 (set (make-local-variable (car v)) (cdr v)))
8424 (error nil)))
8425 lvars)
8427 ;; Run any hooks (typically set up by the major mode
8428 ;; for cloning to work properly).
8429 (run-hooks 'clone-buffer-hook))
8430 (if display-flag
8431 ;; Presumably the current buffer is shown in the selected frame, so
8432 ;; we want to display the clone elsewhere.
8433 (let ((same-window-regexps nil)
8434 (same-window-buffer-names))
8435 (pop-to-buffer new)))
8436 new))
8439 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8440 "Create an indirect buffer that is a twin copy of the current buffer.
8442 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8443 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8444 or if not called with a prefix arg, NEWNAME defaults to the current
8445 buffer's name. The name is modified by adding a `<N>' suffix to it
8446 or by incrementing the N in an existing suffix. Trying to clone a
8447 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8448 property results in an error.
8450 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8451 This is always done when called interactively.
8453 Optional third arg NORECORD non-nil means do not put this buffer at the
8454 front of the list of recently selected ones.
8456 Returns the newly created indirect buffer."
8457 (interactive
8458 (progn
8459 (if (get major-mode 'no-clone-indirect)
8460 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8461 (list (if current-prefix-arg
8462 (read-buffer "Name of indirect buffer: " (current-buffer)))
8463 t)))
8464 (if (get major-mode 'no-clone-indirect)
8465 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8466 (setq newname (or newname (buffer-name)))
8467 (if (string-match "<[0-9]+>\\'" newname)
8468 (setq newname (substring newname 0 (match-beginning 0))))
8469 (let* ((name (generate-new-buffer-name newname))
8470 (buffer (make-indirect-buffer (current-buffer) name t)))
8471 (with-current-buffer buffer
8472 (run-hooks 'clone-indirect-buffer-hook))
8473 (when display-flag
8474 (pop-to-buffer buffer nil norecord))
8475 buffer))
8478 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8479 "Like `clone-indirect-buffer' but display in another window."
8480 (interactive
8481 (progn
8482 (if (get major-mode 'no-clone-indirect)
8483 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8484 (list (if current-prefix-arg
8485 (read-buffer "Name of indirect buffer: " (current-buffer)))
8486 t)))
8487 (let ((pop-up-windows t))
8488 (clone-indirect-buffer newname display-flag norecord)))
8491 ;;; Handling of Backspace and Delete keys.
8493 (defcustom normal-erase-is-backspace 'maybe
8494 "Set the default behavior of the Delete and Backspace keys.
8496 If set to t, Delete key deletes forward and Backspace key deletes
8497 backward.
8499 If set to nil, both Delete and Backspace keys delete backward.
8501 If set to `maybe' (which is the default), Emacs automatically
8502 selects a behavior. On window systems, the behavior depends on
8503 the keyboard used. If the keyboard has both a Backspace key and
8504 a Delete key, and both are mapped to their usual meanings, the
8505 option's default value is set to t, so that Backspace can be used
8506 to delete backward, and Delete can be used to delete forward.
8508 If not running under a window system, customizing this option
8509 accomplishes a similar effect by mapping C-h, which is usually
8510 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8511 via `keyboard-translate'. The former functionality of C-h is
8512 available on the F1 key. You should probably not use this
8513 setting if you don't have both Backspace, Delete and F1 keys.
8515 Setting this variable with setq doesn't take effect. Programmatically,
8516 call `normal-erase-is-backspace-mode' (which see) instead."
8517 :type '(choice (const :tag "Off" nil)
8518 (const :tag "Maybe" maybe)
8519 (other :tag "On" t))
8520 :group 'editing-basics
8521 :version "21.1"
8522 :set (lambda (symbol value)
8523 ;; The fboundp is because of a problem with :set when
8524 ;; dumping Emacs. It doesn't really matter.
8525 (if (fboundp 'normal-erase-is-backspace-mode)
8526 (normal-erase-is-backspace-mode (or value 0))
8527 (set-default symbol value))))
8529 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8530 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8531 (unless frame (setq frame (selected-frame)))
8532 (with-selected-frame frame
8533 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8534 (normal-erase-is-backspace-mode
8535 (if (if (eq normal-erase-is-backspace 'maybe)
8536 (and (not noninteractive)
8537 (or (memq system-type '(ms-dos windows-nt))
8538 (memq window-system '(w32 ns))
8539 (and (memq window-system '(x))
8540 (fboundp 'x-backspace-delete-keys-p)
8541 (x-backspace-delete-keys-p))
8542 ;; If the terminal Emacs is running on has erase char
8543 ;; set to ^H, use the Backspace key for deleting
8544 ;; backward, and the Delete key for deleting forward.
8545 (and (null window-system)
8546 (eq tty-erase-char ?\^H))))
8547 normal-erase-is-backspace)
8548 1 0)))))
8550 (define-minor-mode normal-erase-is-backspace-mode
8551 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8552 With a prefix argument ARG, enable this feature if ARG is
8553 positive, and disable it otherwise. If called from Lisp, enable
8554 the mode if ARG is omitted or nil.
8556 On window systems, when this mode is on, Delete is mapped to C-d
8557 and Backspace is mapped to DEL; when this mode is off, both
8558 Delete and Backspace are mapped to DEL. (The remapping goes via
8559 `local-function-key-map', so binding Delete or Backspace in the
8560 global or local keymap will override that.)
8562 In addition, on window systems, the bindings of C-Delete, M-Delete,
8563 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8564 the global keymap in accordance with the functionality of Delete and
8565 Backspace. For example, if Delete is remapped to C-d, which deletes
8566 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8567 to DEL, which deletes backward, C-Delete is bound to
8568 `backward-kill-word'.
8570 If not running on a window system, a similar effect is accomplished by
8571 remapping C-h (normally produced by the Backspace key) and DEL via
8572 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8573 to C-d; if it's off, the keys are not remapped.
8575 When not running on a window system, and this mode is turned on, the
8576 former functionality of C-h is available on the F1 key. You should
8577 probably not turn on this mode on a text-only terminal if you don't
8578 have both Backspace, Delete and F1 keys.
8580 See also `normal-erase-is-backspace'."
8581 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8582 . (lambda (v)
8583 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8584 (if v 1 0))))
8585 (let ((enabled (eq 1 (terminal-parameter
8586 nil 'normal-erase-is-backspace))))
8588 (cond ((or (memq window-system '(x w32 ns pc))
8589 (memq system-type '(ms-dos windows-nt)))
8590 (let ((bindings
8591 `(([M-delete] [M-backspace])
8592 ([C-M-delete] [C-M-backspace])
8593 ([?\e C-delete] [?\e C-backspace]))))
8595 (if enabled
8596 (progn
8597 (define-key local-function-key-map [delete] [deletechar])
8598 (define-key local-function-key-map [kp-delete] [deletechar])
8599 (define-key local-function-key-map [backspace] [?\C-?])
8600 (dolist (b bindings)
8601 ;; Not sure if input-decode-map is really right, but
8602 ;; keyboard-translate-table (used below) only works
8603 ;; for integer events, and key-translation-table is
8604 ;; global (like the global-map, used earlier).
8605 (define-key input-decode-map (car b) nil)
8606 (define-key input-decode-map (cadr b) nil)))
8607 (define-key local-function-key-map [delete] [?\C-?])
8608 (define-key local-function-key-map [kp-delete] [?\C-?])
8609 (define-key local-function-key-map [backspace] [?\C-?])
8610 (dolist (b bindings)
8611 (define-key input-decode-map (car b) (cadr b))
8612 (define-key input-decode-map (cadr b) (car b))))))
8614 (if enabled
8615 (progn
8616 (keyboard-translate ?\C-h ?\C-?)
8617 (keyboard-translate ?\C-? ?\C-d))
8618 (keyboard-translate ?\C-h ?\C-h)
8619 (keyboard-translate ?\C-? ?\C-?))))
8621 (if (called-interactively-p 'interactive)
8622 (message "Delete key deletes %s"
8623 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8624 "forward" "backward")))))
8626 (defvar vis-mode-saved-buffer-invisibility-spec nil
8627 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8629 (define-minor-mode read-only-mode
8630 "Change whether the current buffer is read-only.
8631 With prefix argument ARG, make the buffer read-only if ARG is
8632 positive, otherwise make it writable. If buffer is read-only
8633 and `view-read-only' is non-nil, enter view mode.
8635 Do not call this from a Lisp program unless you really intend to
8636 do the same thing as the \\[read-only-mode] command, including
8637 possibly enabling or disabling View mode. Also, note that this
8638 command works by setting the variable `buffer-read-only', which
8639 does not affect read-only regions caused by text properties. To
8640 ignore read-only status in a Lisp program (whether due to text
8641 properties or buffer state), bind `inhibit-read-only' temporarily
8642 to a non-nil value."
8643 :variable buffer-read-only
8644 (cond
8645 ((and (not buffer-read-only) view-mode)
8646 (View-exit-and-edit)
8647 (make-local-variable 'view-read-only)
8648 (setq view-read-only t)) ; Must leave view mode.
8649 ((and buffer-read-only view-read-only
8650 ;; If view-mode is already active, `view-mode-enter' is a nop.
8651 (not view-mode)
8652 (not (eq (get major-mode 'mode-class) 'special)))
8653 (view-mode-enter))))
8655 (define-minor-mode visible-mode
8656 "Toggle making all invisible text temporarily visible (Visible mode).
8657 With a prefix argument ARG, enable Visible mode if ARG is
8658 positive, and disable it otherwise. If called from Lisp, enable
8659 the mode if ARG is omitted or nil.
8661 This mode works by saving the value of `buffer-invisibility-spec'
8662 and setting it to nil."
8663 :lighter " Vis"
8664 :group 'editing-basics
8665 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8666 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8667 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8668 (when visible-mode
8669 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8670 buffer-invisibility-spec)
8671 (setq buffer-invisibility-spec nil)))
8673 (defvar messages-buffer-mode-map
8674 (let ((map (make-sparse-keymap)))
8675 (set-keymap-parent map special-mode-map)
8676 (define-key map "g" nil) ; nothing to revert
8677 map))
8679 (define-derived-mode messages-buffer-mode special-mode "Messages"
8680 "Major mode used in the \"*Messages*\" buffer.")
8682 (defun messages-buffer ()
8683 "Return the \"*Messages*\" buffer.
8684 If it does not exist, create and it switch it to `messages-buffer-mode'."
8685 (or (get-buffer "*Messages*")
8686 (with-current-buffer (get-buffer-create "*Messages*")
8687 (messages-buffer-mode)
8688 (current-buffer))))
8691 ;; Minibuffer prompt stuff.
8693 ;;(defun minibuffer-prompt-modification (start end)
8694 ;; (error "You cannot modify the prompt"))
8697 ;;(defun minibuffer-prompt-insertion (start end)
8698 ;; (let ((inhibit-modification-hooks t))
8699 ;; (delete-region start end)
8700 ;; ;; Discard undo information for the text insertion itself
8701 ;; ;; and for the text deletion.above.
8702 ;; (when (consp buffer-undo-list)
8703 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8704 ;; (message "You cannot modify the prompt")))
8707 ;;(setq minibuffer-prompt-properties
8708 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8709 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8712 ;;;; Problematic external packages.
8714 ;; rms says this should be done by specifying symbols that define
8715 ;; versions together with bad values. This is therefore not as
8716 ;; flexible as it could be. See the thread:
8717 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8718 (defconst bad-packages-alist
8719 ;; Not sure exactly which semantic versions have problems.
8720 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8721 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8722 "The version of `semantic' loaded does not work in Emacs 22.
8723 It can cause constant high CPU load.
8724 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8725 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8726 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8727 ;; provided the `CUA-mode' feature. Since this is no longer true,
8728 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8729 (CUA-mode t nil
8730 "CUA-mode is now part of the standard GNU Emacs distribution,
8731 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8733 You have loaded an older version of CUA-mode which does not work
8734 correctly with this version of Emacs. You should remove the old
8735 version and use the one distributed with Emacs."))
8736 "Alist of packages known to cause problems in this version of Emacs.
8737 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8738 PACKAGE is either a regular expression to match file names, or a
8739 symbol (a feature name), like for `with-eval-after-load'.
8740 SYMBOL is either the name of a string variable, or t. Upon
8741 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8742 warning using STRING as the message.")
8744 (defun bad-package-check (package)
8745 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8746 (condition-case nil
8747 (let* ((list (assoc package bad-packages-alist))
8748 (symbol (nth 1 list)))
8749 (and list
8750 (boundp symbol)
8751 (or (eq symbol t)
8752 (and (stringp (setq symbol (eval symbol)))
8753 (string-match-p (nth 2 list) symbol)))
8754 (display-warning package (nth 3 list) :warning)))
8755 (error nil)))
8757 (dolist (elem bad-packages-alist)
8758 (let ((pkg (car elem)))
8759 (with-eval-after-load pkg
8760 (bad-package-check pkg))))
8763 ;;; Generic dispatcher commands
8765 ;; Macro `define-alternatives' is used to create generic commands.
8766 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8767 ;; that can have different alternative implementations where choosing
8768 ;; among them is exclusively a matter of user preference.
8770 ;; (define-alternatives COMMAND) creates a new interactive command
8771 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8772 ;; Typically, the user will not need to customize this variable; packages
8773 ;; wanting to add alternative implementations should use
8775 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8777 (defmacro define-alternatives (command &rest customizations)
8778 "Define the new command `COMMAND'.
8780 The argument `COMMAND' should be a symbol.
8782 Running `M-x COMMAND RET' for the first time prompts for which
8783 alternative to use and records the selected command as a custom
8784 variable.
8786 Running `C-u M-x COMMAND RET' prompts again for an alternative
8787 and overwrites the previous choice.
8789 The variable `COMMAND-alternatives' contains an alist with
8790 alternative implementations of COMMAND. `define-alternatives'
8791 does not have any effect until this variable is set.
8793 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8794 `defcustom' keywords and values to add to the declaration of
8795 `COMMAND-alternatives' (typically :group and :version)."
8796 (let* ((command-name (symbol-name command))
8797 (varalt-name (concat command-name "-alternatives"))
8798 (varalt-sym (intern varalt-name))
8799 (varimp-sym (intern (concat command-name "--implementation"))))
8800 `(progn
8802 (defcustom ,varalt-sym nil
8803 ,(format "Alist of alternative implementations for the `%s' command.
8805 Each entry must be a pair (ALTNAME . ALTFUN), where:
8806 ALTNAME - The name shown at user to describe the alternative implementation.
8807 ALTFUN - The function called to implement this alternative."
8808 command-name)
8809 :type '(alist :key-type string :value-type function)
8810 ,@customizations)
8812 (put ',varalt-sym 'definition-name ',command)
8813 (defvar ,varimp-sym nil "Internal use only.")
8815 (defun ,command (&optional arg)
8816 ,(format "Run generic command `%s'.
8817 If used for the first time, or with interactive ARG, ask the user which
8818 implementation to use for `%s'. The variable `%s'
8819 contains the list of implementations currently supported for this command."
8820 command-name command-name varalt-name)
8821 (interactive "P")
8822 (when (or arg (null ,varimp-sym))
8823 (let ((val (completing-read
8824 ,(format-message
8825 "Select implementation for command `%s': "
8826 command-name)
8827 ,varalt-sym nil t)))
8828 (unless (string-equal val "")
8829 (when (null ,varimp-sym)
8830 (message
8831 "Use C-u M-x %s RET`to select another implementation"
8832 ,command-name)
8833 (sit-for 3))
8834 (customize-save-variable ',varimp-sym
8835 (cdr (assoc-string val ,varalt-sym))))))
8836 (if ,varimp-sym
8837 (call-interactively ,varimp-sym)
8838 (message "%s" ,(format-message
8839 "No implementation selected for command `%s'"
8840 command-name)))))))
8843 ;;; Functions for changing capitalization that Do What I Mean
8844 (defun upcase-dwim (arg)
8845 "Upcase words in the region, if active; if not, upcase word at point.
8846 If the region is active, this function calls `upcase-region'.
8847 Otherwise, it calls `upcase-word', with prefix argument passed to it
8848 to upcase ARG words."
8849 (interactive "*p")
8850 (if (use-region-p)
8851 (upcase-region (region-beginning) (region-end))
8852 (upcase-word arg)))
8854 (defun downcase-dwim (arg)
8855 "Downcase words in the region, if active; if not, downcase word at point.
8856 If the region is active, this function calls `downcase-region'.
8857 Otherwise, it calls `downcase-word', with prefix argument passed to it
8858 to downcase ARG words."
8859 (interactive "*p")
8860 (if (use-region-p)
8861 (downcase-region (region-beginning) (region-end))
8862 (downcase-word arg)))
8864 (defun capitalize-dwim (arg)
8865 "Capitalize words in the region, if active; if not, capitalize word at point.
8866 If the region is active, this function calls `capitalize-region'.
8867 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8868 to capitalize ARG words."
8869 (interactive "*p")
8870 (if (use-region-p)
8871 (capitalize-region (region-beginning) (region-end))
8872 (capitalize-word arg)))
8876 (provide 'simple)
8878 ;;; simple.el ends here