Document reserved keys
[emacs.git] / lisp / simple.el
blobb7ad6ebd7995295e29b1a34d702bc060a065ed93
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2018 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 <https://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 sets the point in the output buffer
43 once the command completes.
44 The value `beg-last-out' sets point at the beginning of the output,
45 `end-last-out' sets point at the end of the buffer, `save-point'
46 restores 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 "Record of point positions in output buffers after command completion.
57 The value is an alist whose elements are of the form (BUFFER . POS),
58 where BUFFER is the output buffer, and POS is the point position
59 in BUFFER once the command finishes.
60 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
62 (defcustom idle-update-delay 0.5
63 "Idle time delay before updating various things on the screen.
64 Various Emacs features that update auxiliary information when point moves
65 wait this many seconds after Emacs becomes idle before doing an update."
66 :type 'number
67 :group 'display
68 :version "22.1")
70 (defgroup killing nil
71 "Killing and yanking commands."
72 :group 'editing)
74 (defgroup paren-matching nil
75 "Highlight (un)matching of parens and expressions."
76 :group 'matching)
78 ;;; next-error support framework
80 (defgroup next-error nil
81 "`next-error' support framework."
82 :group 'compilation
83 :version "22.1")
85 (defface next-error
86 '((t (:inherit region)))
87 "Face used to highlight next error locus."
88 :group 'next-error
89 :version "22.1")
91 (defcustom next-error-highlight 0.5
92 "Highlighting of locations in selected source buffers.
93 If a number, highlight the locus in `next-error' face for the given time
94 in seconds, or until the next command is executed.
95 If t, highlight the locus until the next command is executed, or until
96 some other locus replaces it.
97 If nil, don't highlight the locus in the source buffer.
98 If `fringe-arrow', indicate the locus by the fringe arrow
99 indefinitely until some other locus replaces it."
100 :type '(choice (number :tag "Highlight for specified time")
101 (const :tag "Semipermanent highlighting" t)
102 (const :tag "No highlighting" nil)
103 (const :tag "Fringe arrow" fringe-arrow))
104 :group 'next-error
105 :version "22.1")
107 (defcustom next-error-highlight-no-select 0.5
108 "Highlighting of locations in `next-error-no-select'.
109 If number, highlight the locus in `next-error' face for given time in seconds.
110 If t, highlight the locus indefinitely until some other locus replaces it.
111 If nil, don't highlight the locus in the source buffer.
112 If `fringe-arrow', indicate the locus by the fringe arrow
113 indefinitely until some other locus replaces it."
114 :type '(choice (number :tag "Highlight for specified time")
115 (const :tag "Semipermanent highlighting" t)
116 (const :tag "No highlighting" nil)
117 (const :tag "Fringe arrow" fringe-arrow))
118 :group 'next-error
119 :version "22.1")
121 (defcustom next-error-recenter nil
122 "Display the line in the visited source file recentered as specified.
123 If non-nil, the value is passed directly to `recenter'."
124 :type '(choice (integer :tag "Line to recenter to")
125 (const :tag "Center of window" (4))
126 (const :tag "No recentering" nil))
127 :group 'next-error
128 :version "23.1")
130 (defcustom next-error-hook nil
131 "List of hook functions run by `next-error' after visiting source file."
132 :type 'hook
133 :group 'next-error)
135 (defvar next-error-highlight-timer nil)
137 (defvar next-error-overlay-arrow-position nil)
138 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
139 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
141 (defvar next-error-last-buffer nil
142 "The most recent `next-error' buffer.
143 A buffer becomes most recent when its compilation, grep, or
144 similar mode is started, or when it is used with \\[next-error]
145 or \\[compile-goto-error].")
147 (defvar next-error-function nil
148 "Function to use to find the next error in the current buffer.
149 The function is called with 2 parameters:
150 ARG is an integer specifying by how many errors to move.
151 RESET is a boolean which, if non-nil, says to go back to the beginning
152 of the errors before moving.
153 Major modes providing compile-like functionality should set this variable
154 to indicate to `next-error' that this is a candidate buffer and how
155 to navigate in it.")
156 (make-variable-buffer-local 'next-error-function)
158 (defvar next-error-move-function nil
159 "Function to use to move to an error locus.
160 It takes two arguments, a buffer position in the error buffer
161 and a buffer position in the error locus buffer.
162 The buffer for the error locus should already be current.
163 nil means use goto-char using the second argument position.")
164 (make-variable-buffer-local 'next-error-move-function)
166 (defsubst next-error-buffer-p (buffer
167 &optional avoid-current
168 extra-test-inclusive
169 extra-test-exclusive)
170 "Return non-nil if BUFFER is a `next-error' capable buffer.
171 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
172 return nil.
174 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
175 BUFFER would not normally qualify. If it returns non-nil, BUFFER
176 is considered `next-error' capable, anyway, and the function
177 returns non-nil.
179 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
180 buffer would normally qualify. If it returns nil, BUFFER is
181 rejected, and the function returns nil."
182 (and (buffer-name buffer) ;First make sure it's live.
183 (not (and avoid-current (eq buffer (current-buffer))))
184 (with-current-buffer buffer
185 (if next-error-function ; This is the normal test.
186 ;; Optionally reject some buffers.
187 (if extra-test-exclusive
188 (funcall extra-test-exclusive)
190 ;; Optionally accept some other buffers.
191 (and extra-test-inclusive
192 (funcall extra-test-inclusive))))))
194 (defun next-error-find-buffer (&optional avoid-current
195 extra-test-inclusive
196 extra-test-exclusive)
197 "Return a `next-error' capable buffer.
199 If AVOID-CURRENT is non-nil, treat the current buffer
200 as an absolute last resort only.
202 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
203 that normally would not qualify. If it returns t, the buffer
204 in question is treated as usable.
206 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
207 that would normally be considered usable. If it returns nil,
208 that buffer is rejected."
210 ;; 1. If one window on the selected frame displays such buffer, return it.
211 (let ((window-buffers
212 (delete-dups
213 (delq nil (mapcar (lambda (w)
214 (if (next-error-buffer-p
215 (window-buffer w)
216 avoid-current
217 extra-test-inclusive extra-test-exclusive)
218 (window-buffer w)))
219 (window-list))))))
220 (if (eq (length window-buffers) 1)
221 (car window-buffers)))
222 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
223 (if (and next-error-last-buffer
224 (next-error-buffer-p next-error-last-buffer avoid-current
225 extra-test-inclusive extra-test-exclusive))
226 next-error-last-buffer)
227 ;; 3. If the current buffer is acceptable, choose it.
228 (if (next-error-buffer-p (current-buffer) avoid-current
229 extra-test-inclusive extra-test-exclusive)
230 (current-buffer))
231 ;; 4. Look for any acceptable buffer.
232 (let ((buffers (buffer-list)))
233 (while (and buffers
234 (not (next-error-buffer-p
235 (car buffers) avoid-current
236 extra-test-inclusive extra-test-exclusive)))
237 (setq buffers (cdr buffers)))
238 (car buffers))
239 ;; 5. Use the current buffer as a last resort if it qualifies,
240 ;; even despite AVOID-CURRENT.
241 (and avoid-current
242 (next-error-buffer-p (current-buffer) nil
243 extra-test-inclusive extra-test-exclusive)
244 (progn
245 (message "This is the only buffer with error message locations")
246 (current-buffer)))
247 ;; 6. Give up.
248 (error "No buffers contain error message locations")))
250 (defun next-error (&optional arg reset)
251 "Visit next `next-error' message and corresponding source code.
253 If all the error messages parsed so far have been processed already,
254 the message buffer is checked for new ones.
256 A prefix ARG specifies how many error messages to move;
257 negative means move back to previous error messages.
258 Just \\[universal-argument] as a prefix means reparse the error message buffer
259 and start at the first error.
261 The RESET argument specifies that we should restart from the beginning.
263 \\[next-error] normally uses the most recently started
264 compilation, grep, or occur buffer. It can also operate on any
265 buffer with output from the \\[compile], \\[grep] commands, or,
266 more generally, on any buffer in Compilation mode or with
267 Compilation Minor mode enabled, or any buffer in which
268 `next-error-function' is bound to an appropriate function.
269 To specify use of a particular buffer for error messages, type
270 \\[next-error] in that buffer when it is the only one displayed
271 in the current frame.
273 Once \\[next-error] has chosen the buffer for error messages, it
274 runs `next-error-hook' with `run-hooks', and stays with that buffer
275 until you use it in some other buffer which uses Compilation mode
276 or Compilation Minor mode.
278 To control which errors are matched, customize the variable
279 `compilation-error-regexp-alist'."
280 (interactive "P")
281 (if (consp arg) (setq reset t arg nil))
282 (when (setq next-error-last-buffer (next-error-find-buffer))
283 ;; we know here that next-error-function is a valid symbol we can funcall
284 (with-current-buffer next-error-last-buffer
285 (funcall next-error-function (prefix-numeric-value arg) reset)
286 (when next-error-recenter
287 (recenter next-error-recenter))
288 (run-hooks 'next-error-hook))))
290 (defun next-error-internal ()
291 "Visit the source code corresponding to the `next-error' message at point."
292 (setq next-error-last-buffer (current-buffer))
293 ;; we know here that next-error-function is a valid symbol we can funcall
294 (with-current-buffer next-error-last-buffer
295 (funcall next-error-function 0 nil)
296 (when next-error-recenter
297 (recenter next-error-recenter))
298 (run-hooks 'next-error-hook)))
300 (defalias 'goto-next-locus 'next-error)
301 (defalias 'next-match 'next-error)
303 (defun previous-error (&optional n)
304 "Visit previous `next-error' message and corresponding source code.
306 Prefix arg N says how many error messages to move backwards (or
307 forwards, if negative).
309 This operates on the output from the \\[compile] and \\[grep] commands."
310 (interactive "p")
311 (next-error (- (or n 1))))
313 (defun first-error (&optional n)
314 "Restart at the first error.
315 Visit corresponding source code.
316 With prefix arg N, visit the source code of the Nth error.
317 This operates on the output from the \\[compile] command, for instance."
318 (interactive "p")
319 (next-error n t))
321 (defun next-error-no-select (&optional n)
322 "Move point to the next error in the `next-error' buffer and highlight match.
323 Prefix arg N says how many error messages to move forwards (or
324 backwards, if negative).
325 Finds and highlights the source line like \\[next-error], but does not
326 select the source buffer."
327 (interactive "p")
328 (let ((next-error-highlight next-error-highlight-no-select))
329 (next-error n))
330 (pop-to-buffer next-error-last-buffer))
332 (defun previous-error-no-select (&optional n)
333 "Move point to the previous error in the `next-error' buffer and highlight match.
334 Prefix arg N says how many error messages to move backwards (or
335 forwards, if negative).
336 Finds and highlights the source line like \\[previous-error], but does not
337 select the source buffer."
338 (interactive "p")
339 (next-error-no-select (- (or n 1))))
341 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
342 (defvar next-error-follow-last-line nil)
344 (define-minor-mode next-error-follow-minor-mode
345 "Minor mode for compilation, occur and diff modes.
346 With a prefix argument ARG, enable mode if ARG is positive, and
347 disable it otherwise. If called from Lisp, enable mode if ARG is
348 omitted or nil.
349 When turned on, cursor motion in the compilation, grep, occur or diff
350 buffer causes automatic display of the corresponding source code location."
351 :group 'next-error :init-value nil :lighter " Fol"
352 (if (not next-error-follow-minor-mode)
353 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
354 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
355 (make-local-variable 'next-error-follow-last-line)))
357 ;; Used as a `post-command-hook' by `next-error-follow-mode'
358 ;; for the *Compilation* *grep* and *Occur* buffers.
359 (defun next-error-follow-mode-post-command-hook ()
360 (unless (equal next-error-follow-last-line (line-number-at-pos))
361 (setq next-error-follow-last-line (line-number-at-pos))
362 (condition-case nil
363 (let ((compilation-context-lines nil))
364 (setq compilation-current-error (point))
365 (next-error-no-select 0))
366 (error t))))
371 (defun fundamental-mode ()
372 "Major mode not specialized for anything in particular.
373 Other major modes are defined by comparison with this one."
374 (interactive)
375 (kill-all-local-variables)
376 (run-mode-hooks))
378 ;; Special major modes to view specially formatted data rather than files.
380 (defvar special-mode-map
381 (let ((map (make-sparse-keymap)))
382 (suppress-keymap map)
383 (define-key map "q" 'quit-window)
384 (define-key map " " 'scroll-up-command)
385 (define-key map [?\S-\ ] 'scroll-down-command)
386 (define-key map "\C-?" 'scroll-down-command)
387 (define-key map "?" 'describe-mode)
388 (define-key map "h" 'describe-mode)
389 (define-key map ">" 'end-of-buffer)
390 (define-key map "<" 'beginning-of-buffer)
391 (define-key map "g" 'revert-buffer)
392 map))
394 (put 'special-mode 'mode-class 'special)
395 (define-derived-mode special-mode nil "Special"
396 "Parent major mode from which special major modes should inherit."
397 (setq buffer-read-only t))
399 ;; Making and deleting lines.
401 (defvar self-insert-uses-region-functions nil
402 "Special hook to tell if `self-insert-command' will use the region.
403 It must be called via `run-hook-with-args-until-success' with no arguments.
405 If any function on this hook returns a non-nil value, `delete-selection-mode'
406 will act on that value (see `delete-selection-helper'), and will
407 usually delete the region. If all the functions on this hook return
408 nil, it is an indiction that `self-insert-command' needs the region
409 untouched by `delete-selection-mode', and will itself do whatever is
410 appropriate with the region.
411 Any function on `post-self-insert-hook' which act on the region should
412 add a function to this hook so that `delete-selection-mode' could
413 refrain from deleting the region before `post-self-insert-hook'
414 functions are called.
415 This hook is run by `delete-selection-uses-region-p', which see.")
417 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
418 "Propertized string representing a hard newline character.")
420 (defun newline (&optional arg interactive)
421 "Insert a newline, and move to left margin of the new line if it's blank.
422 If option `use-hard-newlines' is non-nil, the newline is marked with the
423 text-property `hard'.
424 With ARG, insert that many newlines.
426 If `electric-indent-mode' is enabled, this indents the final new line
427 that it adds, and reindents the preceding line. To just insert
428 a newline, use \\[electric-indent-just-newline].
430 Calls `auto-fill-function' if the current column number is greater
431 than the value of `fill-column' and ARG is nil.
432 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
433 (interactive "*P\np")
434 (barf-if-buffer-read-only)
435 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
436 ;; Set last-command-event to tell self-insert what to insert.
437 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
438 (beforepos (point))
439 (last-command-event ?\n)
440 ;; Don't auto-fill if we have a numeric argument.
441 (auto-fill-function (if arg nil auto-fill-function))
442 (arg (prefix-numeric-value arg))
443 (postproc
444 ;; Do the rest in post-self-insert-hook, because we want to do it
445 ;; *before* other functions on that hook.
446 (lambda ()
447 ;; Mark the newline(s) `hard'.
448 (if use-hard-newlines
449 (set-hard-newline-properties
450 (- (point) arg) (point)))
451 ;; If the newline leaves the previous line blank, and we
452 ;; have a left margin, delete that from the blank line.
453 (save-excursion
454 (goto-char beforepos)
455 (beginning-of-line)
456 (and (looking-at "[ \t]$")
457 (> (current-left-margin) 0)
458 (delete-region (point)
459 (line-end-position))))
460 ;; Indent the line after the newline, except in one case:
461 ;; when we added the newline at the beginning of a line which
462 ;; starts a page.
463 (or was-page-start
464 (move-to-left-margin nil t)))))
465 (if (not interactive)
466 ;; FIXME: For non-interactive uses, many calls actually
467 ;; just want (insert "\n"), so maybe we should do just
468 ;; that, so as to avoid the risk of filling or running
469 ;; abbrevs unexpectedly.
470 (let ((post-self-insert-hook (list postproc)))
471 (self-insert-command arg))
472 (unwind-protect
473 (progn
474 (add-hook 'post-self-insert-hook postproc nil t)
475 (self-insert-command arg))
476 ;; We first used let-binding to protect the hook, but that
477 ;; was naive since add-hook affects the symbol-default
478 ;; value of the variable, whereas the let-binding might
479 ;; only protect the buffer-local value.
480 (remove-hook 'post-self-insert-hook postproc t))))
481 nil)
483 (defun set-hard-newline-properties (from to)
484 (let ((sticky (get-text-property from 'rear-nonsticky)))
485 (put-text-property from to 'hard 't)
486 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
487 (if (and (listp sticky) (not (memq 'hard sticky)))
488 (put-text-property from (point) 'rear-nonsticky
489 (cons 'hard sticky)))))
491 (defun open-line (n)
492 "Insert a newline and leave point before it.
493 If there is a fill prefix and/or a `left-margin', insert them on
494 the new line if the line would have been blank.
495 With arg N, insert N newlines."
496 (interactive "*p")
497 (let* ((do-fill-prefix (and fill-prefix (bolp)))
498 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
499 (loc (point-marker))
500 ;; Don't expand an abbrev before point.
501 (abbrev-mode nil))
502 (newline n)
503 (goto-char loc)
504 (while (> n 0)
505 (cond ((bolp)
506 (if do-left-margin (indent-to (current-left-margin)))
507 (if do-fill-prefix (insert-and-inherit fill-prefix))))
508 (forward-line 1)
509 (setq n (1- n)))
510 (goto-char loc)
511 ;; Necessary in case a margin or prefix was inserted.
512 (end-of-line)))
514 (defun split-line (&optional arg)
515 "Split current line, moving portion beyond point vertically down.
516 If the current line starts with `fill-prefix', insert it on the new
517 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
519 When called from Lisp code, ARG may be a prefix string to copy."
520 (interactive "*P")
521 (skip-chars-forward " \t")
522 (let* ((col (current-column))
523 (pos (point))
524 ;; What prefix should we check for (nil means don't).
525 (prefix (cond ((stringp arg) arg)
526 (arg nil)
527 (t fill-prefix)))
528 ;; Does this line start with it?
529 (have-prfx (and prefix
530 (save-excursion
531 (beginning-of-line)
532 (looking-at (regexp-quote prefix))))))
533 (newline 1)
534 (if have-prfx (insert-and-inherit prefix))
535 (indent-to col 0)
536 (goto-char pos)))
538 (defun delete-indentation (&optional arg)
539 "Join this line to previous and fix up whitespace at join.
540 If there is a fill prefix, delete it from the beginning of this line.
541 With argument, join this line to following line."
542 (interactive "*P")
543 (beginning-of-line)
544 (if arg (forward-line 1))
545 (if (eq (preceding-char) ?\n)
546 (progn
547 (delete-region (point) (1- (point)))
548 ;; If the second line started with the fill prefix,
549 ;; delete the prefix.
550 (if (and fill-prefix
551 (<= (+ (point) (length fill-prefix)) (point-max))
552 (string= fill-prefix
553 (buffer-substring (point)
554 (+ (point) (length fill-prefix)))))
555 (delete-region (point) (+ (point) (length fill-prefix))))
556 (fixup-whitespace))))
558 (defalias 'join-line #'delete-indentation) ; easier to find
560 (defun delete-blank-lines ()
561 "On blank line, delete all surrounding blank lines, leaving just one.
562 On isolated blank line, delete that one.
563 On nonblank line, delete any immediately following blank lines."
564 (interactive "*")
565 (let (thisblank singleblank)
566 (save-excursion
567 (beginning-of-line)
568 (setq thisblank (looking-at "[ \t]*$"))
569 ;; Set singleblank if there is just one blank line here.
570 (setq singleblank
571 (and thisblank
572 (not (looking-at "[ \t]*\n[ \t]*$"))
573 (or (bobp)
574 (progn (forward-line -1)
575 (not (looking-at "[ \t]*$")))))))
576 ;; Delete preceding blank lines, and this one too if it's the only one.
577 (if thisblank
578 (progn
579 (beginning-of-line)
580 (if singleblank (forward-line 1))
581 (delete-region (point)
582 (if (re-search-backward "[^ \t\n]" nil t)
583 (progn (forward-line 1) (point))
584 (point-min)))))
585 ;; Delete following blank lines, unless the current line is blank
586 ;; and there are no following blank lines.
587 (if (not (and thisblank singleblank))
588 (save-excursion
589 (end-of-line)
590 (forward-line 1)
591 (delete-region (point)
592 (if (re-search-forward "[^ \t\n]" nil t)
593 (progn (beginning-of-line) (point))
594 (point-max)))))
595 ;; Handle the special case where point is followed by newline and eob.
596 ;; Delete the line, leaving point at eob.
597 (if (looking-at "^[ \t]*\n\\'")
598 (delete-region (point) (point-max)))))
600 (defcustom delete-trailing-lines t
601 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
602 Trailing lines are deleted only if `delete-trailing-whitespace'
603 is called on the entire buffer (rather than an active region)."
604 :type 'boolean
605 :group 'editing
606 :version "24.3")
608 (defun region-modifiable-p (start end)
609 "Return non-nil if the region contains no read-only text."
610 (and (not (get-text-property start 'read-only))
611 (eq end (next-single-property-change start 'read-only nil end))))
613 (defun delete-trailing-whitespace (&optional start end)
614 "Delete trailing whitespace between START and END.
615 If called interactively, START and END are the start/end of the
616 region if the mark is active, or of the buffer's accessible
617 portion if the mark is inactive.
619 This command deletes whitespace characters after the last
620 non-whitespace character in each line between START and END. It
621 does not consider formfeed characters to be whitespace.
623 If this command acts on the entire buffer (i.e. if called
624 interactively with the mark inactive, or called from Lisp with
625 END nil), it also deletes all trailing lines at the end of the
626 buffer if the variable `delete-trailing-lines' is non-nil."
627 (interactive (progn
628 (barf-if-buffer-read-only)
629 (if (use-region-p)
630 (list (region-beginning) (region-end))
631 (list nil nil))))
632 (save-match-data
633 (save-excursion
634 (let ((end-marker (and end (copy-marker end))))
635 (goto-char (or start (point-min)))
636 (with-syntax-table (make-syntax-table (syntax-table))
637 ;; Don't delete formfeeds, even if they are considered whitespace.
638 (modify-syntax-entry ?\f "_")
639 (while (re-search-forward "\\s-$" end-marker t)
640 (skip-syntax-backward "-" (line-beginning-position))
641 (let ((b (point)) (e (match-end 0)))
642 (when (region-modifiable-p b e)
643 (delete-region b e)))))
644 (if end
645 (set-marker end-marker nil)
646 ;; Delete trailing empty lines.
647 (and delete-trailing-lines
648 ;; Really the end of buffer.
649 (= (goto-char (point-max)) (1+ (buffer-size)))
650 (<= (skip-chars-backward "\n") -2)
651 (region-modifiable-p (1+ (point)) (point-max))
652 (delete-region (1+ (point)) (point-max)))))))
653 ;; Return nil for the benefit of `write-file-functions'.
654 nil)
656 (defun newline-and-indent ()
657 "Insert a newline, then indent according to major mode.
658 Indentation is done using the value of `indent-line-function'.
659 In programming language modes, this is the same as TAB.
660 In some text modes, where TAB inserts a tab, this command indents to the
661 column specified by the function `current-left-margin'."
662 (interactive "*")
663 (delete-horizontal-space t)
664 (newline nil t)
665 (indent-according-to-mode))
667 (defun reindent-then-newline-and-indent ()
668 "Reindent current line, insert newline, then indent the new line.
669 Indentation of both lines is done according to the current major mode,
670 which means calling the current value of `indent-line-function'.
671 In programming language modes, this is the same as TAB.
672 In some text modes, where TAB inserts a tab, this indents to the
673 column specified by the function `current-left-margin'."
674 (interactive "*")
675 (let ((pos (point)))
676 ;; Be careful to insert the newline before indenting the line.
677 ;; Otherwise, the indentation might be wrong.
678 (newline)
679 (save-excursion
680 (goto-char pos)
681 ;; We are at EOL before the call to indent-according-to-mode, and
682 ;; after it we usually are as well, but not always. We tried to
683 ;; address it with `save-excursion' but that uses a normal marker
684 ;; whereas we need `move after insertion', so we do the save/restore
685 ;; by hand.
686 (setq pos (copy-marker pos t))
687 (indent-according-to-mode)
688 (goto-char pos)
689 ;; Remove the trailing white-space after indentation because
690 ;; indentation may introduce the whitespace.
691 (delete-horizontal-space t))
692 (indent-according-to-mode)))
694 (defcustom read-quoted-char-radix 8
695 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
696 Legitimate radix values are 8, 10 and 16."
697 :type '(choice (const 8) (const 10) (const 16))
698 :group 'editing-basics)
700 (defun read-quoted-char (&optional prompt)
701 "Like `read-char', but do not allow quitting.
702 Also, if the first character read is an octal digit,
703 we read any number of octal digits and return the
704 specified character code. Any nondigit terminates the sequence.
705 If the terminator is RET, it is discarded;
706 any other terminator is used itself as input.
708 The optional argument PROMPT specifies a string to use to prompt the user.
709 The variable `read-quoted-char-radix' controls which radix to use
710 for numeric input."
711 (let ((message-log-max nil)
712 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
713 help-event-list)))
714 done (first t) (code 0) char translated)
715 (while (not done)
716 (let ((inhibit-quit first)
717 ;; Don't let C-h or other help chars get the help
718 ;; message--only help function keys. See bug#16617.
719 (help-char nil)
720 (help-event-list help-events)
721 (help-form
722 "Type the special character you want to use,
723 or the octal character code.
724 RET terminates the character code and is discarded;
725 any other non-digit terminates the character code and is then used as input."))
726 (setq char (read-event (and prompt (format "%s-" prompt)) t))
727 (if inhibit-quit (setq quit-flag nil)))
728 ;; Translate TAB key into control-I ASCII character, and so on.
729 ;; Note: `read-char' does it using the `ascii-character' property.
730 ;; We tried using read-key instead, but that disables the keystroke
731 ;; echo produced by 'C-q', see bug#24635.
732 (let ((translation (lookup-key local-function-key-map (vector char))))
733 (setq translated (if (arrayp translation)
734 (aref translation 0)
735 char)))
736 (if (integerp translated)
737 (setq translated (char-resolve-modifiers translated)))
738 (cond ((null translated))
739 ((not (integerp translated))
740 (setq unread-command-events (list char)
741 done t))
742 ((/= (logand translated ?\M-\^@) 0)
743 ;; Turn a meta-character into a character with the 0200 bit set.
744 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
745 done t))
746 ((and (<= ?0 translated)
747 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
748 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
749 (and prompt (setq prompt (message "%s %c" prompt translated))))
750 ((and (<= ?a (downcase translated))
751 (< (downcase translated)
752 (+ ?a -10 (min 36 read-quoted-char-radix))))
753 (setq code (+ (* code read-quoted-char-radix)
754 (+ 10 (- (downcase translated) ?a))))
755 (and prompt (setq prompt (message "%s %c" prompt translated))))
756 ((and (not first) (eq translated ?\C-m))
757 (setq done t))
758 ((not first)
759 (setq unread-command-events (list char)
760 done t))
761 (t (setq code translated
762 done t)))
763 (setq first nil))
764 code))
766 (defun quoted-insert (arg)
767 "Read next input character and insert it.
768 This is useful for inserting control characters.
769 With argument, insert ARG copies of the character.
771 If the first character you type after this command is an octal digit,
772 you should type a sequence of octal digits which specify a character code.
773 Any nondigit terminates the sequence. If the terminator is a RET,
774 it is discarded; any other terminator is used itself as input.
775 The variable `read-quoted-char-radix' specifies the radix for this feature;
776 set it to 10 or 16 to use decimal or hex instead of octal.
778 In overwrite mode, this function inserts the character anyway, and
779 does not handle octal digits specially. This means that if you use
780 overwrite as your normal editing mode, you can use this function to
781 insert characters when necessary.
783 In binary overwrite mode, this function does overwrite, and octal
784 digits are interpreted as a character code. This is intended to be
785 useful for editing binary files."
786 (interactive "*p")
787 (let* ((char
788 ;; Avoid "obsolete" warnings for translation-table-for-input.
789 (with-no-warnings
790 (let (translation-table-for-input input-method-function)
791 (if (or (not overwrite-mode)
792 (eq overwrite-mode 'overwrite-mode-binary))
793 (read-quoted-char)
794 (read-char))))))
795 ;; This used to assume character codes 0240 - 0377 stand for
796 ;; characters in some single-byte character set, and converted them
797 ;; to Emacs characters. But in 23.1 this feature is deprecated
798 ;; in favor of inserting the corresponding Unicode characters.
799 ;; (if (and enable-multibyte-characters
800 ;; (>= char ?\240)
801 ;; (<= char ?\377))
802 ;; (setq char (unibyte-char-to-multibyte char)))
803 (unless (characterp char)
804 (user-error "%s is not a valid character"
805 (key-description (vector char))))
806 (if (> arg 0)
807 (if (eq overwrite-mode 'overwrite-mode-binary)
808 (delete-char arg)))
809 (while (> arg 0)
810 (insert-and-inherit char)
811 (setq arg (1- arg)))))
813 (defun forward-to-indentation (&optional arg)
814 "Move forward ARG lines and position at first nonblank character."
815 (interactive "^p")
816 (forward-line (or arg 1))
817 (skip-chars-forward " \t"))
819 (defun backward-to-indentation (&optional arg)
820 "Move backward ARG lines and position at first nonblank character."
821 (interactive "^p")
822 (forward-line (- (or arg 1)))
823 (skip-chars-forward " \t"))
825 (defun back-to-indentation ()
826 "Move point to the first non-whitespace character on this line."
827 (interactive "^")
828 (beginning-of-line 1)
829 (skip-syntax-forward " " (line-end-position))
830 ;; Move back over chars that have whitespace syntax but have the p flag.
831 (backward-prefix-chars))
833 (defun fixup-whitespace ()
834 "Fixup white space between objects around point.
835 Leave one space or none, according to the context."
836 (interactive "*")
837 (save-excursion
838 (delete-horizontal-space)
839 (if (or (looking-at "^\\|$\\|\\s)")
840 (save-excursion (forward-char -1)
841 (looking-at "$\\|\\s(\\|\\s'")))
843 (insert ?\s))))
845 (defun delete-horizontal-space (&optional backward-only)
846 "Delete all spaces and tabs around point.
847 If BACKWARD-ONLY is non-nil, only delete them before point."
848 (interactive "*P")
849 (let ((orig-pos (point)))
850 (delete-region
851 (if backward-only
852 orig-pos
853 (progn
854 (skip-chars-forward " \t")
855 (constrain-to-field nil orig-pos t)))
856 (progn
857 (skip-chars-backward " \t")
858 (constrain-to-field nil orig-pos)))))
860 (defun just-one-space (&optional n)
861 "Delete all spaces and tabs around point, leaving one space (or N spaces).
862 If N is negative, delete newlines as well, leaving -N spaces.
863 See also `cycle-spacing'."
864 (interactive "*p")
865 (cycle-spacing n nil 'single-shot))
867 (defvar cycle-spacing--context nil
868 "Store context used in consecutive calls to `cycle-spacing' command.
869 The first time `cycle-spacing' runs, it saves in this variable:
870 its N argument, the original point position, and the original spacing
871 around point.")
873 (defun cycle-spacing (&optional n preserve-nl-back mode)
874 "Manipulate whitespace around point in a smart way.
875 In interactive use, this function behaves differently in successive
876 consecutive calls.
878 The first call in a sequence acts like `just-one-space'.
879 It deletes all spaces and tabs around point, leaving one space
880 \(or N spaces). N is the prefix argument. If N is negative,
881 it deletes newlines as well, leaving -N spaces.
882 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
884 The second call in a sequence deletes all spaces.
886 The third call in a sequence restores the original whitespace (and point).
888 If MODE is `single-shot', it only performs the first step in the sequence.
889 If MODE is `fast' and the first step would not result in any change
890 \(i.e., there are exactly (abs N) spaces around point),
891 the function goes straight to the second step.
893 Repeatedly calling the function with different values of N starts a
894 new sequence each time."
895 (interactive "*p")
896 (let ((orig-pos (point))
897 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
898 (num (abs (or n 1))))
899 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
900 (constrain-to-field nil orig-pos)
901 (cond
902 ;; Command run for the first time, single-shot mode or different argument
903 ((or (eq 'single-shot mode)
904 (not (equal last-command this-command))
905 (not cycle-spacing--context)
906 (not (eq (car cycle-spacing--context) n)))
907 (let* ((start (point))
908 (num (- num (skip-chars-forward " " (+ num (point)))))
909 (mid (point))
910 (end (progn
911 (skip-chars-forward skip-characters)
912 (constrain-to-field nil orig-pos t))))
913 (setq cycle-spacing--context ;; Save for later.
914 ;; Special handling for case where there was no space at all.
915 (unless (= start end)
916 (cons n (cons orig-pos (buffer-substring start (point))))))
917 ;; If this run causes no change in buffer content, delete all spaces,
918 ;; otherwise delete all excess spaces.
919 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
920 start mid) end)
921 (insert (make-string num ?\s))))
923 ;; Command run for the second time.
924 ((not (equal orig-pos (point)))
925 (delete-region (point) orig-pos))
927 ;; Command run for the third time.
929 (insert (cddr cycle-spacing--context))
930 (goto-char (cadr cycle-spacing--context))
931 (setq cycle-spacing--context nil)))))
933 (defun beginning-of-buffer (&optional arg)
934 "Move point to the beginning of the buffer.
935 With numeric arg N, put point N/10 of the way from the beginning.
936 If the buffer is narrowed, this command uses the beginning of the
937 accessible part of the buffer.
939 Push mark at previous position, unless either a \\[universal-argument] prefix
940 is supplied, or Transient Mark mode is enabled and the mark is active."
941 (declare (interactive-only "use `(goto-char (point-min))' instead."))
942 (interactive "^P")
943 (or (consp arg)
944 (region-active-p)
945 (push-mark))
946 (let ((size (- (point-max) (point-min))))
947 (goto-char (if (and arg (not (consp arg)))
948 (+ (point-min)
949 (if (> size 10000)
950 ;; Avoid overflow for large buffer sizes!
951 (* (prefix-numeric-value arg)
952 (/ size 10))
953 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
954 (point-min))))
955 (if (and arg (not (consp arg))) (forward-line 1)))
957 (defun end-of-buffer (&optional arg)
958 "Move point to the end of the buffer.
959 With numeric arg N, put point N/10 of the way from the end.
960 If the buffer is narrowed, this command uses the end of the
961 accessible part of the buffer.
963 Push mark at previous position, unless either a \\[universal-argument] prefix
964 is supplied, or Transient Mark mode is enabled and the mark is active."
965 (declare (interactive-only "use `(goto-char (point-max))' instead."))
966 (interactive "^P")
967 (or (consp arg) (region-active-p) (push-mark))
968 (let ((size (- (point-max) (point-min))))
969 (goto-char (if (and arg (not (consp arg)))
970 (- (point-max)
971 (if (> size 10000)
972 ;; Avoid overflow for large buffer sizes!
973 (* (prefix-numeric-value arg)
974 (/ size 10))
975 (/ (* size (prefix-numeric-value arg)) 10)))
976 (point-max))))
977 ;; If we went to a place in the middle of the buffer,
978 ;; adjust it to the beginning of a line.
979 (cond ((and arg (not (consp arg))) (forward-line 1))
980 ((and (eq (current-buffer) (window-buffer))
981 (> (point) (window-end nil t)))
982 ;; If the end of the buffer is not already on the screen,
983 ;; then scroll specially to put it near, but not at, the bottom.
984 (overlay-recenter (point))
985 (recenter -3))))
987 (defcustom delete-active-region t
988 "Whether single-char deletion commands delete an active region.
989 This has an effect only if Transient Mark mode is enabled, and
990 affects `delete-forward-char' and `delete-backward-char', though
991 not `delete-char'.
993 If the value is the symbol `kill', the active region is killed
994 instead of deleted."
995 :type '(choice (const :tag "Delete active region" t)
996 (const :tag "Kill active region" kill)
997 (const :tag "Do ordinary deletion" nil))
998 :group 'killing
999 :version "24.1")
1001 (defvar region-extract-function
1002 (lambda (method)
1003 (when (region-beginning)
1004 (cond
1005 ((eq method 'bounds)
1006 (list (cons (region-beginning) (region-end))))
1007 ((eq method 'delete-only)
1008 (delete-region (region-beginning) (region-end)))
1010 (filter-buffer-substring (region-beginning) (region-end) method)))))
1011 "Function to get the region's content.
1012 Called with one argument METHOD.
1013 If METHOD is `delete-only', then delete the region; the return value
1014 is undefined. If METHOD is nil, then return the content as a string.
1015 If METHOD is `bounds', then return the boundaries of the region
1016 as a list of cons cells of the form (START . END).
1017 If METHOD is anything else, delete the region and return its content
1018 as a string, after filtering it with `filter-buffer-substring', which
1019 is called with METHOD as its 3rd argument.")
1021 (defvar region-insert-function
1022 (lambda (lines)
1023 (let ((first t))
1024 (while lines
1025 (or first
1026 (insert ?\n))
1027 (insert-for-yank (car lines))
1028 (setq lines (cdr lines)
1029 first nil))))
1030 "Function to insert the region's content.
1031 Called with one argument LINES.
1032 Insert the region as a list of lines.")
1034 (defun delete-backward-char (n &optional killflag)
1035 "Delete the previous N characters (following if N is negative).
1036 If Transient Mark mode is enabled, the mark is active, and N is 1,
1037 delete the text in the region and deactivate the mark instead.
1038 To disable this, set option `delete-active-region' to nil.
1040 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1041 kill ring) instead of delete. Interactively, N is the prefix
1042 arg, and KILLFLAG is set if N is explicitly specified.
1044 When killing, the killed text is filtered by
1045 `filter-buffer-substring' before it is saved in the kill ring, so
1046 the actual saved text might be different from what was killed.
1048 In Overwrite mode, single character backward deletion may replace
1049 tabs with spaces so as to back over columns, unless point is at
1050 the end of the line."
1051 (declare (interactive-only delete-char))
1052 (interactive "p\nP")
1053 (unless (integerp n)
1054 (signal 'wrong-type-argument (list 'integerp n)))
1055 (cond ((and (use-region-p)
1056 delete-active-region
1057 (= n 1))
1058 ;; If a region is active, kill or delete it.
1059 (if (eq delete-active-region 'kill)
1060 (kill-region (region-beginning) (region-end) 'region)
1061 (funcall region-extract-function 'delete-only)))
1062 ;; In Overwrite mode, maybe untabify while deleting
1063 ((null (or (null overwrite-mode)
1064 (<= n 0)
1065 (memq (char-before) '(?\t ?\n))
1066 (eobp)
1067 (eq (char-after) ?\n)))
1068 (let ((ocol (current-column)))
1069 (delete-char (- n) killflag)
1070 (save-excursion
1071 (insert-char ?\s (- ocol (current-column)) nil))))
1072 ;; Otherwise, do simple deletion.
1073 (t (delete-char (- n) killflag))))
1075 (defun delete-forward-char (n &optional killflag)
1076 "Delete the following N characters (previous if N is negative).
1077 If Transient Mark mode is enabled, the mark is active, and N is 1,
1078 delete the text in the region and deactivate the mark instead.
1079 To disable this, set variable `delete-active-region' to nil.
1081 Optional second arg KILLFLAG non-nil means to kill (save in kill
1082 ring) instead of delete. Interactively, N is the prefix arg, and
1083 KILLFLAG is set if N was explicitly specified.
1085 When killing, the killed text is filtered by
1086 `filter-buffer-substring' before it is saved in the kill ring, so
1087 the actual saved text might be different from what was killed."
1088 (declare (interactive-only delete-char))
1089 (interactive "p\nP")
1090 (unless (integerp n)
1091 (signal 'wrong-type-argument (list 'integerp n)))
1092 (cond ((and (use-region-p)
1093 delete-active-region
1094 (= n 1))
1095 ;; If a region is active, kill or delete it.
1096 (if (eq delete-active-region 'kill)
1097 (kill-region (region-beginning) (region-end) 'region)
1098 (funcall region-extract-function 'delete-only)))
1100 ;; Otherwise, do simple deletion.
1101 (t (delete-char n killflag))))
1103 (defun mark-whole-buffer ()
1104 "Put point at beginning and mark at end of buffer.
1105 If narrowing is in effect, only uses the accessible part of the buffer.
1106 You probably should not use this function in Lisp programs;
1107 it is usually a mistake for a Lisp function to use any subroutine
1108 that uses or sets the mark."
1109 (declare (interactive-only t))
1110 (interactive)
1111 (push-mark)
1112 (push-mark (point-max) nil t)
1113 ;; This is really `point-min' in most cases, but if we're in the
1114 ;; minibuffer, this is at the end of the prompt.
1115 (goto-char (minibuffer-prompt-end)))
1118 ;; Counting lines, one way or another.
1120 (defun goto-line (line &optional buffer)
1121 "Go to LINE, counting from line 1 at beginning of buffer.
1122 If called interactively, a numeric prefix argument specifies
1123 LINE; without a numeric prefix argument, read LINE from the
1124 minibuffer.
1126 If optional argument BUFFER is non-nil, switch to that buffer and
1127 move to line LINE there. If called interactively with \\[universal-argument]
1128 as argument, BUFFER is the most recently selected other buffer.
1130 Prior to moving point, this function sets the mark (without
1131 activating it), unless Transient Mark mode is enabled and the
1132 mark is already active.
1134 This function is usually the wrong thing to use in a Lisp program.
1135 What you probably want instead is something like:
1136 (goto-char (point-min))
1137 (forward-line (1- N))
1138 If at all possible, an even better solution is to use char counts
1139 rather than line counts."
1140 (declare (interactive-only forward-line))
1141 (interactive
1142 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1143 (list (prefix-numeric-value current-prefix-arg))
1144 ;; Look for a default, a number in the buffer at point.
1145 (let* ((default
1146 (save-excursion
1147 (skip-chars-backward "0-9")
1148 (if (looking-at "[0-9]")
1149 (string-to-number
1150 (buffer-substring-no-properties
1151 (point)
1152 (progn (skip-chars-forward "0-9")
1153 (point)))))))
1154 ;; Decide if we're switching buffers.
1155 (buffer
1156 (if (consp current-prefix-arg)
1157 (other-buffer (current-buffer) t)))
1158 (buffer-prompt
1159 (if buffer
1160 (concat " in " (buffer-name buffer))
1161 "")))
1162 ;; Read the argument, offering that number (if any) as default.
1163 (list (read-number (format "Goto line%s: " buffer-prompt)
1164 (list default (line-number-at-pos)))
1165 buffer))))
1166 ;; Switch to the desired buffer, one way or another.
1167 (if buffer
1168 (let ((window (get-buffer-window buffer)))
1169 (if window (select-window window)
1170 (switch-to-buffer-other-window buffer))))
1171 ;; Leave mark at previous position
1172 (or (region-active-p) (push-mark))
1173 ;; Move to the specified line number in that buffer.
1174 (save-restriction
1175 (widen)
1176 (goto-char (point-min))
1177 (if (eq selective-display t)
1178 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1179 (forward-line (1- line)))))
1181 (defun count-words-region (start end &optional arg)
1182 "Count the number of words in the region.
1183 If called interactively, print a message reporting the number of
1184 lines, words, and characters in the region (whether or not the
1185 region is active); with prefix ARG, report for the entire buffer
1186 rather than the region.
1188 If called from Lisp, return the number of words between positions
1189 START and END."
1190 (interactive (if current-prefix-arg
1191 (list nil nil current-prefix-arg)
1192 (list (region-beginning) (region-end) nil)))
1193 (cond ((not (called-interactively-p 'any))
1194 (count-words start end))
1195 (arg
1196 (count-words--buffer-message))
1198 (count-words--message "Region" start end))))
1200 (defun count-words (start end)
1201 "Count words between START and END.
1202 If called interactively, START and END are normally the start and
1203 end of the buffer; but if the region is active, START and END are
1204 the start and end of the region. Print a message reporting the
1205 number of lines, words, and chars.
1207 If called from Lisp, return the number of words between START and
1208 END, without printing any message."
1209 (interactive (list nil nil))
1210 (cond ((not (called-interactively-p 'any))
1211 (let ((words 0))
1212 (save-excursion
1213 (save-restriction
1214 (narrow-to-region start end)
1215 (goto-char (point-min))
1216 (while (forward-word-strictly 1)
1217 (setq words (1+ words)))))
1218 words))
1219 ((use-region-p)
1220 (call-interactively 'count-words-region))
1222 (count-words--buffer-message))))
1224 (defun count-words--buffer-message ()
1225 (count-words--message
1226 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1227 (point-min) (point-max)))
1229 (defun count-words--message (str start end)
1230 (let ((lines (count-lines start end))
1231 (words (count-words start end))
1232 (chars (- end start)))
1233 (message "%s has %d line%s, %d word%s, and %d character%s."
1235 lines (if (= lines 1) "" "s")
1236 words (if (= words 1) "" "s")
1237 chars (if (= chars 1) "" "s"))))
1239 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1241 (defun what-line ()
1242 "Print the current buffer line number and narrowed line number of point."
1243 (interactive)
1244 (let ((start (point-min))
1245 (n (line-number-at-pos)))
1246 (if (= start 1)
1247 (message "Line %d" n)
1248 (save-excursion
1249 (save-restriction
1250 (widen)
1251 (message "line %d (narrowed line %d)"
1252 (+ n (line-number-at-pos start) -1) n))))))
1254 (defun count-lines (start end)
1255 "Return number of lines between START and END.
1256 This is usually the number of newlines between them,
1257 but can be one more if START is not equal to END
1258 and the greater of them is not at the start of a line."
1259 (save-excursion
1260 (save-restriction
1261 (narrow-to-region start end)
1262 (goto-char (point-min))
1263 (if (eq selective-display t)
1264 (save-match-data
1265 (let ((done 0))
1266 (while (re-search-forward "[\n\C-m]" nil t 40)
1267 (setq done (+ 40 done)))
1268 (while (re-search-forward "[\n\C-m]" nil t 1)
1269 (setq done (+ 1 done)))
1270 (goto-char (point-max))
1271 (if (and (/= start end)
1272 (not (bolp)))
1273 (1+ done)
1274 done)))
1275 (- (buffer-size) (forward-line (buffer-size)))))))
1277 (defun line-number-at-pos (&optional pos absolute)
1278 "Return buffer line number at position POS.
1279 If POS is nil, use current buffer location.
1281 If ABSOLUTE is nil, the default, counting starts
1282 at (point-min), so the value refers to the contents of the
1283 accessible portion of the (potentially narrowed) buffer. If
1284 ABSOLUTE is non-nil, ignore any narrowing and return the
1285 absolute line number."
1286 (save-restriction
1287 (when absolute
1288 (widen))
1289 (let ((opoint (or pos (point))) start)
1290 (save-excursion
1291 (goto-char (point-min))
1292 (setq start (point))
1293 (goto-char opoint)
1294 (forward-line 0)
1295 (1+ (count-lines start (point)))))))
1297 (defun what-cursor-position (&optional detail)
1298 "Print info on cursor position (on screen and within buffer).
1299 Also describe the character after point, and give its character code
1300 in octal, decimal and hex.
1302 For a non-ASCII multibyte character, also give its encoding in the
1303 buffer's selected coding system if the coding system encodes the
1304 character safely. If the character is encoded into one byte, that
1305 code is shown in hex. If the character is encoded into more than one
1306 byte, just \"...\" is shown.
1308 In addition, with prefix argument, show details about that character
1309 in *Help* buffer. See also the command `describe-char'."
1310 (interactive "P")
1311 (let* ((char (following-char))
1312 (bidi-fixer
1313 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1314 ;; start a directional embedding, which could completely
1315 ;; disrupt the rest of the line (e.g., RLO will display the
1316 ;; rest of the line right-to-left). So we put an invisible
1317 ;; PDF character after these characters, to end the
1318 ;; embedding, which eliminates any effects on the rest of
1319 ;; the line. For RLE and RLO we also append an invisible
1320 ;; LRM, to avoid reordering the following numerical
1321 ;; characters. For LRI/RLI/FSI we append a PDI.
1322 (cond ((memq char '(?\x202a ?\x202d))
1323 (propertize (string ?\x202c) 'invisible t))
1324 ((memq char '(?\x202b ?\x202e))
1325 (propertize (string ?\x202c ?\x200e) 'invisible t))
1326 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1327 (propertize (string ?\x2069) 'invisible t))
1328 ;; Strong right-to-left characters cause reordering of
1329 ;; the following numerical characters which show the
1330 ;; codepoint, so append LRM to countermand that.
1331 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1332 (propertize (string ?\x200e) 'invisible t))
1334 "")))
1335 (beg (point-min))
1336 (end (point-max))
1337 (pos (point))
1338 (total (buffer-size))
1339 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1340 (hscroll (if (= (window-hscroll) 0)
1342 (format " Hscroll=%d" (window-hscroll))))
1343 (col (current-column)))
1344 (if (= pos end)
1345 (if (or (/= beg 1) (/= end (1+ total)))
1346 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1347 pos total percent beg end col hscroll)
1348 (message "point=%d of %d (EOB) column=%d%s"
1349 pos total col hscroll))
1350 (let ((coding buffer-file-coding-system)
1351 encoded encoding-msg display-prop under-display)
1352 (if (or (not coding)
1353 (eq (coding-system-type coding) t))
1354 (setq coding (default-value 'buffer-file-coding-system)))
1355 (if (eq (char-charset char) 'eight-bit)
1356 (setq encoding-msg
1357 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1358 ;; Check if the character is displayed with some `display'
1359 ;; text property. In that case, set under-display to the
1360 ;; buffer substring covered by that property.
1361 (setq display-prop (get-char-property pos 'display))
1362 (if display-prop
1363 (let ((to (or (next-single-char-property-change pos 'display)
1364 (point-max))))
1365 (if (< to (+ pos 4))
1366 (setq under-display "")
1367 (setq under-display "..."
1368 to (+ pos 4)))
1369 (setq under-display
1370 (concat (buffer-substring-no-properties pos to)
1371 under-display)))
1372 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1373 (setq encoding-msg
1374 (if display-prop
1375 (if (not (stringp display-prop))
1376 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1377 char char char under-display)
1378 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1379 char char char under-display display-prop))
1380 (if encoded
1381 (format "(%d, #o%o, #x%x, file %s)"
1382 char char char
1383 (if (> (length encoded) 1)
1384 "..."
1385 (encoded-string-description encoded coding)))
1386 (format "(%d, #o%o, #x%x)" char char char)))))
1387 (if detail
1388 ;; We show the detailed information about CHAR.
1389 (describe-char (point)))
1390 (if (or (/= beg 1) (/= end (1+ total)))
1391 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1392 (if (< char 256)
1393 (single-key-description char)
1394 (buffer-substring-no-properties (point) (1+ (point))))
1395 bidi-fixer
1396 encoding-msg pos total percent beg end col hscroll)
1397 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1398 (if enable-multibyte-characters
1399 (if (< char 128)
1400 (single-key-description char)
1401 (buffer-substring-no-properties (point) (1+ (point))))
1402 (single-key-description char))
1403 bidi-fixer encoding-msg pos total percent col hscroll))))))
1405 ;; Initialize read-expression-map. It is defined at C level.
1406 (defvar read-expression-map
1407 (let ((m (make-sparse-keymap)))
1408 (define-key m "\M-\t" 'completion-at-point)
1409 ;; Might as well bind TAB to completion, since inserting a TAB char is
1410 ;; much too rarely useful.
1411 (define-key m "\t" 'completion-at-point)
1412 (set-keymap-parent m minibuffer-local-map)
1415 (defun read-minibuffer (prompt &optional initial-contents)
1416 "Return a Lisp object read using the minibuffer, unevaluated.
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 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1423 t 'minibuffer-history))
1425 (defun eval-minibuffer (prompt &optional initial-contents)
1426 "Return value of Lisp expression read using the minibuffer.
1427 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1428 is a string to insert in the minibuffer before reading.
1429 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1430 Such arguments are used as in `read-from-minibuffer'.)"
1431 ;; Used for interactive spec `X'.
1432 (eval (read--expression prompt initial-contents)))
1434 (defvar minibuffer-completing-symbol nil
1435 "Non-nil means completing a Lisp symbol in the minibuffer.")
1436 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1438 (defvar minibuffer-default nil
1439 "The current default value or list of default values in the minibuffer.
1440 The functions `read-from-minibuffer' and `completing-read' bind
1441 this variable locally.")
1443 (defcustom eval-expression-print-level 4
1444 "Value for `print-level' while printing value in `eval-expression'.
1445 A value of nil means no limit."
1446 :group 'lisp
1447 :type '(choice (const :tag "No Limit" nil) integer)
1448 :version "21.1")
1450 (defcustom eval-expression-print-length 12
1451 "Value for `print-length' while printing value in `eval-expression'.
1452 A value of nil means no limit."
1453 :group 'lisp
1454 :type '(choice (const :tag "No Limit" nil) integer)
1455 :version "21.1")
1457 (defcustom eval-expression-debug-on-error t
1458 "If non-nil set `debug-on-error' to t in `eval-expression'.
1459 If nil, don't change the value of `debug-on-error'."
1460 :group 'lisp
1461 :type 'boolean
1462 :version "21.1")
1464 (defcustom eval-expression-print-maximum-character 127
1465 "The largest integer that will be displayed as a character.
1466 This affects printing by `eval-expression' (via
1467 `eval-expression-print-format')."
1468 :group 'lisp
1469 :type 'integer
1470 :version "26.1")
1472 (defun eval-expression-print-format (value)
1473 "If VALUE in an integer, return a specially formatted string.
1474 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1475 If VALUE is not an integer, nil is returned.
1476 This function is used by commands like `eval-expression' that
1477 display the result of expression evaluation."
1478 (when (integerp value)
1479 (let ((char-string
1480 (and (characterp value)
1481 (<= value eval-expression-print-maximum-character)
1482 (char-displayable-p value)
1483 (prin1-char value))))
1484 (if char-string
1485 (format " (#o%o, #x%x, %s)" value value char-string)
1486 (format " (#o%o, #x%x)" value value)))))
1488 (defvar eval-expression-minibuffer-setup-hook nil
1489 "Hook run by `eval-expression' when entering the minibuffer.")
1491 (defun read--expression (prompt &optional initial-contents)
1492 (let ((minibuffer-completing-symbol t))
1493 (minibuffer-with-setup-hook
1494 (lambda ()
1495 ;; FIXME: call emacs-lisp-mode?
1496 (add-function :before-until (local 'eldoc-documentation-function)
1497 #'elisp-eldoc-documentation-function)
1498 (eldoc-mode 1)
1499 (add-hook 'completion-at-point-functions
1500 #'elisp-completion-at-point nil t)
1501 (run-hooks 'eval-expression-minibuffer-setup-hook))
1502 (read-from-minibuffer prompt initial-contents
1503 read-expression-map t
1504 'read-expression-history))))
1506 (defun eval-expression-get-print-arguments (prefix-argument)
1507 "Get arguments for commands that print an expression result.
1508 Returns a list (INSERT-VALUE NO-TRUNCATE CHAR-PRINT-LIMIT)
1509 based on PREFIX-ARG. This function determines the interpretation
1510 of the prefix argument for `eval-expression' and
1511 `eval-last-sexp'."
1512 (let ((num (prefix-numeric-value prefix-argument)))
1513 (list (not (memq prefix-argument '(- nil)))
1514 (= num 0)
1515 (cond ((not (memq prefix-argument '(0 -1 - nil))) nil)
1516 ((= num -1) most-positive-fixnum)
1517 (t eval-expression-print-maximum-character)))))
1519 ;; We define this, rather than making `eval' interactive,
1520 ;; for the sake of completion of names like eval-region, eval-buffer.
1521 (defun eval-expression (exp &optional insert-value no-truncate char-print-limit)
1522 "Evaluate EXP and print value in the echo area.
1523 When called interactively, read an Emacs Lisp expression and
1524 evaluate it. Value is also consed on to front of the variable
1525 `values'. Optional argument INSERT-VALUE non-nil (interactively,
1526 with a non `-' prefix argument) means insert the result into the
1527 current buffer instead of printing it in the echo area.
1529 Normally, this function truncates long output according to the
1530 value of the variables `eval-expression-print-length' and
1531 `eval-expression-print-level'. When NO-TRUNCATE is
1532 non-nil (interactively, with a prefix argument of zero), however,
1533 there is no such truncation.
1535 If the resulting value is an integer, and CHAR-PRINT-LIMIT is
1536 non-nil (interactively, unless given a positive prefix argument)
1537 it will be printed in several additional formats (octal,
1538 hexadecimal, and character). The character format is only used
1539 if the value is below CHAR-PRINT-LIMIT (interactively, if the
1540 prefix argument is -1 or the value is below
1541 `eval-expression-print-maximum-character').
1543 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1544 minibuffer.
1546 If `eval-expression-debug-on-error' is non-nil, which is the default,
1547 this command arranges for all errors to enter the debugger."
1548 (interactive
1549 (cons (read--expression "Eval: ")
1550 (eval-expression-get-print-arguments current-prefix-arg)))
1552 (if (null eval-expression-debug-on-error)
1553 (push (eval exp lexical-binding) values)
1554 (let ((old-value (make-symbol "t")) new-value)
1555 ;; Bind debug-on-error to something unique so that we can
1556 ;; detect when evalled code changes it.
1557 (let ((debug-on-error old-value))
1558 (push (eval (macroexpand-all exp) lexical-binding) values)
1559 (setq new-value debug-on-error))
1560 ;; If evalled code has changed the value of debug-on-error,
1561 ;; propagate that change to the global binding.
1562 (unless (eq old-value new-value)
1563 (setq debug-on-error new-value))))
1565 (let ((print-length (unless no-truncate eval-expression-print-length))
1566 (print-level (unless no-truncate eval-expression-print-level))
1567 (eval-expression-print-maximum-character char-print-limit)
1568 (deactivate-mark))
1569 (let ((out (if insert-value (current-buffer) t)))
1570 (prog1
1571 (prin1 (car values) out)
1572 (let ((str (and char-print-limit
1573 (eval-expression-print-format (car values)))))
1574 (when str (princ str out)))))))
1576 (defun edit-and-eval-command (prompt command)
1577 "Prompting with PROMPT, let user edit COMMAND and eval result.
1578 COMMAND is a Lisp expression. Let user edit that expression in
1579 the minibuffer, then read and evaluate the result."
1580 (let ((command
1581 (let ((print-level nil)
1582 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1583 (unwind-protect
1584 (read-from-minibuffer prompt
1585 (prin1-to-string command)
1586 read-expression-map t
1587 'command-history)
1588 ;; If command was added to command-history as a string,
1589 ;; get rid of that. We want only evaluable expressions there.
1590 (if (stringp (car command-history))
1591 (setq command-history (cdr command-history)))))))
1593 ;; If command to be redone does not match front of history,
1594 ;; add it to the history.
1595 (or (equal command (car command-history))
1596 (setq command-history (cons command command-history)))
1597 (eval command)))
1599 (defun repeat-complex-command (arg)
1600 "Edit and re-evaluate last complex command, or ARGth from last.
1601 A complex command is one which used the minibuffer.
1602 The command is placed in the minibuffer as a Lisp form for editing.
1603 The result is executed, repeating the command as changed.
1604 If the command has been changed or is not the most recent previous
1605 command it is added to the front of the command history.
1606 You can use the minibuffer history commands \
1607 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1608 to get different commands to edit and resubmit."
1609 (interactive "p")
1610 (let ((elt (nth (1- arg) command-history))
1611 newcmd)
1612 (if elt
1613 (progn
1614 (setq newcmd
1615 (let ((print-level nil)
1616 (minibuffer-history-position arg)
1617 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1618 (unwind-protect
1619 (read-from-minibuffer
1620 "Redo: " (prin1-to-string elt) read-expression-map t
1621 (cons 'command-history arg))
1623 ;; If command was added to command-history as a
1624 ;; string, get rid of that. We want only
1625 ;; evaluable expressions there.
1626 (if (stringp (car command-history))
1627 (setq command-history (cdr command-history))))))
1629 ;; If command to be redone does not match front of history,
1630 ;; add it to the history.
1631 (or (equal newcmd (car command-history))
1632 (setq command-history (cons newcmd command-history)))
1633 (apply #'funcall-interactively
1634 (car newcmd)
1635 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1636 (if command-history
1637 (error "Argument %d is beyond length of command history" arg)
1638 (error "There are no previous complex commands to repeat")))))
1641 (defvar extended-command-history nil)
1642 (defvar execute-extended-command--last-typed nil)
1644 (defun read-extended-command ()
1645 "Read command name to invoke in `execute-extended-command'."
1646 (minibuffer-with-setup-hook
1647 (lambda ()
1648 (add-hook 'post-self-insert-hook
1649 (lambda ()
1650 (setq execute-extended-command--last-typed
1651 (minibuffer-contents)))
1652 nil 'local)
1653 (set (make-local-variable 'minibuffer-default-add-function)
1654 (lambda ()
1655 ;; Get a command name at point in the original buffer
1656 ;; to propose it after M-n.
1657 (with-current-buffer (window-buffer (minibuffer-selected-window))
1658 (and (commandp (function-called-at-point))
1659 (format "%S" (function-called-at-point)))))))
1660 ;; Read a string, completing from and restricting to the set of
1661 ;; all defined commands. Don't provide any initial input.
1662 ;; Save the command read on the extended-command history list.
1663 (completing-read
1664 (concat (cond
1665 ((eq current-prefix-arg '-) "- ")
1666 ((and (consp current-prefix-arg)
1667 (eq (car current-prefix-arg) 4)) "C-u ")
1668 ((and (consp current-prefix-arg)
1669 (integerp (car current-prefix-arg)))
1670 (format "%d " (car current-prefix-arg)))
1671 ((integerp current-prefix-arg)
1672 (format "%d " current-prefix-arg)))
1673 ;; This isn't strictly correct if `execute-extended-command'
1674 ;; is bound to anything else (e.g. [menu]).
1675 ;; It could use (key-description (this-single-command-keys)),
1676 ;; but actually a prompt other than "M-x" would be confusing,
1677 ;; because "M-x" is a well-known prompt to read a command
1678 ;; and it serves as a shorthand for "Extended command: ".
1679 "M-x ")
1680 (lambda (string pred action)
1681 (let ((pred
1682 (if (memq action '(nil t))
1683 ;; Exclude obsolete commands from completions.
1684 (lambda (sym)
1685 (and (funcall pred sym)
1686 (or (equal string (symbol-name sym))
1687 (not (get sym 'byte-obsolete-info)))))
1688 pred)))
1689 (complete-with-action action obarray string pred)))
1690 #'commandp t nil 'extended-command-history)))
1692 (defcustom suggest-key-bindings t
1693 "Non-nil means show the equivalent key-binding when M-x command has one.
1694 The value can be a length of time to show the message for.
1695 If the value is non-nil and not a number, we wait 2 seconds."
1696 :group 'keyboard
1697 :type '(choice (const :tag "off" nil)
1698 (integer :tag "time" 2)
1699 (other :tag "on")))
1701 (defcustom extended-command-suggest-shorter t
1702 "If non-nil, show a shorter M-x invocation when there is one."
1703 :group 'keyboard
1704 :type 'boolean
1705 :version "26.1")
1707 (defun execute-extended-command--shorter-1 (name length)
1708 (cond
1709 ((zerop length) (list ""))
1710 ((equal name "") nil)
1712 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1713 (execute-extended-command--shorter-1
1714 (substring name 1) (1- length)))
1715 (when (string-match "\\`\\(-\\)?[^-]*" name)
1716 (execute-extended-command--shorter-1
1717 (substring name (match-end 0)) length))))))
1719 (defun execute-extended-command--shorter (name typed)
1720 (let ((candidates '())
1721 (max (length typed))
1722 (len 1)
1723 binding)
1724 (while (and (not binding)
1725 (progn
1726 (unless candidates
1727 (setq len (1+ len))
1728 (setq candidates (execute-extended-command--shorter-1
1729 name len)))
1730 ;; Don't show the help message if the binding isn't
1731 ;; significantly shorter than the M-x command the user typed.
1732 (< len (- max 5))))
1733 (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
1734 (let ((candidate (pop candidates)))
1735 (when (equal name
1736 (car-safe (completion-try-completion
1737 candidate obarray 'commandp len)))
1738 (setq binding candidate))))
1739 binding))
1741 (defun execute-extended-command (prefixarg &optional command-name typed)
1742 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1743 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1744 "Read a command name, then read the arguments and call the command.
1745 To pass a prefix argument to the command you are
1746 invoking, give a prefix argument to `execute-extended-command'."
1747 (declare (interactive-only command-execute))
1748 ;; FIXME: Remember the actual text typed by the user before completion,
1749 ;; so that we don't later on suggest the same shortening.
1750 (interactive
1751 (let ((execute-extended-command--last-typed nil))
1752 (list current-prefix-arg
1753 (read-extended-command)
1754 execute-extended-command--last-typed)))
1755 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1756 (unless command-name
1757 (let ((current-prefix-arg prefixarg) ; for prompt
1758 (execute-extended-command--last-typed nil))
1759 (setq command-name (read-extended-command))
1760 (setq typed execute-extended-command--last-typed)))
1761 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1762 (binding (and suggest-key-bindings
1763 (not executing-kbd-macro)
1764 (where-is-internal function overriding-local-map t))))
1765 (unless (commandp function)
1766 (error "`%s' is not a valid command name" command-name))
1767 ;; Some features, such as novice.el, rely on this-command-keys
1768 ;; including M-x COMMAND-NAME RET.
1769 (set--this-command-keys (concat "\M-x" (symbol-name function) "\r"))
1770 (setq this-command function)
1771 ;; Normally `real-this-command' should never be changed, but here we really
1772 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1773 ;; binding" for <cmd>, so the command the user really wanted to run is
1774 ;; `function' and not `execute-extended-command'. The difference is
1775 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1776 (setq real-this-command function)
1777 (let ((prefix-arg prefixarg))
1778 (command-execute function 'record))
1779 ;; If enabled, show which key runs this command.
1780 ;; But first wait, and skip the message if there is input.
1781 (let* ((waited
1782 ;; If this command displayed something in the echo area;
1783 ;; wait a few seconds, then display our suggestion message.
1784 ;; FIXME: Wait *after* running post-command-hook!
1785 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1786 ;; find a better answer anyway!
1787 (when suggest-key-bindings
1788 (sit-for (cond
1789 ((zerop (length (current-message))) 0)
1790 ((numberp suggest-key-bindings) suggest-key-bindings)
1791 (t 2))))))
1792 (when (and waited (not (consp unread-command-events)))
1793 (unless (or (not extended-command-suggest-shorter)
1794 binding executing-kbd-macro (not (symbolp function))
1795 (<= (length (symbol-name function)) 2))
1796 ;; There's no binding for CMD. Let's try and find the shortest
1797 ;; string to use in M-x.
1798 ;; FIXME: Can be slow. Cache it maybe?
1799 (while-no-input
1800 (setq binding (execute-extended-command--shorter
1801 (symbol-name function) typed))))
1802 (when binding
1803 (with-temp-message
1804 (format-message "You can run the command `%s' with %s"
1805 function
1806 (if (stringp binding)
1807 (concat "M-x " binding " RET")
1808 (key-description binding)))
1809 (sit-for (if (numberp suggest-key-bindings)
1810 suggest-key-bindings
1811 2))))))))
1813 (defun command-execute (cmd &optional record-flag keys special)
1814 ;; BEWARE: Called directly from the C code.
1815 "Execute CMD as an editor command.
1816 CMD must be a symbol that satisfies the `commandp' predicate.
1817 Optional second arg RECORD-FLAG non-nil
1818 means unconditionally put this command in the variable `command-history'.
1819 Otherwise, that is done only if an arg is read using the minibuffer.
1820 The argument KEYS specifies the value to use instead of (this-command-keys)
1821 when reading the arguments; if it is nil, (this-command-keys) is used.
1822 The argument SPECIAL, if non-nil, means that this command is executing
1823 a special event, so ignore the prefix argument and don't clear it."
1824 (setq debug-on-next-call nil)
1825 (let ((prefixarg (unless special
1826 ;; FIXME: This should probably be done around
1827 ;; pre-command-hook rather than here!
1828 (prog1 prefix-arg
1829 (setq current-prefix-arg prefix-arg)
1830 (setq prefix-arg nil)
1831 (when current-prefix-arg
1832 (prefix-command-update))))))
1833 (if (and (symbolp cmd)
1834 (get cmd 'disabled)
1835 disabled-command-function)
1836 ;; FIXME: Weird calling convention!
1837 (run-hooks 'disabled-command-function)
1838 (let ((final cmd))
1839 (while
1840 (progn
1841 (setq final (indirect-function final))
1842 (if (autoloadp final)
1843 (setq final (autoload-do-load final cmd)))))
1844 (cond
1845 ((arrayp final)
1846 ;; If requested, place the macro in the command history. For
1847 ;; other sorts of commands, call-interactively takes care of this.
1848 (when record-flag
1849 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1850 ;; Don't keep command history around forever.
1851 (when (and (numberp history-length) (> history-length 0))
1852 (let ((cell (nthcdr history-length command-history)))
1853 (if (consp cell) (setcdr cell nil)))))
1854 (execute-kbd-macro final prefixarg))
1856 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1857 (prog1 (call-interactively cmd record-flag keys)
1858 (when (and (symbolp cmd)
1859 (get cmd 'byte-obsolete-info)
1860 (not (get cmd 'command-execute-obsolete-warned)))
1861 (put cmd 'command-execute-obsolete-warned t)
1862 (message "%s" (macroexp--obsolete-warning
1863 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1865 (defvar minibuffer-history nil
1866 "Default minibuffer history list.
1867 This is used for all minibuffer input
1868 except when an alternate history list is specified.
1870 Maximum length of the history list is determined by the value
1871 of `history-length', which see.")
1872 (defvar minibuffer-history-sexp-flag nil
1873 "Control whether history list elements are expressions or strings.
1874 If the value of this variable equals current minibuffer depth,
1875 they are expressions; otherwise they are strings.
1876 \(That convention is designed to do the right thing for
1877 recursive uses of the minibuffer.)")
1878 (setq minibuffer-history-variable 'minibuffer-history)
1879 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1880 (defvar minibuffer-history-search-history nil)
1882 (defvar minibuffer-text-before-history nil
1883 "Text that was in this minibuffer before any history commands.
1884 This is nil if there have not yet been any history commands
1885 in this use of the minibuffer.")
1887 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1889 (defun minibuffer-history-initialize ()
1890 (setq minibuffer-text-before-history nil))
1892 (defun minibuffer-avoid-prompt (_new _old)
1893 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1894 (declare (obsolete cursor-intangible-mode "25.1"))
1895 (constrain-to-field nil (point-max)))
1897 (defcustom minibuffer-history-case-insensitive-variables nil
1898 "Minibuffer history variables for which matching should ignore case.
1899 If a history variable is a member of this list, then the
1900 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1901 commands ignore case when searching it, regardless of `case-fold-search'."
1902 :type '(repeat variable)
1903 :group 'minibuffer)
1905 (defun previous-matching-history-element (regexp n)
1906 "Find the previous history element that matches REGEXP.
1907 \(Previous history elements refer to earlier actions.)
1908 With prefix argument N, search for Nth previous match.
1909 If N is negative, find the next or Nth next match.
1910 Normally, history elements are matched case-insensitively if
1911 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1912 makes the search case-sensitive.
1913 See also `minibuffer-history-case-insensitive-variables'."
1914 (interactive
1915 (let* ((enable-recursive-minibuffers t)
1916 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1918 minibuffer-local-map
1920 'minibuffer-history-search-history
1921 (car minibuffer-history-search-history))))
1922 ;; Use the last regexp specified, by default, if input is empty.
1923 (list (if (string= regexp "")
1924 (if minibuffer-history-search-history
1925 (car minibuffer-history-search-history)
1926 (user-error "No previous history search regexp"))
1927 regexp)
1928 (prefix-numeric-value current-prefix-arg))))
1929 (unless (zerop n)
1930 (if (and (zerop minibuffer-history-position)
1931 (null minibuffer-text-before-history))
1932 (setq minibuffer-text-before-history
1933 (minibuffer-contents-no-properties)))
1934 (let ((history (symbol-value minibuffer-history-variable))
1935 (case-fold-search
1936 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1937 ;; On some systems, ignore case for file names.
1938 (if (memq minibuffer-history-variable
1939 minibuffer-history-case-insensitive-variables)
1941 ;; Respect the user's setting for case-fold-search:
1942 case-fold-search)
1943 nil))
1944 prevpos
1945 match-string
1946 match-offset
1947 (pos minibuffer-history-position))
1948 (while (/= n 0)
1949 (setq prevpos pos)
1950 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1951 (when (= pos prevpos)
1952 (user-error (if (= pos 1)
1953 "No later matching history item"
1954 "No earlier matching history item")))
1955 (setq match-string
1956 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1957 (let ((print-level nil))
1958 (prin1-to-string (nth (1- pos) history)))
1959 (nth (1- pos) history)))
1960 (setq match-offset
1961 (if (< n 0)
1962 (and (string-match regexp match-string)
1963 (match-end 0))
1964 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1965 (match-beginning 1))))
1966 (when match-offset
1967 (setq n (+ n (if (< n 0) 1 -1)))))
1968 (setq minibuffer-history-position pos)
1969 (goto-char (point-max))
1970 (delete-minibuffer-contents)
1971 (insert match-string)
1972 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1973 (if (memq (car (car command-history)) '(previous-matching-history-element
1974 next-matching-history-element))
1975 (setq command-history (cdr command-history))))
1977 (defun next-matching-history-element (regexp n)
1978 "Find the next history element that matches REGEXP.
1979 \(The next history element refers to a more recent action.)
1980 With prefix argument N, search for Nth next match.
1981 If N is negative, find the previous or Nth previous match.
1982 Normally, history elements are matched case-insensitively if
1983 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1984 makes the search case-sensitive."
1985 (interactive
1986 (let* ((enable-recursive-minibuffers t)
1987 (regexp (read-from-minibuffer "Next element matching (regexp): "
1989 minibuffer-local-map
1991 'minibuffer-history-search-history
1992 (car minibuffer-history-search-history))))
1993 ;; Use the last regexp specified, by default, if input is empty.
1994 (list (if (string= regexp "")
1995 (if minibuffer-history-search-history
1996 (car minibuffer-history-search-history)
1997 (user-error "No previous history search regexp"))
1998 regexp)
1999 (prefix-numeric-value current-prefix-arg))))
2000 (previous-matching-history-element regexp (- n)))
2002 (defvar minibuffer-temporary-goal-position nil)
2004 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
2005 "Function run by `goto-history-element' before consuming default values.
2006 This is useful to dynamically add more elements to the list of default values
2007 when `goto-history-element' reaches the end of this list.
2008 Before calling this function `goto-history-element' sets the variable
2009 `minibuffer-default-add-done' to t, so it will call this function only
2010 once. In special cases, when this function needs to be called more
2011 than once, it can set `minibuffer-default-add-done' to nil explicitly,
2012 overriding the setting of this variable to t in `goto-history-element'.")
2014 (defvar minibuffer-default-add-done nil
2015 "When nil, add more elements to the end of the list of default values.
2016 The value nil causes `goto-history-element' to add more elements to
2017 the list of defaults when it reaches the end of this list. It does
2018 this by calling a function defined by `minibuffer-default-add-function'.")
2020 (make-variable-buffer-local 'minibuffer-default-add-done)
2022 (defun minibuffer-default-add-completions ()
2023 "Return a list of all completions without the default value.
2024 This function is used to add all elements of the completion table to
2025 the end of the list of defaults just after the default value."
2026 (let ((def minibuffer-default)
2027 (all (all-completions ""
2028 minibuffer-completion-table
2029 minibuffer-completion-predicate)))
2030 (if (listp def)
2031 (append def all)
2032 (cons def (delete def all)))))
2034 (defun goto-history-element (nabs)
2035 "Puts element of the minibuffer history in the minibuffer.
2036 The argument NABS specifies the absolute history position."
2037 (interactive "p")
2038 (when (and (not minibuffer-default-add-done)
2039 (functionp minibuffer-default-add-function)
2040 (< nabs (- (if (listp minibuffer-default)
2041 (length minibuffer-default)
2042 1))))
2043 (setq minibuffer-default-add-done t
2044 minibuffer-default (funcall minibuffer-default-add-function)))
2045 (let ((minimum (if minibuffer-default
2046 (- (if (listp minibuffer-default)
2047 (length minibuffer-default)
2050 elt minibuffer-returned-to-present)
2051 (if (and (zerop minibuffer-history-position)
2052 (null minibuffer-text-before-history))
2053 (setq minibuffer-text-before-history
2054 (minibuffer-contents-no-properties)))
2055 (if (< nabs minimum)
2056 (user-error (if minibuffer-default
2057 "End of defaults; no next item"
2058 "End of history; no default available")))
2059 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
2060 (length (symbol-value minibuffer-history-variable))
2062 (user-error "Beginning of history; no preceding item"))
2063 (unless (memq last-command '(next-history-element
2064 previous-history-element))
2065 (let ((prompt-end (minibuffer-prompt-end)))
2066 (set (make-local-variable 'minibuffer-temporary-goal-position)
2067 (cond ((<= (point) prompt-end) prompt-end)
2068 ((eobp) nil)
2069 (t (point))))))
2070 (goto-char (point-max))
2071 (delete-minibuffer-contents)
2072 (setq minibuffer-history-position nabs)
2073 (cond ((< nabs 0)
2074 (setq elt (if (listp minibuffer-default)
2075 (nth (1- (abs nabs)) minibuffer-default)
2076 minibuffer-default)))
2077 ((= nabs 0)
2078 (setq elt (or minibuffer-text-before-history ""))
2079 (setq minibuffer-returned-to-present t)
2080 (setq minibuffer-text-before-history nil))
2081 (t (setq elt (nth (1- minibuffer-history-position)
2082 (symbol-value minibuffer-history-variable)))))
2083 (insert
2084 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2085 (not minibuffer-returned-to-present))
2086 (let ((print-level nil))
2087 (prin1-to-string elt))
2088 elt))
2089 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2091 (defun next-history-element (n)
2092 "Puts next element of the minibuffer history in the minibuffer.
2093 With argument N, it uses the Nth following element."
2094 (interactive "p")
2095 (or (zerop n)
2096 (goto-history-element (- minibuffer-history-position n))))
2098 (defun previous-history-element (n)
2099 "Puts previous element of the minibuffer history in the minibuffer.
2100 With argument N, it uses the Nth previous element."
2101 (interactive "p")
2102 (or (zerop n)
2103 (goto-history-element (+ minibuffer-history-position n))))
2105 (defun next-line-or-history-element (&optional arg)
2106 "Move cursor vertically down ARG lines, or to the next history element.
2107 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2108 next element of the minibuffer history in the minibuffer."
2109 (interactive "^p")
2110 (or arg (setq arg 1))
2111 (let* ((old-point (point))
2112 ;; Don't add newlines if they have the mode enabled globally.
2113 (next-line-add-newlines nil)
2114 ;; Remember the original goal column of possibly multi-line input
2115 ;; excluding the length of the prompt on the first line.
2116 (prompt-end (minibuffer-prompt-end))
2117 (old-column (unless (and (eolp) (> (point) prompt-end))
2118 (if (= (line-number-at-pos) 1)
2119 (max (- (current-column) (1- prompt-end)) 0)
2120 (current-column)))))
2121 (condition-case nil
2122 (with-no-warnings
2123 (next-line arg))
2124 (end-of-buffer
2125 ;; Restore old position since `line-move-visual' moves point to
2126 ;; the end of the line when it fails to go to the next line.
2127 (goto-char old-point)
2128 (next-history-element arg)
2129 ;; Reset `temporary-goal-column' because a correct value is not
2130 ;; calculated when `next-line' above fails by bumping against
2131 ;; the bottom of the minibuffer (bug#22544).
2132 (setq temporary-goal-column 0)
2133 ;; Restore the original goal column on the last line
2134 ;; of possibly multi-line input.
2135 (goto-char (point-max))
2136 (when old-column
2137 (if (= (line-number-at-pos) 1)
2138 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2139 (move-to-column old-column)))))))
2141 (defun previous-line-or-history-element (&optional arg)
2142 "Move cursor vertically up ARG lines, or to the previous history element.
2143 When point moves over the top line of multi-line minibuffer, puts ARGth
2144 previous element of the minibuffer history in the minibuffer."
2145 (interactive "^p")
2146 (or arg (setq arg 1))
2147 (let* ((old-point (point))
2148 ;; Remember the original goal column of possibly multi-line input
2149 ;; excluding the length of the prompt on the first line.
2150 (prompt-end (minibuffer-prompt-end))
2151 (old-column (unless (and (eolp) (> (point) prompt-end))
2152 (if (= (line-number-at-pos) 1)
2153 (max (- (current-column) (1- prompt-end)) 0)
2154 (current-column)))))
2155 (condition-case nil
2156 (with-no-warnings
2157 (previous-line arg))
2158 (beginning-of-buffer
2159 ;; Restore old position since `line-move-visual' moves point to
2160 ;; the beginning of the line when it fails to go to the previous line.
2161 (goto-char old-point)
2162 (previous-history-element arg)
2163 ;; Reset `temporary-goal-column' because a correct value is not
2164 ;; calculated when `previous-line' above fails by bumping against
2165 ;; the top of the minibuffer (bug#22544).
2166 (setq temporary-goal-column 0)
2167 ;; Restore the original goal column on the first line
2168 ;; of possibly multi-line input.
2169 (goto-char (minibuffer-prompt-end))
2170 (if old-column
2171 (if (= (line-number-at-pos) 1)
2172 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2173 (move-to-column old-column))
2174 ;; Put the cursor at the end of the visual line instead of the
2175 ;; logical line, so the next `previous-line-or-history-element'
2176 ;; would move to the previous history element, not to a possible upper
2177 ;; visual line from the end of logical line in `line-move-visual' mode.
2178 (end-of-visual-line)
2179 ;; Since `end-of-visual-line' puts the cursor at the beginning
2180 ;; of the next visual line, move it one char back to the end
2181 ;; of the first visual line (bug#22544).
2182 (unless (eolp) (backward-char 1)))))))
2184 (defun next-complete-history-element (n)
2185 "Get next history element which completes the minibuffer before the point.
2186 The contents of the minibuffer after the point are deleted, and replaced
2187 by the new completion."
2188 (interactive "p")
2189 (let ((point-at-start (point)))
2190 (next-matching-history-element
2191 (concat
2192 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2194 ;; next-matching-history-element always puts us at (point-min).
2195 ;; Move to the position we were at before changing the buffer contents.
2196 ;; This is still sensible, because the text before point has not changed.
2197 (goto-char point-at-start)))
2199 (defun previous-complete-history-element (n)
2201 Get previous history element which completes the minibuffer before the point.
2202 The contents of the minibuffer after the point are deleted, and replaced
2203 by the new completion."
2204 (interactive "p")
2205 (next-complete-history-element (- n)))
2207 ;; For compatibility with the old subr of the same name.
2208 (defun minibuffer-prompt-width ()
2209 "Return the display width of the minibuffer prompt.
2210 Return 0 if current buffer is not a minibuffer."
2211 ;; Return the width of everything before the field at the end of
2212 ;; the buffer; this should be 0 for normal buffers.
2213 (1- (minibuffer-prompt-end)))
2215 ;; isearch minibuffer history
2216 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2218 (defvar minibuffer-history-isearch-message-overlay)
2219 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2221 (defun minibuffer-history-isearch-setup ()
2222 "Set up a minibuffer for using isearch to search the minibuffer history.
2223 Intended to be added to `minibuffer-setup-hook'."
2224 (set (make-local-variable 'isearch-search-fun-function)
2225 'minibuffer-history-isearch-search)
2226 (set (make-local-variable 'isearch-message-function)
2227 'minibuffer-history-isearch-message)
2228 (set (make-local-variable 'isearch-wrap-function)
2229 'minibuffer-history-isearch-wrap)
2230 (set (make-local-variable 'isearch-push-state-function)
2231 'minibuffer-history-isearch-push-state)
2232 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2234 (defun minibuffer-history-isearch-end ()
2235 "Clean up the minibuffer after terminating isearch in the minibuffer."
2236 (if minibuffer-history-isearch-message-overlay
2237 (delete-overlay minibuffer-history-isearch-message-overlay)))
2239 (defun minibuffer-history-isearch-search ()
2240 "Return the proper search function, for isearch in minibuffer history."
2241 (lambda (string bound noerror)
2242 (let ((search-fun
2243 ;; Use standard functions to search within minibuffer text
2244 (isearch-search-fun-default))
2245 found)
2246 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2247 ;; searching forward. Lazy-highlight calls this lambda with the
2248 ;; bound arg, so skip the minibuffer prompt.
2249 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2250 (goto-char (minibuffer-prompt-end)))
2252 ;; 1. First try searching in the initial minibuffer text
2253 (funcall search-fun string
2254 (if isearch-forward bound (minibuffer-prompt-end))
2255 noerror)
2256 ;; 2. If the above search fails, start putting next/prev history
2257 ;; elements in the minibuffer successively, and search the string
2258 ;; in them. Do this only when bound is nil (i.e. not while
2259 ;; lazy-highlighting search strings in the current minibuffer text).
2260 (unless bound
2261 (condition-case nil
2262 (progn
2263 (while (not found)
2264 (cond (isearch-forward
2265 (next-history-element 1)
2266 (goto-char (minibuffer-prompt-end)))
2268 (previous-history-element 1)
2269 (goto-char (point-max))))
2270 (setq isearch-barrier (point) isearch-opoint (point))
2271 ;; After putting the next/prev history element, search
2272 ;; the string in them again, until next-history-element
2273 ;; or previous-history-element raises an error at the
2274 ;; beginning/end of history.
2275 (setq found (funcall search-fun string
2276 (unless isearch-forward
2277 ;; For backward search, don't search
2278 ;; in the minibuffer prompt
2279 (minibuffer-prompt-end))
2280 noerror)))
2281 ;; Return point of the new search result
2282 (point))
2283 ;; Return nil when next(prev)-history-element fails
2284 (error nil)))))))
2286 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2287 "Display the minibuffer history search prompt.
2288 If there are no search errors, this function displays an overlay with
2289 the isearch prompt which replaces the original minibuffer prompt.
2290 Otherwise, it displays the standard isearch message returned from
2291 the function `isearch-message'."
2292 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2293 ;; Use standard function `isearch-message' when not in the minibuffer,
2294 ;; or search fails, or has an error (like incomplete regexp).
2295 ;; This function overwrites minibuffer text with isearch message,
2296 ;; so it's possible to see what is wrong in the search string.
2297 (isearch-message c-q-hack ellipsis)
2298 ;; Otherwise, put the overlay with the standard isearch prompt over
2299 ;; the initial minibuffer prompt.
2300 (if (overlayp minibuffer-history-isearch-message-overlay)
2301 (move-overlay minibuffer-history-isearch-message-overlay
2302 (point-min) (minibuffer-prompt-end))
2303 (setq minibuffer-history-isearch-message-overlay
2304 (make-overlay (point-min) (minibuffer-prompt-end)))
2305 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2306 (overlay-put minibuffer-history-isearch-message-overlay
2307 'display (isearch-message-prefix c-q-hack ellipsis))
2308 ;; And clear any previous isearch message.
2309 (message "")))
2311 (defun minibuffer-history-isearch-wrap ()
2312 "Wrap the minibuffer history search when search fails.
2313 Move point to the first history element for a forward search,
2314 or to the last history element for a backward search."
2315 ;; When `minibuffer-history-isearch-search' fails on reaching the
2316 ;; beginning/end of the history, wrap the search to the first/last
2317 ;; minibuffer history element.
2318 (if isearch-forward
2319 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2320 (goto-history-element 0))
2321 (setq isearch-success t)
2322 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2324 (defun minibuffer-history-isearch-push-state ()
2325 "Save a function restoring the state of minibuffer history search.
2326 Save `minibuffer-history-position' to the additional state parameter
2327 in the search status stack."
2328 (let ((pos minibuffer-history-position))
2329 (lambda (cmd)
2330 (minibuffer-history-isearch-pop-state cmd pos))))
2332 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2333 "Restore the minibuffer history search state.
2334 Go to the history element by the absolute history position HIST-POS."
2335 (goto-history-element hist-pos))
2338 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2339 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2341 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2342 "Table mapping redo records to the corresponding undo one.
2343 A redo record for undo-in-region maps to t.
2344 A redo record for ordinary undo maps to the following (earlier) undo.")
2346 (defvar undo-in-region nil
2347 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2349 (defvar undo-no-redo nil
2350 "If t, `undo' doesn't go through redo entries.")
2352 (defvar pending-undo-list nil
2353 "Within a run of consecutive undo commands, list remaining to be undone.
2354 If t, we undid all the way to the end of it.")
2356 (defun undo (&optional arg)
2357 "Undo some previous changes.
2358 Repeat this command to undo more changes.
2359 A numeric ARG serves as a repeat count.
2361 In Transient Mark mode when the mark is active, only undo changes within
2362 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2363 as an argument limits undo to changes within the current region."
2364 (interactive "*P")
2365 ;; Make last-command indicate for the next command that this was an undo.
2366 ;; That way, another undo will undo more.
2367 ;; If we get to the end of the undo history and get an error,
2368 ;; another undo command will find the undo history empty
2369 ;; and will get another error. To begin undoing the undos,
2370 ;; you must type some other command.
2371 (let* ((modified (buffer-modified-p))
2372 ;; For an indirect buffer, look in the base buffer for the
2373 ;; auto-save data.
2374 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2375 (recent-save (with-current-buffer base-buffer
2376 (recent-auto-save-p)))
2377 message)
2378 ;; If we get an error in undo-start,
2379 ;; the next command should not be a "consecutive undo".
2380 ;; So set `this-command' to something other than `undo'.
2381 (setq this-command 'undo-start)
2383 (unless (and (eq last-command 'undo)
2384 (or (eq pending-undo-list t)
2385 ;; If something (a timer or filter?) changed the buffer
2386 ;; since the previous command, don't continue the undo seq.
2387 (let ((list buffer-undo-list))
2388 (while (eq (car list) nil)
2389 (setq list (cdr list)))
2390 ;; If the last undo record made was made by undo
2391 ;; it shows nothing else happened in between.
2392 (gethash list undo-equiv-table))))
2393 (setq undo-in-region
2394 (or (region-active-p) (and arg (not (numberp arg)))))
2395 (if undo-in-region
2396 (undo-start (region-beginning) (region-end))
2397 (undo-start))
2398 ;; get rid of initial undo boundary
2399 (undo-more 1))
2400 ;; If we got this far, the next command should be a consecutive undo.
2401 (setq this-command 'undo)
2402 ;; Check to see whether we're hitting a redo record, and if
2403 ;; so, ask the user whether she wants to skip the redo/undo pair.
2404 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2405 (or (eq (selected-window) (minibuffer-window))
2406 (setq message (format "%s%s!"
2407 (if (or undo-no-redo (not equiv))
2408 "Undo" "Redo")
2409 (if undo-in-region " in region" ""))))
2410 (when (and (consp equiv) undo-no-redo)
2411 ;; The equiv entry might point to another redo record if we have done
2412 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2413 (while (let ((next (gethash equiv undo-equiv-table)))
2414 (if next (setq equiv next))))
2415 (setq pending-undo-list equiv)))
2416 (undo-more
2417 (if (numberp arg)
2418 (prefix-numeric-value arg)
2420 ;; Record the fact that the just-generated undo records come from an
2421 ;; undo operation--that is, they are redo records.
2422 ;; In the ordinary case (not within a region), map the redo
2423 ;; record to the following undos.
2424 ;; I don't know how to do that in the undo-in-region case.
2425 (let ((list buffer-undo-list))
2426 ;; Strip any leading undo boundaries there might be, like we do
2427 ;; above when checking.
2428 (while (eq (car list) nil)
2429 (setq list (cdr list)))
2430 (puthash list
2431 ;; Prevent identity mapping. This can happen if
2432 ;; consecutive nils are erroneously in undo list.
2433 (if (or undo-in-region (eq list pending-undo-list))
2435 pending-undo-list)
2436 undo-equiv-table))
2437 ;; Don't specify a position in the undo record for the undo command.
2438 ;; Instead, undoing this should move point to where the change is.
2439 (let ((tail buffer-undo-list)
2440 (prev nil))
2441 (while (car tail)
2442 (when (integerp (car tail))
2443 (let ((pos (car tail)))
2444 (if prev
2445 (setcdr prev (cdr tail))
2446 (setq buffer-undo-list (cdr tail)))
2447 (setq tail (cdr tail))
2448 (while (car tail)
2449 (if (eq pos (car tail))
2450 (if prev
2451 (setcdr prev (cdr tail))
2452 (setq buffer-undo-list (cdr tail)))
2453 (setq prev tail))
2454 (setq tail (cdr tail)))
2455 (setq tail nil)))
2456 (setq prev tail tail (cdr tail))))
2457 ;; Record what the current undo list says,
2458 ;; so the next command can tell if the buffer was modified in between.
2459 (and modified (not (buffer-modified-p))
2460 (with-current-buffer base-buffer
2461 (delete-auto-save-file-if-necessary recent-save)))
2462 ;; Display a message announcing success.
2463 (if message
2464 (message "%s" message))))
2466 (defun buffer-disable-undo (&optional buffer)
2467 "Make BUFFER stop keeping undo information.
2468 No argument or nil as argument means do this for the current buffer."
2469 (interactive)
2470 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2471 (setq buffer-undo-list t)))
2473 (defun undo-only (&optional arg)
2474 "Undo some previous changes.
2475 Repeat this command to undo more changes.
2476 A numeric ARG serves as a repeat count.
2477 Contrary to `undo', this will not redo a previous undo."
2478 (interactive "*p")
2479 (let ((undo-no-redo t)) (undo arg)))
2481 (defvar undo-in-progress nil
2482 "Non-nil while performing an undo.
2483 Some change-hooks test this variable to do something different.")
2485 (defun undo-more (n)
2486 "Undo back N undo-boundaries beyond what was already undone recently.
2487 Call `undo-start' to get ready to undo recent changes,
2488 then call `undo-more' one or more times to undo them."
2489 (or (listp pending-undo-list)
2490 (user-error (concat "No further undo information"
2491 (and undo-in-region " for region"))))
2492 (let ((undo-in-progress t))
2493 ;; Note: The following, while pulling elements off
2494 ;; `pending-undo-list' will call primitive change functions which
2495 ;; will push more elements onto `buffer-undo-list'.
2496 (setq pending-undo-list (primitive-undo n pending-undo-list))
2497 (if (null pending-undo-list)
2498 (setq pending-undo-list t))))
2500 (defun primitive-undo (n list)
2501 "Undo N records from the front of the list LIST.
2502 Return what remains of the list."
2504 ;; This is a good feature, but would make undo-start
2505 ;; unable to do what is expected.
2506 ;;(when (null (car (list)))
2507 ;; ;; If the head of the list is a boundary, it is the boundary
2508 ;; ;; preceding this command. Get rid of it and don't count it.
2509 ;; (setq list (cdr list))))
2511 (let ((arg n)
2512 ;; In a writable buffer, enable undoing read-only text that is
2513 ;; so because of text properties.
2514 (inhibit-read-only t)
2515 ;; Don't let `intangible' properties interfere with undo.
2516 (inhibit-point-motion-hooks t)
2517 ;; We use oldlist only to check for EQ. ++kfs
2518 (oldlist buffer-undo-list)
2519 (did-apply nil)
2520 (next nil))
2521 (while (> arg 0)
2522 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2523 ;; Handle an integer by setting point to that value.
2524 (pcase next
2525 ((pred integerp) (goto-char next))
2526 ;; Element (t . TIME) records previous modtime.
2527 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2528 ;; UNKNOWN_MODTIME_NSECS.
2529 (`(t . ,time)
2530 ;; If this records an obsolete save
2531 ;; (not matching the actual disk file)
2532 ;; then don't mark unmodified.
2533 (when (or (equal time (visited-file-modtime))
2534 (and (consp time)
2535 (equal (list (car time) (cdr time))
2536 (visited-file-modtime))))
2537 (when (fboundp 'unlock-buffer)
2538 (unlock-buffer))
2539 (set-buffer-modified-p nil)))
2540 ;; Element (nil PROP VAL BEG . END) is property change.
2541 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2542 (when (or (> (point-min) beg) (< (point-max) end))
2543 (error "Changes to be undone are outside visible portion of buffer"))
2544 (put-text-property beg end prop val))
2545 ;; Element (BEG . END) means range was inserted.
2546 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2547 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2548 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2549 (when (or (> (point-min) beg) (< (point-max) end))
2550 (error "Changes to be undone are outside visible portion of buffer"))
2551 ;; Set point first thing, so that undoing this undo
2552 ;; does not send point back to where it is now.
2553 (goto-char beg)
2554 (delete-region beg end))
2555 ;; Element (apply FUN . ARGS) means call FUN to undo.
2556 (`(apply . ,fun-args)
2557 (let ((currbuff (current-buffer)))
2558 (if (integerp (car fun-args))
2559 ;; Long format: (apply DELTA START END FUN . ARGS).
2560 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2561 (start-mark (copy-marker start nil))
2562 (end-mark (copy-marker end t)))
2563 (when (or (> (point-min) start) (< (point-max) end))
2564 (error "Changes to be undone are outside visible portion of buffer"))
2565 (apply fun args) ;; Use `save-current-buffer'?
2566 ;; Check that the function did what the entry
2567 ;; said it would do.
2568 (unless (and (= start start-mark)
2569 (= (+ delta end) end-mark))
2570 (error "Changes to be undone by function different than announced"))
2571 (set-marker start-mark nil)
2572 (set-marker end-mark nil))
2573 (apply fun-args))
2574 (unless (eq currbuff (current-buffer))
2575 (error "Undo function switched buffer"))
2576 (setq did-apply t)))
2577 ;; Element (STRING . POS) means STRING was deleted.
2578 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2579 (let ((valid-marker-adjustments nil)
2580 (apos (abs pos)))
2581 (when (or (< apos (point-min)) (> apos (point-max)))
2582 (error "Changes to be undone are outside visible portion of buffer"))
2583 ;; Check that marker adjustments which were recorded
2584 ;; with the (STRING . POS) record are still valid, ie
2585 ;; the markers haven't moved. We check their validity
2586 ;; before reinserting the string so as we don't need to
2587 ;; mind marker insertion-type.
2588 (while (and (markerp (car-safe (car list)))
2589 (integerp (cdr-safe (car list))))
2590 (let* ((marker-adj (pop list))
2591 (m (car marker-adj)))
2592 (and (eq (marker-buffer m) (current-buffer))
2593 (= apos m)
2594 (push marker-adj valid-marker-adjustments))))
2595 ;; Insert string and adjust point
2596 (if (< pos 0)
2597 (progn
2598 (goto-char (- pos))
2599 (insert string))
2600 (goto-char pos)
2601 (insert string)
2602 (goto-char pos))
2603 ;; Adjust the valid marker adjustments
2604 (dolist (adj valid-marker-adjustments)
2605 ;; Insert might have invalidated some of the markers
2606 ;; via modification hooks. Update only the currently
2607 ;; valid ones (bug#25599).
2608 (if (marker-buffer (car adj))
2609 (set-marker (car adj)
2610 (- (car adj) (cdr adj)))))))
2611 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2612 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2613 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2614 next)
2615 ;; Even though these elements are not expected in the undo
2616 ;; list, adjust them to be conservative for the 24.4
2617 ;; release. (Bug#16818)
2618 (when (marker-buffer marker)
2619 (set-marker marker
2620 (- marker offset)
2621 (marker-buffer marker))))
2622 (_ (error "Unrecognized entry in undo list %S" next))))
2623 (setq arg (1- arg)))
2624 ;; Make sure an apply entry produces at least one undo entry,
2625 ;; so the test in `undo' for continuing an undo series
2626 ;; will work right.
2627 (if (and did-apply
2628 (eq oldlist buffer-undo-list))
2629 (setq buffer-undo-list
2630 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2631 list)
2633 ;; Deep copy of a list
2634 (defun undo-copy-list (list)
2635 "Make a copy of undo list LIST."
2636 (mapcar 'undo-copy-list-1 list))
2638 (defun undo-copy-list-1 (elt)
2639 (if (consp elt)
2640 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2641 elt))
2643 (defun undo-start (&optional beg end)
2644 "Set `pending-undo-list' to the front of the undo list.
2645 The next call to `undo-more' will undo the most recently made change.
2646 If BEG and END are specified, then only undo elements
2647 that apply to text between BEG and END are used; other undo elements
2648 are ignored. If BEG and END are nil, all undo elements are used."
2649 (if (eq buffer-undo-list t)
2650 (user-error "No undo information in this buffer"))
2651 (setq pending-undo-list
2652 (if (and beg end (not (= beg end)))
2653 (undo-make-selective-list (min beg end) (max beg end))
2654 buffer-undo-list)))
2656 ;; The positions given in elements of the undo list are the positions
2657 ;; as of the time that element was recorded to undo history. In
2658 ;; general, subsequent buffer edits render those positions invalid in
2659 ;; the current buffer, unless adjusted according to the intervening
2660 ;; undo elements.
2662 ;; Undo in region is a use case that requires adjustments to undo
2663 ;; elements. It must adjust positions of elements in the region based
2664 ;; on newer elements not in the region so as they may be correctly
2665 ;; applied in the current buffer. undo-make-selective-list
2666 ;; accomplishes this with its undo-deltas list of adjustments. An
2667 ;; example undo history from oldest to newest:
2669 ;; buf pos:
2670 ;; 123456789 buffer-undo-list undo-deltas
2671 ;; --------- ---------------- -----------
2672 ;; aaa (1 . 4) (1 . -3)
2673 ;; aaba (3 . 4) N/A (in region)
2674 ;; ccaaba (1 . 3) (1 . -2)
2675 ;; ccaabaddd (7 . 10) (7 . -3)
2676 ;; ccaabdd ("ad" . 6) (6 . 2)
2677 ;; ccaabaddd (6 . 8) (6 . -2)
2678 ;; | |<-- region: "caab", from 2 to 6
2680 ;; When the user starts a run of undos in region,
2681 ;; undo-make-selective-list is called to create the full list of in
2682 ;; region elements. Each element is adjusted forward chronologically
2683 ;; through undo-deltas to determine if it is in the region.
2685 ;; In the above example, the insertion of "b" is (3 . 4) in the
2686 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2687 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2688 ;; . 6) is assessed as in the region and placed in the selective list.
2689 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2690 ;; due to the selected element. The "b" insertion is the only element
2691 ;; fully in the region, so in this example undo-make-selective-list
2692 ;; returns (nil (5 . 6)).
2694 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2695 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2696 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2697 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2698 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2700 ;; More interesting is how to adjust the "ddd" insertion due to the
2701 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2702 ;; If the reinsertion was a manual retyping of "ad", then the total
2703 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2704 ;; the reinsertion was due to undo, one might expect the first "d"
2705 ;; character would again be a part of the "ddd" text, meaning its
2706 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2708 ;; undo-make-selective-list assumes in this situation that "ad" was a
2709 ;; new edit, even if it was inserted because of an undo.
2710 ;; Consequently, if the user undos in region "8 to 10" of the
2711 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2712 ;; "ccaabad", as though the first "d" became detached from the
2713 ;; original "ddd" insertion. This quirk is a FIXME.
2715 (defun undo-make-selective-list (start end)
2716 "Return a list of undo elements for the region START to END.
2717 The elements come from `buffer-undo-list', but we keep only the
2718 elements inside this region, and discard those outside this
2719 region. The elements' positions are adjusted so as the returned
2720 list can be applied to the current buffer."
2721 (let ((ulist buffer-undo-list)
2722 ;; A list of position adjusted undo elements in the region.
2723 (selective-list (list nil))
2724 ;; A list of undo-deltas for out of region undo elements.
2725 undo-deltas
2726 undo-elt)
2727 (while ulist
2728 (when undo-no-redo
2729 (while (gethash ulist undo-equiv-table)
2730 (setq ulist (gethash ulist undo-equiv-table))))
2731 (setq undo-elt (car ulist))
2732 (cond
2733 ((null undo-elt)
2734 ;; Don't put two nils together in the list
2735 (when (car selective-list)
2736 (push nil selective-list)))
2737 ((and (consp undo-elt) (eq (car undo-elt) t))
2738 ;; This is a "was unmodified" element. Keep it
2739 ;; if we have kept everything thus far.
2740 (when (not undo-deltas)
2741 (push undo-elt selective-list)))
2742 ;; Skip over marker adjustments, instead relying
2743 ;; on finding them after (TEXT . POS) elements
2744 ((markerp (car-safe undo-elt))
2745 nil)
2747 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2748 undo-deltas)))
2749 (if (undo-elt-in-region adjusted-undo-elt start end)
2750 (progn
2751 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2752 (push adjusted-undo-elt selective-list)
2753 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2754 ;; kept. primitive-undo may discard them later.
2755 (when (and (stringp (car-safe adjusted-undo-elt))
2756 (integerp (cdr-safe adjusted-undo-elt)))
2757 (let ((list-i (cdr ulist)))
2758 (while (markerp (car-safe (car list-i)))
2759 (push (pop list-i) selective-list)))))
2760 (let ((delta (undo-delta undo-elt)))
2761 (when (/= 0 (cdr delta))
2762 (push delta undo-deltas)))))))
2763 (pop ulist))
2764 (nreverse selective-list)))
2766 (defun undo-elt-in-region (undo-elt start end)
2767 "Determine whether UNDO-ELT falls inside the region START ... END.
2768 If it crosses the edge, we return nil.
2770 Generally this function is not useful for determining
2771 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2772 because markers can be arbitrarily relocated. Instead, pass the
2773 marker adjustment's corresponding (TEXT . POS) element."
2774 (cond ((integerp undo-elt)
2775 (and (>= undo-elt start)
2776 (<= undo-elt end)))
2777 ((eq undo-elt nil)
2779 ((atom undo-elt)
2780 nil)
2781 ((stringp (car undo-elt))
2782 ;; (TEXT . POSITION)
2783 (and (>= (abs (cdr undo-elt)) start)
2784 (<= (abs (cdr undo-elt)) end)))
2785 ((and (consp undo-elt) (markerp (car undo-elt)))
2786 ;; (MARKER . ADJUSTMENT)
2787 (<= start (car undo-elt) end))
2788 ((null (car undo-elt))
2789 ;; (nil PROPERTY VALUE BEG . END)
2790 (let ((tail (nthcdr 3 undo-elt)))
2791 (and (>= (car tail) start)
2792 (<= (cdr tail) end))))
2793 ((integerp (car undo-elt))
2794 ;; (BEGIN . END)
2795 (and (>= (car undo-elt) start)
2796 (<= (cdr undo-elt) end)))))
2798 (defun undo-elt-crosses-region (undo-elt start end)
2799 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2800 This assumes we have already decided that UNDO-ELT
2801 is not *inside* the region START...END."
2802 (declare (obsolete nil "25.1"))
2803 (cond ((atom undo-elt) nil)
2804 ((null (car undo-elt))
2805 ;; (nil PROPERTY VALUE BEG . END)
2806 (let ((tail (nthcdr 3 undo-elt)))
2807 (and (< (car tail) end)
2808 (> (cdr tail) start))))
2809 ((integerp (car undo-elt))
2810 ;; (BEGIN . END)
2811 (and (< (car undo-elt) end)
2812 (> (cdr undo-elt) start)))))
2814 (defun undo-adjust-elt (elt deltas)
2815 "Return adjustment of undo element ELT by the undo DELTAS
2816 list."
2817 (pcase elt
2818 ;; POSITION
2819 ((pred integerp)
2820 (undo-adjust-pos elt deltas))
2821 ;; (BEG . END)
2822 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2823 (undo-adjust-beg-end beg end deltas))
2824 ;; (TEXT . POSITION)
2825 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2826 (cons text (* (if (< pos 0) -1 1)
2827 (undo-adjust-pos (abs pos) deltas))))
2828 ;; (nil PROPERTY VALUE BEG . END)
2829 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2830 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2831 ;; (apply DELTA START END FUN . ARGS)
2832 ;; FIXME
2833 ;; All others return same elt
2834 (_ elt)))
2836 ;; (BEG . END) can adjust to the same positions, commonly when an
2837 ;; insertion was undone and they are out of region, for example:
2839 ;; buf pos:
2840 ;; 123456789 buffer-undo-list undo-deltas
2841 ;; --------- ---------------- -----------
2842 ;; [...]
2843 ;; abbaa (2 . 4) (2 . -2)
2844 ;; aaa ("bb" . 2) (2 . 2)
2845 ;; [...]
2847 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2848 ;; undo. Further adjustments to such an element should be the same as
2849 ;; for (TEXT . POSITION) elements. The options are:
2851 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2852 ;; analogous to marker insertion-type t.
2854 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2855 ;; marker insertion-type nil.
2857 ;; There was no strong reason to prefer one or the other, except that
2858 ;; the first is more consistent with prior undo in region behavior.
2859 (defun undo-adjust-beg-end (beg end deltas)
2860 "Return cons of adjustments to BEG and END by the undo DELTAS
2861 list."
2862 (let ((adj-beg (undo-adjust-pos beg deltas)))
2863 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2864 (cons adj-beg
2865 (max adj-beg (undo-adjust-pos end deltas t)))))
2867 (defun undo-adjust-pos (pos deltas &optional use-<)
2868 "Return adjustment of POS by the undo DELTAS list, comparing
2869 with < or <= based on USE-<."
2870 (dolist (d deltas pos)
2871 (when (if use-<
2872 (< (car d) pos)
2873 (<= (car d) pos))
2874 (setq pos
2875 ;; Don't allow pos to become less than the undo-delta
2876 ;; position. This edge case is described in the overview
2877 ;; comments.
2878 (max (car d) (- pos (cdr d)))))))
2880 ;; Return the first affected buffer position and the delta for an undo element
2881 ;; delta is defined as the change in subsequent buffer positions if we *did*
2882 ;; the undo.
2883 (defun undo-delta (undo-elt)
2884 (if (consp undo-elt)
2885 (cond ((stringp (car undo-elt))
2886 ;; (TEXT . POSITION)
2887 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2888 ((integerp (car undo-elt))
2889 ;; (BEGIN . END)
2890 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2892 '(0 . 0)))
2893 '(0 . 0)))
2895 ;;; Default undo-boundary addition
2897 ;; This section adds a new undo-boundary at either after a command is
2898 ;; called or in some cases on a timer called after a change is made in
2899 ;; any buffer.
2900 (defvar-local undo-auto--last-boundary-cause nil
2901 "Describe the cause of the last undo-boundary.
2903 If `explicit', the last boundary was caused by an explicit call to
2904 `undo-boundary', that is one not called by the code in this
2905 section.
2907 If it is equal to `timer', then the last boundary was inserted
2908 by `undo-auto--boundary-timer'.
2910 If it is equal to `command', then the last boundary was inserted
2911 automatically after a command, that is by the code defined in
2912 this section.
2914 If it is equal to a list, then the last boundary was inserted by
2915 an amalgamating command. The car of the list is the number of
2916 times an amalgamating command has been called, and the cdr are the
2917 buffers that were changed during the last command.")
2919 (defvar undo-auto-current-boundary-timer nil
2920 "Current timer which will run `undo-auto--boundary-timer' or nil.
2922 If set to non-nil, this will effectively disable the timer.")
2924 (defvar undo-auto--this-command-amalgamating nil
2925 "Non-nil if `this-command' should be amalgamated.
2926 This variable is set to nil by `undo-auto--boundaries' and is set
2927 by `undo-auto-amalgamate'." )
2929 (defun undo-auto--needs-boundary-p ()
2930 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2931 (car-safe buffer-undo-list))
2933 (defun undo-auto--last-boundary-amalgamating-number ()
2934 "Return the number of amalgamating last commands or nil.
2935 Amalgamating commands are, by default, either
2936 `self-insert-command' and `delete-char', but can be any command
2937 that calls `undo-auto-amalgamate'."
2938 (car-safe undo-auto--last-boundary-cause))
2940 (defun undo-auto--ensure-boundary (cause)
2941 "Add an `undo-boundary' to the current buffer if needed.
2942 REASON describes the reason that the boundary is being added; see
2943 `undo-auto--last-boundary' for more information."
2944 (when (and
2945 (undo-auto--needs-boundary-p))
2946 (let ((last-amalgamating
2947 (undo-auto--last-boundary-amalgamating-number)))
2948 (undo-boundary)
2949 (setq undo-auto--last-boundary-cause
2950 (if (eq 'amalgamate cause)
2951 (cons
2952 (if last-amalgamating (1+ last-amalgamating) 0)
2953 undo-auto--undoably-changed-buffers)
2954 cause)))))
2956 (defun undo-auto--boundaries (cause)
2957 "Check recently changed buffers and add a boundary if necessary.
2958 REASON describes the reason that the boundary is being added; see
2959 `undo-last-boundary' for more information."
2960 ;; (Bug #23785) All commands should ensure that there is an undo
2961 ;; boundary whether they have changed the current buffer or not.
2962 (when (eq cause 'command)
2963 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2964 (dolist (b undo-auto--undoably-changed-buffers)
2965 (when (buffer-live-p b)
2966 (with-current-buffer b
2967 (undo-auto--ensure-boundary cause))))
2968 (setq undo-auto--undoably-changed-buffers nil))
2970 (defun undo-auto--boundary-timer ()
2971 "Timer which will run `undo--auto-boundary-timer'."
2972 (setq undo-auto-current-boundary-timer nil)
2973 (undo-auto--boundaries 'timer))
2975 (defun undo-auto--boundary-ensure-timer ()
2976 "Ensure that the `undo-auto-boundary-timer' is set."
2977 (unless undo-auto-current-boundary-timer
2978 (setq undo-auto-current-boundary-timer
2979 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2981 (defvar undo-auto--undoably-changed-buffers nil
2982 "List of buffers that have changed recently.
2984 This list is maintained by `undo-auto--undoable-change' and
2985 `undo-auto--boundaries' and can be affected by changes to their
2986 default values.")
2988 (defun undo-auto--add-boundary ()
2989 "Add an `undo-boundary' in appropriate buffers."
2990 (undo-auto--boundaries
2991 (let ((amal undo-auto--this-command-amalgamating))
2992 (setq undo-auto--this-command-amalgamating nil)
2993 (if amal
2994 'amalgamate
2995 'command))))
2997 (defun undo-auto-amalgamate ()
2998 "Amalgamate undo if necessary.
2999 This function can be called before an amalgamating command. It
3000 removes the previous `undo-boundary' if a series of such calls
3001 have been made. By default `self-insert-command' and
3002 `delete-char' are the only amalgamating commands, although this
3003 function could be called by any command wishing to have this
3004 behavior."
3005 (let ((last-amalgamating-count
3006 (undo-auto--last-boundary-amalgamating-number)))
3007 (setq undo-auto--this-command-amalgamating t)
3008 (when
3009 last-amalgamating-count
3011 (and
3012 (< last-amalgamating-count 20)
3013 (eq this-command last-command))
3014 ;; Amalgamate all buffers that have changed.
3015 (dolist (b (cdr undo-auto--last-boundary-cause))
3016 (when (buffer-live-p b)
3017 (with-current-buffer
3019 (when
3020 ;; The head of `buffer-undo-list' is nil.
3021 ;; `car-safe' doesn't work because
3022 ;; `buffer-undo-list' need not be a list!
3023 (and (listp buffer-undo-list)
3024 (not (car buffer-undo-list)))
3025 (setq buffer-undo-list
3026 (cdr buffer-undo-list))))))
3027 (setq undo-auto--last-boundary-cause 0)))))
3029 (defun undo-auto--undoable-change ()
3030 "Called after every undoable buffer change."
3031 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
3032 (undo-auto--boundary-ensure-timer))
3033 ;; End auto-boundary section
3035 (defun undo-amalgamate-change-group (handle)
3036 "Amalgamate changes in change-group since HANDLE.
3037 Remove all undo boundaries between the state of HANDLE and now.
3038 HANDLE is as returned by `prepare-change-group'."
3039 (dolist (elt handle)
3040 (with-current-buffer (car elt)
3041 (setq elt (cdr elt))
3042 (when (consp buffer-undo-list)
3043 (let ((old-car (car-safe elt))
3044 (old-cdr (cdr-safe elt)))
3045 (unwind-protect
3046 (progn
3047 ;; Temporarily truncate the undo log at ELT.
3048 (when (consp elt)
3049 (setcar elt t) (setcdr elt nil))
3050 (when
3051 (or (null elt) ;The undo-log was empty.
3052 ;; `elt' is still in the log: normal case.
3053 (eq elt (last buffer-undo-list))
3054 ;; `elt' is not in the log any more, but that's because
3055 ;; the log is "all new", so we should remove all
3056 ;; boundaries from it.
3057 (not (eq (last buffer-undo-list) (last old-cdr))))
3058 (cl-callf (lambda (x) (delq nil x))
3059 (if (car buffer-undo-list)
3060 buffer-undo-list
3061 ;; Preserve the undo-boundaries at either ends of the
3062 ;; change-groups.
3063 (cdr buffer-undo-list)))))
3064 ;; Reset the modified cons cell ELT to its original content.
3065 (when (consp elt)
3066 (setcar elt old-car)
3067 (setcdr elt old-cdr))))))))
3070 (defcustom undo-ask-before-discard nil
3071 "If non-nil ask about discarding undo info for the current command.
3072 Normally, Emacs discards the undo info for the current command if
3073 it exceeds `undo-outer-limit'. But if you set this option
3074 non-nil, it asks in the echo area whether to discard the info.
3075 If you answer no, there is a slight risk that Emacs might crash, so
3076 only do it if you really want to undo the command.
3078 This option is mainly intended for debugging. You have to be
3079 careful if you use it for other purposes. Garbage collection is
3080 inhibited while the question is asked, meaning that Emacs might
3081 leak memory. So you should make sure that you do not wait
3082 excessively long before answering the question."
3083 :type 'boolean
3084 :group 'undo
3085 :version "22.1")
3087 (defvar undo-extra-outer-limit nil
3088 "If non-nil, an extra level of size that's ok in an undo item.
3089 We don't ask the user about truncating the undo list until the
3090 current item gets bigger than this amount.
3092 This variable only matters if `undo-ask-before-discard' is non-nil.")
3093 (make-variable-buffer-local 'undo-extra-outer-limit)
3095 ;; When the first undo batch in an undo list is longer than
3096 ;; undo-outer-limit, this function gets called to warn the user that
3097 ;; the undo info for the current command was discarded. Garbage
3098 ;; collection is inhibited around the call, so it had better not do a
3099 ;; lot of consing.
3100 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3101 (defun undo-outer-limit-truncate (size)
3102 (if undo-ask-before-discard
3103 (when (or (null undo-extra-outer-limit)
3104 (> size undo-extra-outer-limit))
3105 ;; Don't ask the question again unless it gets even bigger.
3106 ;; This applies, in particular, if the user quits from the question.
3107 ;; Such a quit quits out of GC, but something else will call GC
3108 ;; again momentarily. It will call this function again,
3109 ;; but we don't want to ask the question again.
3110 (setq undo-extra-outer-limit (+ size 50000))
3111 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3112 (yes-or-no-p (format-message
3113 "Buffer `%s' undo info is %d bytes long; discard it? "
3114 (buffer-name) size)))
3115 (progn (setq buffer-undo-list nil)
3116 (setq undo-extra-outer-limit nil)
3118 nil))
3119 (display-warning '(undo discard-info)
3120 (concat
3121 (format-message
3122 "Buffer `%s' undo info was %d bytes long.\n"
3123 (buffer-name) size)
3124 "The undo info was discarded because it exceeded \
3125 `undo-outer-limit'.
3127 This is normal if you executed a command that made a huge change
3128 to the buffer. In that case, to prevent similar problems in the
3129 future, set `undo-outer-limit' to a value that is large enough to
3130 cover the maximum size of normal changes you expect a single
3131 command to make, but not so large that it might exceed the
3132 maximum memory allotted to Emacs.
3134 If you did not execute any such command, the situation is
3135 probably due to a bug and you should report it.
3137 You can disable the popping up of this buffer by adding the entry
3138 \(undo discard-info) to the user option `warning-suppress-types',
3139 which is defined in the `warnings' library.\n")
3140 :warning)
3141 (setq buffer-undo-list nil)
3144 (defcustom password-word-equivalents
3145 '("password" "passcode" "passphrase" "pass phrase"
3146 ; These are sorted according to the GNU en_US locale.
3147 "암호" ; ko
3148 "パスワード" ; ja
3149 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3150 "ពាក្យសម្ងាត់" ; km
3151 "adgangskode" ; da
3152 "contraseña" ; es
3153 "contrasenya" ; ca
3154 "geslo" ; sl
3155 "hasło" ; pl
3156 "heslo" ; cs, sk
3157 "iphasiwedi" ; zu
3158 "jelszó" ; hu
3159 "lösenord" ; sv
3160 "lozinka" ; hr, sr
3161 "mật khẩu" ; vi
3162 "mot de passe" ; fr
3163 "parola" ; tr
3164 "pasahitza" ; eu
3165 "passord" ; nb
3166 "passwort" ; de
3167 "pasvorto" ; eo
3168 "salasana" ; fi
3169 "senha" ; pt
3170 "slaptažodis" ; lt
3171 "wachtwoord" ; nl
3172 "كلمة السر" ; ar
3173 "ססמה" ; he
3174 "лозинка" ; sr
3175 "пароль" ; kk, ru, uk
3176 "गुप्तशब्द" ; mr
3177 "शब्दकूट" ; hi
3178 "પાસવર્ડ" ; gu
3179 "సంకేతపదము" ; te
3180 "ਪਾਸਵਰਡ" ; pa
3181 "ಗುಪ್ತಪದ" ; kn
3182 "கடவுச்சொல்" ; ta
3183 "അടയാളവാക്ക്" ; ml
3184 "গুপ্তশব্দ" ; as
3185 "পাসওয়ার্ড" ; bn_IN
3186 "රහස්පදය" ; si
3187 "密码" ; zh_CN
3188 "密碼" ; zh_TW
3190 "List of words equivalent to \"password\".
3191 This is used by Shell mode and other parts of Emacs to recognize
3192 password prompts, including prompts in languages other than
3193 English. Different case choices should not be assumed to be
3194 included; callers should bind `case-fold-search' to t."
3195 :type '(repeat string)
3196 :version "24.4"
3197 :group 'processes)
3199 (defvar shell-command-history nil
3200 "History list for some commands that read shell commands.
3202 Maximum length of the history list is determined by the value
3203 of `history-length', which see.")
3205 (defvar shell-command-switch (purecopy "-c")
3206 "Switch used to have the shell execute its command line argument.")
3208 (defvar shell-command-default-error-buffer nil
3209 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3210 This buffer is used when `shell-command' or `shell-command-on-region'
3211 is run interactively. A value of nil means that output to stderr and
3212 stdout will be intermixed in the output stream.")
3214 (declare-function mailcap-file-default-commands "mailcap" (files))
3215 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3217 (defun minibuffer-default-add-shell-commands ()
3218 "Return a list of all commands associated with the current file.
3219 This function is used to add all related commands retrieved by `mailcap'
3220 to the end of the list of defaults just after the default value."
3221 (interactive)
3222 (let* ((filename (if (listp minibuffer-default)
3223 (car minibuffer-default)
3224 minibuffer-default))
3225 (commands (and filename (require 'mailcap nil t)
3226 (mailcap-file-default-commands (list filename)))))
3227 (setq commands (mapcar (lambda (command)
3228 (concat command " " filename))
3229 commands))
3230 (if (listp minibuffer-default)
3231 (append minibuffer-default commands)
3232 (cons minibuffer-default commands))))
3234 (declare-function shell-completion-vars "shell" ())
3236 (defvar minibuffer-local-shell-command-map
3237 (let ((map (make-sparse-keymap)))
3238 (set-keymap-parent map minibuffer-local-map)
3239 (define-key map "\t" 'completion-at-point)
3240 map)
3241 "Keymap used for completing shell commands in minibuffer.")
3243 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3244 "Read a shell command from the minibuffer.
3245 The arguments are the same as the ones of `read-from-minibuffer',
3246 except READ and KEYMAP are missing and HIST defaults
3247 to `shell-command-history'."
3248 (require 'shell)
3249 (minibuffer-with-setup-hook
3250 (lambda ()
3251 (shell-completion-vars)
3252 (set (make-local-variable 'minibuffer-default-add-function)
3253 'minibuffer-default-add-shell-commands))
3254 (apply 'read-from-minibuffer prompt initial-contents
3255 minibuffer-local-shell-command-map
3257 (or hist 'shell-command-history)
3258 args)))
3260 (defcustom async-shell-command-buffer 'confirm-new-buffer
3261 "What to do when the output buffer is used by another shell command.
3262 This option specifies how to resolve the conflict where a new command
3263 wants to direct its output to the buffer `*Async Shell Command*',
3264 but this buffer is already taken by another running shell command.
3266 The value `confirm-kill-process' is used to ask for confirmation before
3267 killing the already running process and running a new process
3268 in the same buffer, `confirm-new-buffer' for confirmation before running
3269 the command in a new buffer with a name other than the default buffer name,
3270 `new-buffer' for doing the same without confirmation,
3271 `confirm-rename-buffer' for confirmation before renaming the existing
3272 output buffer and running a new command in the default buffer,
3273 `rename-buffer' for doing the same without confirmation."
3274 :type '(choice (const :tag "Confirm killing of running command"
3275 confirm-kill-process)
3276 (const :tag "Confirm creation of a new buffer"
3277 confirm-new-buffer)
3278 (const :tag "Create a new buffer"
3279 new-buffer)
3280 (const :tag "Confirm renaming of existing buffer"
3281 confirm-rename-buffer)
3282 (const :tag "Rename the existing buffer"
3283 rename-buffer))
3284 :group 'shell
3285 :version "24.3")
3287 (defcustom async-shell-command-display-buffer t
3288 "Whether to display the command buffer immediately.
3289 If t, display the buffer immediately; if nil, wait until there
3290 is output."
3291 :type '(choice (const :tag "Display buffer immediately"
3293 (const :tag "Display buffer on output"
3294 nil))
3295 :group 'shell
3296 :version "26.1")
3298 (defun shell-command--save-pos-or-erase ()
3299 "Store a buffer position or erase the buffer.
3300 See `shell-command-dont-erase-buffer'."
3301 (let ((sym shell-command-dont-erase-buffer)
3302 pos)
3303 (setq buffer-read-only nil)
3304 ;; Setting buffer-read-only to nil doesn't suffice
3305 ;; if some text has a non-nil read-only property,
3306 ;; which comint sometimes adds for prompts.
3307 (setq pos
3308 (cond ((eq sym 'save-point) (point))
3309 ((eq sym 'beg-last-out) (point-max))
3310 ((not sym)
3311 (let ((inhibit-read-only t))
3312 (erase-buffer) nil))))
3313 (when pos
3314 (goto-char (point-max))
3315 (push (cons (current-buffer) pos)
3316 shell-command-saved-pos))))
3318 (defun shell-command--set-point-after-cmd (&optional buffer)
3319 "Set point in BUFFER after command complete.
3320 BUFFER is the output buffer of the command; if nil, then defaults
3321 to the current BUFFER.
3322 Set point to the `cdr' of the element in `shell-command-saved-pos'
3323 whose `car' is BUFFER."
3324 (when shell-command-dont-erase-buffer
3325 (let* ((sym shell-command-dont-erase-buffer)
3326 (buf (or buffer (current-buffer)))
3327 (pos (alist-get buf shell-command-saved-pos)))
3328 (setq shell-command-saved-pos
3329 (assq-delete-all buf shell-command-saved-pos))
3330 (when (buffer-live-p buf)
3331 (let ((win (car (get-buffer-window-list buf)))
3332 (pmax (with-current-buffer buf (point-max))))
3333 (unless (and pos (memq sym '(save-point beg-last-out)))
3334 (setq pos pmax))
3335 ;; Set point in the window displaying buf, if any; otherwise
3336 ;; display buf temporary in selected frame and set the point.
3337 (if win
3338 (set-window-point win pos)
3339 (save-window-excursion
3340 (let ((win (display-buffer
3342 '(nil (inhibit-switch-frame . t)))))
3343 (set-window-point win pos)))))))))
3345 (defun async-shell-command (command &optional output-buffer error-buffer)
3346 "Execute string COMMAND asynchronously in background.
3348 Like `shell-command', but adds `&' at the end of COMMAND
3349 to execute it asynchronously.
3351 The output appears in the buffer `*Async Shell Command*'.
3352 That buffer is in shell mode.
3354 You can configure `async-shell-command-buffer' to specify what to do
3355 when the `*Async Shell Command*' buffer is already taken by another
3356 running shell command. To run COMMAND without displaying the output
3357 in a window you can configure `display-buffer-alist' to use the action
3358 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3360 In Elisp, you will often be better served by calling `start-process'
3361 directly, since it offers more control and does not impose the use of
3362 a shell (with its need to quote arguments)."
3363 (interactive
3364 (list
3365 (read-shell-command "Async shell command: " nil nil
3366 (let ((filename
3367 (cond
3368 (buffer-file-name)
3369 ((eq major-mode 'dired-mode)
3370 (dired-get-filename nil t)))))
3371 (and filename (file-relative-name filename))))
3372 current-prefix-arg
3373 shell-command-default-error-buffer))
3374 (unless (string-match "&[ \t]*\\'" command)
3375 (setq command (concat command " &")))
3376 (shell-command command output-buffer error-buffer))
3378 (defun shell-command (command &optional output-buffer error-buffer)
3379 "Execute string COMMAND in inferior shell; display output, if any.
3380 With prefix argument, insert the COMMAND's output at point.
3382 Interactively, prompt for COMMAND in the minibuffer.
3384 If COMMAND ends in `&', execute it asynchronously.
3385 The output appears in the buffer `*Async Shell Command*'.
3386 That buffer is in shell mode. You can also use
3387 `async-shell-command' that automatically adds `&'.
3389 Otherwise, COMMAND is executed synchronously. The output appears in
3390 the buffer `*Shell Command Output*'. If the output is short enough to
3391 display in the echo area (which is determined by the variables
3392 `resize-mini-windows' and `max-mini-window-height'), it is shown
3393 there, but it is nonetheless available in buffer `*Shell Command
3394 Output*' even though that buffer is not automatically displayed.
3396 To specify a coding system for converting non-ASCII characters
3397 in the shell command output, use \\[universal-coding-system-argument] \
3398 before this command.
3400 Noninteractive callers can specify coding systems by binding
3401 `coding-system-for-read' and `coding-system-for-write'.
3403 The optional second argument OUTPUT-BUFFER, if non-nil,
3404 says to put the output in some other buffer.
3405 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3406 and insert the output there; a non-nil value of
3407 `shell-command-dont-erase-buffer' prevents the buffer from being
3408 erased. If OUTPUT-BUFFER is not a buffer and not nil, insert the
3409 output in current buffer after point leaving mark after it. This
3410 cannot be done asynchronously.
3412 If the command terminates without error, but generates output,
3413 and you did not specify \"insert it in the current buffer\",
3414 the output can be displayed in the echo area or in its buffer.
3415 If the output is short enough to display in the echo area
3416 \(determined by the variable `max-mini-window-height' if
3417 `resize-mini-windows' is non-nil), it is shown there.
3418 Otherwise, the buffer containing the output is displayed.
3420 If there is output and an error, and you did not specify \"insert it
3421 in the current buffer\", a message about the error goes at the end
3422 of the output.
3424 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3425 or buffer name to which to direct the command's standard error output.
3426 If it is nil, error output is mingled with regular output.
3427 In an interactive call, the variable `shell-command-default-error-buffer'
3428 specifies the value of ERROR-BUFFER.
3430 In Elisp, you will often be better served by calling `call-process' or
3431 `start-process' directly, since they offer more control and do not
3432 impose the use of a shell (with its need to quote arguments)."
3434 (interactive
3435 (list
3436 (read-shell-command "Shell command: " nil nil
3437 (let ((filename
3438 (cond
3439 (buffer-file-name)
3440 ((eq major-mode 'dired-mode)
3441 (dired-get-filename nil t)))))
3442 (and filename (file-relative-name filename))))
3443 current-prefix-arg
3444 shell-command-default-error-buffer))
3445 ;; Look for a handler in case default-directory is a remote file name.
3446 (let ((handler
3447 (find-file-name-handler (directory-file-name default-directory)
3448 'shell-command)))
3449 (if handler
3450 (funcall handler 'shell-command command output-buffer error-buffer)
3451 (if (and output-buffer
3452 (not (or (bufferp output-buffer) (stringp output-buffer))))
3453 ;; Output goes in current buffer.
3454 (let ((error-file
3455 (if error-buffer
3456 (make-temp-file
3457 (expand-file-name "scor"
3458 (or small-temporary-file-directory
3459 temporary-file-directory)))
3460 nil)))
3461 (barf-if-buffer-read-only)
3462 (push-mark nil t)
3463 ;; We do not use -f for csh; we will not support broken use of
3464 ;; .cshrcs. Even the BSD csh manual says to use
3465 ;; "if ($?prompt) exit" before things which are not useful
3466 ;; non-interactively. Besides, if someone wants their other
3467 ;; aliases for shell commands then they can still have them.
3468 (call-process shell-file-name nil
3469 (if error-file
3470 (list t error-file)
3472 nil shell-command-switch command)
3473 (when (and error-file (file-exists-p error-file))
3474 (if (< 0 (nth 7 (file-attributes error-file)))
3475 (with-current-buffer (get-buffer-create error-buffer)
3476 (let ((pos-from-end (- (point-max) (point))))
3477 (or (bobp)
3478 (insert "\f\n"))
3479 ;; Do no formatting while reading error file,
3480 ;; because that can run a shell command, and we
3481 ;; don't want that to cause an infinite recursion.
3482 (format-insert-file error-file nil)
3483 ;; Put point after the inserted errors.
3484 (goto-char (- (point-max) pos-from-end)))
3485 (display-buffer (current-buffer))))
3486 (delete-file error-file))
3487 ;; This is like exchange-point-and-mark, but doesn't
3488 ;; activate the mark. It is cleaner to avoid activation,
3489 ;; even though the command loop would deactivate the mark
3490 ;; because we inserted text.
3491 (goto-char (prog1 (mark t)
3492 (set-marker (mark-marker) (point)
3493 (current-buffer)))))
3494 ;; Output goes in a separate buffer.
3495 ;; Preserve the match data in case called from a program.
3496 ;; FIXME: It'd be ridiculous for an Elisp function to call
3497 ;; shell-command and assume that it won't mess the match-data!
3498 (save-match-data
3499 (if (string-match "[ \t]*&[ \t]*\\'" command)
3500 ;; Command ending with ampersand means asynchronous.
3501 (let* ((buffer (get-buffer-create
3502 (or output-buffer "*Async Shell Command*")))
3503 (bname (buffer-name buffer))
3504 (directory default-directory)
3505 proc)
3506 ;; Remove the ampersand.
3507 (setq command (substring command 0 (match-beginning 0)))
3508 ;; Ask the user what to do with already running process.
3509 (setq proc (get-buffer-process buffer))
3510 (when proc
3511 (cond
3512 ((eq async-shell-command-buffer 'confirm-kill-process)
3513 ;; If will kill a process, query first.
3514 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3515 (kill-process proc)
3516 (error "Shell command in progress")))
3517 ((eq async-shell-command-buffer 'confirm-new-buffer)
3518 ;; If will create a new buffer, query first.
3519 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3520 (setq buffer (generate-new-buffer bname))
3521 (error "Shell command in progress")))
3522 ((eq async-shell-command-buffer 'new-buffer)
3523 ;; It will create a new buffer.
3524 (setq buffer (generate-new-buffer bname)))
3525 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3526 ;; If will rename the buffer, query first.
3527 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3528 (progn
3529 (with-current-buffer buffer
3530 (rename-uniquely))
3531 (setq buffer (get-buffer-create bname)))
3532 (error "Shell command in progress")))
3533 ((eq async-shell-command-buffer 'rename-buffer)
3534 ;; It will rename the buffer.
3535 (with-current-buffer buffer
3536 (rename-uniquely))
3537 (setq buffer (get-buffer-create bname)))))
3538 (with-current-buffer buffer
3539 (shell-command--save-pos-or-erase)
3540 (setq default-directory directory)
3541 (setq proc (start-process "Shell" buffer shell-file-name
3542 shell-command-switch command))
3543 (setq mode-line-process '(":%s"))
3544 (require 'shell) (shell-mode)
3545 (set-process-sentinel proc 'shell-command-sentinel)
3546 ;; Use the comint filter for proper handling of
3547 ;; carriage motion (see comint-inhibit-carriage-motion).
3548 (set-process-filter proc 'comint-output-filter)
3549 (if async-shell-command-display-buffer
3550 ;; Display buffer immediately.
3551 (display-buffer buffer '(nil (allow-no-window . t)))
3552 ;; Defer displaying buffer until first process output.
3553 ;; Use disposable named advice so that the buffer is
3554 ;; displayed at most once per process lifetime.
3555 (let ((nonce (make-symbol "nonce")))
3556 (add-function :before (process-filter proc)
3557 (lambda (proc _string)
3558 (let ((buf (process-buffer proc)))
3559 (when (buffer-live-p buf)
3560 (remove-function (process-filter proc)
3561 nonce)
3562 (display-buffer buf))))
3563 `((name . ,nonce)))))))
3564 ;; Otherwise, command is executed synchronously.
3565 (shell-command-on-region (point) (point) command
3566 output-buffer nil error-buffer)))))))
3568 (defun display-message-or-buffer (message &optional buffer-name action frame)
3569 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3570 MESSAGE may be either a string or a buffer.
3572 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3573 for maximum height of the echo area, as defined by `max-mini-window-height'
3574 if `resize-mini-windows' is non-nil.
3576 Returns either the string shown in the echo area, or when a pop-up
3577 buffer is used, the window used to display it.
3579 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3580 name of the buffer used to display it in the case where a pop-up buffer
3581 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3582 string and it is displayed in the echo area, it is not specified whether
3583 the contents are inserted into the buffer anyway.
3585 Optional arguments ACTION and FRAME are as for `display-buffer',
3586 and are only used if a pop-up buffer is displayed."
3587 (cond ((and (stringp message) (not (string-match "\n" message)))
3588 ;; Trivial case where we can use the echo area
3589 (message "%s" message))
3590 ((and (stringp message)
3591 (= (string-match "\n" message) (1- (length message))))
3592 ;; Trivial case where we can just remove single trailing newline
3593 (message "%s" (substring message 0 (1- (length message)))))
3595 ;; General case
3596 (with-current-buffer
3597 (if (bufferp message)
3598 message
3599 (get-buffer-create (or buffer-name "*Message*")))
3601 (unless (bufferp message)
3602 (erase-buffer)
3603 (insert message))
3605 (let ((lines
3606 (if (= (buffer-size) 0)
3608 (count-screen-lines nil nil nil (minibuffer-window)))))
3609 (cond ((= lines 0))
3610 ((and (or (<= lines 1)
3611 (<= lines
3612 (if resize-mini-windows
3613 (cond ((floatp max-mini-window-height)
3614 (* (frame-height)
3615 max-mini-window-height))
3616 ((integerp max-mini-window-height)
3617 max-mini-window-height)
3620 1)))
3621 ;; Don't use the echo area if the output buffer is
3622 ;; already displayed in the selected frame.
3623 (not (get-buffer-window (current-buffer))))
3624 ;; Echo area
3625 (goto-char (point-max))
3626 (when (bolp)
3627 (backward-char 1))
3628 (message "%s" (buffer-substring (point-min) (point))))
3630 ;; Buffer
3631 (goto-char (point-min))
3632 (display-buffer (current-buffer) action frame))))))))
3635 ;; We have a sentinel to prevent insertion of a termination message
3636 ;; in the buffer itself, and to set the point in the buffer when
3637 ;; `shell-command-dont-erase-buffer' is non-nil.
3638 (defun shell-command-sentinel (process signal)
3639 (when (memq (process-status process) '(exit signal))
3640 (shell-command--set-point-after-cmd (process-buffer process))
3641 (message "%s: %s."
3642 (car (cdr (cdr (process-command process))))
3643 (substring signal 0 -1))))
3645 (defun shell-command-on-region (start end command
3646 &optional output-buffer replace
3647 error-buffer display-error-buffer
3648 region-noncontiguous-p)
3649 "Execute string COMMAND in inferior shell with region as input.
3650 Normally display output (if any) in temp buffer `*Shell Command Output*';
3651 Prefix arg means replace the region with it. Return the exit code of
3652 COMMAND.
3654 To specify a coding system for converting non-ASCII characters
3655 in the input and output to the shell command, use \\[universal-coding-system-argument]
3656 before this command. By default, the input (from the current buffer)
3657 is encoded using coding-system specified by `process-coding-system-alist',
3658 falling back to `default-process-coding-system' if no match for COMMAND
3659 is found in `process-coding-system-alist'.
3661 Noninteractive callers can specify coding systems by binding
3662 `coding-system-for-read' and `coding-system-for-write'.
3664 If the command generates output, the output may be displayed
3665 in the echo area or in a buffer.
3666 If the output is short enough to display in the echo area
3667 \(determined by the variable `max-mini-window-height' if
3668 `resize-mini-windows' is non-nil), it is shown there.
3669 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3670 The output is available in that buffer in both cases.
3672 If there is output and an error, a message about the error
3673 appears at the end of the output.
3675 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3676 command's output. If the value is a buffer or buffer name,
3677 erase that buffer and insert the output there; a non-nil value of
3678 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3679 If the value is nil, use the buffer `*Shell Command Output*'.
3680 Any other non-nil value means to insert the output in the
3681 current buffer after START.
3683 Optional fifth arg REPLACE, if non-nil, means to insert the
3684 output in place of text from START to END, putting point and mark
3685 around it.
3687 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3688 or buffer name to which to direct the command's standard error
3689 output. If nil, error output is mingled with regular output.
3690 When called interactively, `shell-command-default-error-buffer'
3691 is used for ERROR-BUFFER.
3693 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3694 display the error buffer if there were any errors. When called
3695 interactively, this is t."
3696 (interactive (let (string)
3697 (unless (mark)
3698 (user-error "The mark is not set now, so there is no region"))
3699 ;; Do this before calling region-beginning
3700 ;; and region-end, in case subprocess output
3701 ;; relocates them while we are in the minibuffer.
3702 (setq string (read-shell-command "Shell command on region: "))
3703 ;; call-interactively recognizes region-beginning and
3704 ;; region-end specially, leaving them in the history.
3705 (list (region-beginning) (region-end)
3706 string
3707 current-prefix-arg
3708 current-prefix-arg
3709 shell-command-default-error-buffer
3711 (region-noncontiguous-p))))
3712 (let ((error-file
3713 (if error-buffer
3714 (make-temp-file
3715 (expand-file-name "scor"
3716 (or small-temporary-file-directory
3717 temporary-file-directory)))
3718 nil))
3719 exit-status)
3720 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3721 (if region-noncontiguous-p
3722 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3723 output)
3724 (with-temp-buffer
3725 (insert input)
3726 (call-process-region (point-min) (point-max)
3727 shell-file-name t t
3728 nil shell-command-switch
3729 command)
3730 (setq output (split-string (buffer-string) "\n")))
3731 (goto-char start)
3732 (funcall region-insert-function output))
3733 (if (or replace
3734 (and output-buffer
3735 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3736 ;; Replace specified region with output from command.
3737 (let ((swap (and replace (< start end))))
3738 ;; Don't muck with mark unless REPLACE says we should.
3739 (goto-char start)
3740 (and replace (push-mark (point) 'nomsg))
3741 (setq exit-status
3742 (call-shell-region start end command replace
3743 (if error-file
3744 (list t error-file)
3745 t)))
3746 ;; It is rude to delete a buffer which the command is not using.
3747 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3748 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3749 ;; (kill-buffer shell-buffer)))
3750 ;; Don't muck with mark unless REPLACE says we should.
3751 (and replace swap (exchange-point-and-mark)))
3752 ;; No prefix argument: put the output in a temp buffer,
3753 ;; replacing its entire contents.
3754 (let ((buffer (get-buffer-create
3755 (or output-buffer "*Shell Command Output*"))))
3756 (unwind-protect
3757 (if (and (eq buffer (current-buffer))
3758 (or (not shell-command-dont-erase-buffer)
3759 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3760 (not (region-active-p)))))
3761 ;; If the input is the same buffer as the output,
3762 ;; delete everything but the specified region,
3763 ;; then replace that region with the output.
3764 (progn (setq buffer-read-only nil)
3765 (delete-region (max start end) (point-max))
3766 (delete-region (point-min) (min start end))
3767 (setq exit-status
3768 (call-process-region (point-min) (point-max)
3769 shell-file-name t
3770 (if error-file
3771 (list t error-file)
3773 nil shell-command-switch
3774 command)))
3775 ;; Clear the output buffer, then run the command with
3776 ;; output there.
3777 (let ((directory default-directory))
3778 (with-current-buffer buffer
3779 (if (not output-buffer)
3780 (setq default-directory directory))
3781 (shell-command--save-pos-or-erase)))
3782 (setq exit-status
3783 (call-shell-region start end command nil
3784 (if error-file
3785 (list buffer error-file)
3786 buffer))))
3787 ;; Report the output.
3788 (with-current-buffer buffer
3789 (setq mode-line-process
3790 (cond ((null exit-status)
3791 " - Error")
3792 ((stringp exit-status)
3793 (format " - Signal [%s]" exit-status))
3794 ((not (equal 0 exit-status))
3795 (format " - Exit [%d]" exit-status)))))
3796 (if (with-current-buffer buffer (> (point-max) (point-min)))
3797 ;; There's some output, display it
3798 (progn
3799 (display-message-or-buffer buffer)
3800 (shell-command--set-point-after-cmd buffer))
3801 ;; No output; error?
3802 (let ((output
3803 (if (and error-file
3804 (< 0 (nth 7 (file-attributes error-file))))
3805 (format "some error output%s"
3806 (if shell-command-default-error-buffer
3807 (format " to the \"%s\" buffer"
3808 shell-command-default-error-buffer)
3809 ""))
3810 "no output")))
3811 (cond ((null exit-status)
3812 (message "(Shell command failed with error)"))
3813 ((equal 0 exit-status)
3814 (message "(Shell command succeeded with %s)"
3815 output))
3816 ((stringp exit-status)
3817 (message "(Shell command killed by signal %s)"
3818 exit-status))
3820 (message "(Shell command failed with code %d and %s)"
3821 exit-status output))))
3822 ;; Don't kill: there might be useful info in the undo-log.
3823 ;; (kill-buffer buffer)
3824 )))))
3826 (when (and error-file (file-exists-p error-file))
3827 (if (< 0 (nth 7 (file-attributes error-file)))
3828 (with-current-buffer (get-buffer-create error-buffer)
3829 (let ((pos-from-end (- (point-max) (point))))
3830 (or (bobp)
3831 (insert "\f\n"))
3832 ;; Do no formatting while reading error file,
3833 ;; because that can run a shell command, and we
3834 ;; don't want that to cause an infinite recursion.
3835 (format-insert-file error-file nil)
3836 ;; Put point after the inserted errors.
3837 (goto-char (- (point-max) pos-from-end)))
3838 (and display-error-buffer
3839 (display-buffer (current-buffer)))))
3840 (delete-file error-file))
3841 exit-status))
3843 (defun shell-command-to-string (command)
3844 "Execute shell command COMMAND and return its output as a string."
3845 (with-output-to-string
3846 (with-current-buffer
3847 standard-output
3848 (process-file shell-file-name nil t nil shell-command-switch command))))
3850 (defun process-file (program &optional infile buffer display &rest args)
3851 "Process files synchronously in a separate process.
3852 Similar to `call-process', but may invoke a file handler based on
3853 `default-directory'. The current working directory of the
3854 subprocess is `default-directory'.
3856 File names in INFILE and BUFFER are handled normally, but file
3857 names in ARGS should be relative to `default-directory', as they
3858 are passed to the process verbatim. (This is a difference to
3859 `call-process' which does not support file handlers for INFILE
3860 and BUFFER.)
3862 Some file handlers might not support all variants, for example
3863 they might behave as if DISPLAY was nil, regardless of the actual
3864 value passed."
3865 (let ((fh (find-file-name-handler default-directory 'process-file))
3866 lc stderr-file)
3867 (unwind-protect
3868 (if fh (apply fh 'process-file program infile buffer display args)
3869 (when infile (setq lc (file-local-copy infile)))
3870 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3871 (make-temp-file "emacs")))
3872 (prog1
3873 (apply 'call-process program
3874 (or lc infile)
3875 (if stderr-file (list (car buffer) stderr-file) buffer)
3876 display args)
3877 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3878 (when stderr-file (delete-file stderr-file))
3879 (when lc (delete-file lc)))))
3881 (defvar process-file-side-effects t
3882 "Whether a call of `process-file' changes remote files.
3884 By default, this variable is always set to t, meaning that a
3885 call of `process-file' could potentially change any file on a
3886 remote host. When set to nil, a file handler could optimize
3887 its behavior with respect to remote file attribute caching.
3889 You should only ever change this variable with a let-binding;
3890 never with `setq'.")
3892 (defun start-file-process (name buffer program &rest program-args)
3893 "Start a program in a subprocess. Return the process object for it.
3895 Similar to `start-process', but may invoke a file handler based on
3896 `default-directory'. See Info node `(elisp)Magic File Names'.
3898 This handler ought to run PROGRAM, perhaps on the local host,
3899 perhaps on a remote host that corresponds to `default-directory'.
3900 In the latter case, the local part of `default-directory' becomes
3901 the working directory of the process.
3903 PROGRAM and PROGRAM-ARGS might be file names. They are not
3904 objects of file handler invocation. File handlers might not
3905 support pty association, if PROGRAM is nil."
3906 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3907 (if fh (apply fh 'start-file-process name buffer program program-args)
3908 (apply 'start-process name buffer program program-args))))
3910 ;;;; Process menu
3912 (defvar tabulated-list-format)
3913 (defvar tabulated-list-entries)
3914 (defvar tabulated-list-sort-key)
3915 (declare-function tabulated-list-init-header "tabulated-list" ())
3916 (declare-function tabulated-list-print "tabulated-list"
3917 (&optional remember-pos update))
3919 (defvar process-menu-query-only nil)
3921 (defvar process-menu-mode-map
3922 (let ((map (make-sparse-keymap)))
3923 (define-key map [?d] 'process-menu-delete-process)
3924 map))
3926 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3927 "Major mode for listing the processes called by Emacs."
3928 (setq tabulated-list-format [("Process" 15 t)
3929 ("PID" 7 t)
3930 ("Status" 7 t)
3931 ("Buffer" 15 t)
3932 ("TTY" 12 t)
3933 ("Command" 0 t)])
3934 (make-local-variable 'process-menu-query-only)
3935 (setq tabulated-list-sort-key (cons "Process" nil))
3936 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t))
3938 (defun process-menu-delete-process ()
3939 "Kill process at point in a `list-processes' buffer."
3940 (interactive)
3941 (let ((pos (point)))
3942 (delete-process (tabulated-list-get-id))
3943 (revert-buffer)
3944 (goto-char (min pos (point-max)))
3945 (if (eobp)
3946 (forward-line -1)
3947 (beginning-of-line))))
3949 (defun list-processes--refresh ()
3950 "Recompute the list of processes for the Process List buffer.
3951 Also, delete any process that is exited or signaled."
3952 (setq tabulated-list-entries nil)
3953 (dolist (p (process-list))
3954 (cond ((memq (process-status p) '(exit signal closed))
3955 (delete-process p))
3956 ((or (not process-menu-query-only)
3957 (process-query-on-exit-flag p))
3958 (let* ((buf (process-buffer p))
3959 (type (process-type p))
3960 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
3961 (name (process-name p))
3962 (status (symbol-name (process-status p)))
3963 (buf-label (if (buffer-live-p buf)
3964 `(,(buffer-name buf)
3965 face link
3966 help-echo ,(format-message
3967 "Visit buffer `%s'"
3968 (buffer-name buf))
3969 follow-link t
3970 process-buffer ,buf
3971 action process-menu-visit-buffer)
3972 "--"))
3973 (tty (or (process-tty-name p) "--"))
3974 (cmd
3975 (if (memq type '(network serial))
3976 (let ((contact (process-contact p t)))
3977 (if (eq type 'network)
3978 (format "(%s %s)"
3979 (if (plist-get contact :type)
3980 "datagram"
3981 "network")
3982 (if (plist-get contact :server)
3983 (format "server on %s"
3985 (plist-get contact :host)
3986 (plist-get contact :local)))
3987 (format "connection to %s"
3988 (plist-get contact :host))))
3989 (format "(serial port %s%s)"
3990 (or (plist-get contact :port) "?")
3991 (let ((speed (plist-get contact :speed)))
3992 (if speed
3993 (format " at %s b/s" speed)
3994 "")))))
3995 (mapconcat 'identity (process-command p) " "))))
3996 (push (list p (vector name pid status buf-label tty cmd))
3997 tabulated-list-entries)))))
3998 (tabulated-list-init-header))
4000 (defun process-menu-visit-buffer (button)
4001 (display-buffer (button-get button 'process-buffer)))
4003 (defun list-processes (&optional query-only buffer)
4004 "Display a list of all processes that are Emacs sub-processes.
4005 If optional argument QUERY-ONLY is non-nil, only processes with
4006 the query-on-exit flag set are listed.
4007 Any process listed as exited or signaled is actually eliminated
4008 after the listing is made.
4009 Optional argument BUFFER specifies a buffer to use, instead of
4010 \"*Process List*\".
4011 The return value is always nil.
4013 This function lists only processes that were launched by Emacs. To
4014 see other processes running on the system, use `list-system-processes'."
4015 (interactive)
4016 (or (fboundp 'process-list)
4017 (error "Asynchronous subprocesses are not supported on this system"))
4018 (unless (bufferp buffer)
4019 (setq buffer (get-buffer-create "*Process List*")))
4020 (with-current-buffer buffer
4021 (process-menu-mode)
4022 (setq process-menu-query-only query-only)
4023 (list-processes--refresh)
4024 (tabulated-list-print))
4025 (display-buffer buffer)
4026 nil)
4028 ;;;; Prefix commands
4030 (setq prefix-command--needs-update nil)
4031 (setq prefix-command--last-echo nil)
4033 (defun internal-echo-keystrokes-prefix ()
4034 ;; BEWARE: Called directly from C code.
4035 ;; If the return value is non-nil, it means we are in the middle of
4036 ;; a command with prefix, such as a command invoked with prefix-arg.
4037 (if (not prefix-command--needs-update)
4038 prefix-command--last-echo
4039 (setq prefix-command--last-echo
4040 (let ((strs nil))
4041 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
4042 (lambda (fun) (push (funcall fun) strs)))
4043 (setq strs (delq nil strs))
4044 (when strs (mapconcat #'identity strs " "))))))
4046 (defvar prefix-command-echo-keystrokes-functions nil
4047 "Abnormal hook which constructs the description of the current prefix state.
4048 Each function is called with no argument, should return a string or nil.")
4050 (defun prefix-command-update ()
4051 "Update state of prefix commands.
4052 Call it whenever you change the \"prefix command state\"."
4053 (setq prefix-command--needs-update t))
4055 (defvar prefix-command-preserve-state-hook nil
4056 "Normal hook run when a command needs to preserve the prefix.")
4058 (defun prefix-command-preserve-state ()
4059 "Pass the current prefix command state to the next command.
4060 Should be called by all prefix commands.
4061 Runs `prefix-command-preserve-state-hook'."
4062 (run-hooks 'prefix-command-preserve-state-hook)
4063 ;; If the current command is a prefix command, we don't want the next (real)
4064 ;; command to have `last-command' set to, say, `universal-argument'.
4065 (setq this-command last-command)
4066 (setq real-this-command real-last-command)
4067 (prefix-command-update))
4069 (defun reset-this-command-lengths ()
4070 (declare (obsolete prefix-command-preserve-state "25.1"))
4071 nil)
4073 ;;;;; The main prefix command.
4075 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4077 (add-hook 'prefix-command-echo-keystrokes-functions
4078 #'universal-argument--description)
4079 (defun universal-argument--description ()
4080 (when prefix-arg
4081 (concat "C-u"
4082 (pcase prefix-arg
4083 (`(-) " -")
4084 (`(,(and (pred integerp) n))
4085 (let ((str ""))
4086 (while (and (> n 4) (= (mod n 4) 0))
4087 (setq str (concat str " C-u"))
4088 (setq n (/ n 4)))
4089 (if (= n 4) str (format " %s" prefix-arg))))
4090 (_ (format " %s" prefix-arg))))))
4092 (add-hook 'prefix-command-preserve-state-hook
4093 #'universal-argument--preserve)
4094 (defun universal-argument--preserve ()
4095 (setq prefix-arg current-prefix-arg))
4097 (defvar universal-argument-map
4098 (let ((map (make-sparse-keymap))
4099 (universal-argument-minus
4100 ;; For backward compatibility, minus with no modifiers is an ordinary
4101 ;; command if digits have already been entered.
4102 `(menu-item "" negative-argument
4103 :filter ,(lambda (cmd)
4104 (if (integerp prefix-arg) nil cmd)))))
4105 (define-key map [switch-frame]
4106 (lambda (e) (interactive "e")
4107 (handle-switch-frame e) (universal-argument--mode)))
4108 (define-key map [?\C-u] 'universal-argument-more)
4109 (define-key map [?-] universal-argument-minus)
4110 (define-key map [?0] 'digit-argument)
4111 (define-key map [?1] 'digit-argument)
4112 (define-key map [?2] 'digit-argument)
4113 (define-key map [?3] 'digit-argument)
4114 (define-key map [?4] 'digit-argument)
4115 (define-key map [?5] 'digit-argument)
4116 (define-key map [?6] 'digit-argument)
4117 (define-key map [?7] 'digit-argument)
4118 (define-key map [?8] 'digit-argument)
4119 (define-key map [?9] 'digit-argument)
4120 (define-key map [kp-0] 'digit-argument)
4121 (define-key map [kp-1] 'digit-argument)
4122 (define-key map [kp-2] 'digit-argument)
4123 (define-key map [kp-3] 'digit-argument)
4124 (define-key map [kp-4] 'digit-argument)
4125 (define-key map [kp-5] 'digit-argument)
4126 (define-key map [kp-6] 'digit-argument)
4127 (define-key map [kp-7] 'digit-argument)
4128 (define-key map [kp-8] 'digit-argument)
4129 (define-key map [kp-9] 'digit-argument)
4130 (define-key map [kp-subtract] universal-argument-minus)
4131 map)
4132 "Keymap used while processing \\[universal-argument].")
4134 (defun universal-argument--mode ()
4135 (prefix-command-update)
4136 (set-transient-map universal-argument-map nil))
4138 (defun universal-argument ()
4139 "Begin a numeric argument for the following command.
4140 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4141 \\[universal-argument] following the digits or minus sign ends the argument.
4142 \\[universal-argument] without digits or minus sign provides 4 as argument.
4143 Repeating \\[universal-argument] without digits or minus sign
4144 multiplies the argument by 4 each time.
4145 For some commands, just \\[universal-argument] by itself serves as a flag
4146 which is different in effect from any particular numeric argument.
4147 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4148 (interactive)
4149 (prefix-command-preserve-state)
4150 (setq prefix-arg (list 4))
4151 (universal-argument--mode))
4153 (defun universal-argument-more (arg)
4154 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4155 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4156 (interactive "P")
4157 (prefix-command-preserve-state)
4158 (setq prefix-arg (if (consp arg)
4159 (list (* 4 (car arg)))
4160 (if (eq arg '-)
4161 (list -4)
4162 arg)))
4163 (when (consp prefix-arg) (universal-argument--mode)))
4165 (defun negative-argument (arg)
4166 "Begin a negative numeric argument for the next command.
4167 \\[universal-argument] following digits or minus sign ends the argument."
4168 (interactive "P")
4169 (prefix-command-preserve-state)
4170 (setq prefix-arg (cond ((integerp arg) (- arg))
4171 ((eq arg '-) nil)
4172 (t '-)))
4173 (universal-argument--mode))
4175 (defun digit-argument (arg)
4176 "Part of the numeric argument for the next command.
4177 \\[universal-argument] following digits or minus sign ends the argument."
4178 (interactive "P")
4179 (prefix-command-preserve-state)
4180 (let* ((char (if (integerp last-command-event)
4181 last-command-event
4182 (get last-command-event 'ascii-character)))
4183 (digit (- (logand char ?\177) ?0)))
4184 (setq prefix-arg (cond ((integerp arg)
4185 (+ (* arg 10)
4186 (if (< arg 0) (- digit) digit)))
4187 ((eq arg '-)
4188 ;; Treat -0 as just -, so that -01 will work.
4189 (if (zerop digit) '- (- digit)))
4191 digit))))
4192 (universal-argument--mode))
4195 (defvar filter-buffer-substring-functions nil
4196 "This variable is a wrapper hook around `buffer-substring--filter'.
4197 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4198 (make-obsolete-variable 'filter-buffer-substring-functions
4199 'filter-buffer-substring-function "24.4")
4201 (defvar filter-buffer-substring-function #'buffer-substring--filter
4202 "Function to perform the filtering in `filter-buffer-substring'.
4203 The function is called with the same 3 arguments (BEG END DELETE)
4204 that `filter-buffer-substring' received. It should return the
4205 buffer substring between BEG and END, after filtering. If DELETE is
4206 non-nil, it should delete the text between BEG and END from the buffer.")
4208 (defvar buffer-substring-filters nil
4209 "List of filter functions for `buffer-substring--filter'.
4210 Each function must accept a single argument, a string, and return a string.
4211 The buffer substring is passed to the first function in the list,
4212 and the return value of each function is passed to the next.
4213 As a special convention, point is set to the start of the buffer text
4214 being operated on (i.e., the first argument of `buffer-substring--filter')
4215 before these functions are called.")
4216 (make-obsolete-variable 'buffer-substring-filters
4217 'filter-buffer-substring-function "24.1")
4219 (defun filter-buffer-substring (beg end &optional delete)
4220 "Return the buffer substring between BEG and END, after filtering.
4221 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4223 This calls the function that `filter-buffer-substring-function' specifies
4224 \(passing the same three arguments that it received) to do the work,
4225 and returns whatever it does. The default function does no filtering,
4226 unless a hook has been set.
4228 Use `filter-buffer-substring' instead of `buffer-substring',
4229 `buffer-substring-no-properties', or `delete-and-extract-region' when
4230 you want to allow filtering to take place. For example, major or minor
4231 modes can use `filter-buffer-substring-function' to extract characters
4232 that are special to a buffer, and should not be copied into other buffers."
4233 (funcall filter-buffer-substring-function beg end delete))
4235 (defun buffer-substring--filter (beg end &optional delete)
4236 "Default function to use for `filter-buffer-substring-function'.
4237 Its arguments and return value are as specified for `filter-buffer-substring'.
4238 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4239 \(see `with-wrapper-hook' for details about wrapper hooks),
4240 and the abnormal hook `buffer-substring-filters'.
4241 No filtering is done unless a hook says to."
4242 (subr--with-wrapper-hook-no-warnings
4243 filter-buffer-substring-functions (beg end delete)
4244 (cond
4245 ((or delete buffer-substring-filters)
4246 (save-excursion
4247 (goto-char beg)
4248 (let ((string (if delete (delete-and-extract-region beg end)
4249 (buffer-substring beg end))))
4250 (dolist (filter buffer-substring-filters)
4251 (setq string (funcall filter string)))
4252 string)))
4254 (buffer-substring beg end)))))
4257 ;;;; Window system cut and paste hooks.
4259 (defvar interprogram-cut-function #'gui-select-text
4260 "Function to call to make a killed region available to other programs.
4261 Most window systems provide a facility for cutting and pasting
4262 text between different programs, such as the clipboard on X and
4263 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4265 This variable holds a function that Emacs calls whenever text is
4266 put in the kill ring, to make the new kill available to other
4267 programs. The function takes one argument, TEXT, which is a
4268 string containing the text which should be made available.")
4270 (defvar interprogram-paste-function #'gui-selection-value
4271 "Function to call to get text cut from other programs.
4272 Most window systems provide a facility for cutting and pasting
4273 text between different programs, such as the clipboard on X and
4274 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4276 This variable holds a function that Emacs calls to obtain text
4277 that other programs have provided for pasting. The function is
4278 called with no arguments. If no other program has provided text
4279 to paste, the function should return nil (in which case the
4280 caller, usually `current-kill', should use the top of the Emacs
4281 kill ring). If another program has provided text to paste, the
4282 function should return that text as a string (in which case the
4283 caller should put this string in the kill ring as the latest
4284 kill).
4286 The function may also return a list of strings if the window
4287 system supports multiple selections. The first string will be
4288 used as the pasted text, but the other will be placed in the kill
4289 ring for easy access via `yank-pop'.
4291 Note that the function should return a string only if a program
4292 other than Emacs has provided a string for pasting; if Emacs
4293 provided the most recent string, the function should return nil.
4294 If it is difficult to tell whether Emacs or some other program
4295 provided the current string, it is probably good enough to return
4296 nil if the string is equal (according to `string=') to the last
4297 text Emacs provided.")
4301 ;;;; The kill ring data structure.
4303 (defvar kill-ring nil
4304 "List of killed text sequences.
4305 Since the kill ring is supposed to interact nicely with cut-and-paste
4306 facilities offered by window systems, use of this variable should
4307 interact nicely with `interprogram-cut-function' and
4308 `interprogram-paste-function'. The functions `kill-new',
4309 `kill-append', and `current-kill' are supposed to implement this
4310 interaction; you may want to use them instead of manipulating the kill
4311 ring directly.")
4313 (defcustom kill-ring-max 60
4314 "Maximum length of kill ring before oldest elements are thrown away."
4315 :type 'integer
4316 :group 'killing)
4318 (defvar kill-ring-yank-pointer nil
4319 "The tail of the kill ring whose car is the last thing yanked.")
4321 (defcustom save-interprogram-paste-before-kill nil
4322 "Save clipboard strings into kill ring before replacing them.
4323 When one selects something in another program to paste it into Emacs,
4324 but kills something in Emacs before actually pasting it,
4325 this selection is gone unless this variable is non-nil,
4326 in which case the other program's selection is saved in the `kill-ring'
4327 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4328 :type 'boolean
4329 :group 'killing
4330 :version "23.2")
4332 (defcustom kill-do-not-save-duplicates nil
4333 "Do not add a new string to `kill-ring' if it duplicates the last one.
4334 The comparison is done using `equal-including-properties'."
4335 :type 'boolean
4336 :group 'killing
4337 :version "23.2")
4339 (defun kill-new (string &optional replace)
4340 "Make STRING the latest kill in the kill ring.
4341 Set `kill-ring-yank-pointer' to point to it.
4342 If `interprogram-cut-function' is non-nil, apply it to STRING.
4343 Optional second argument REPLACE non-nil means that STRING will replace
4344 the front of the kill ring, rather than being added to the list.
4346 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4347 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4348 STRING.
4350 When the yank handler has a non-nil PARAM element, the original STRING
4351 argument is not used by `insert-for-yank'. However, since Lisp code
4352 may access and use elements from the kill ring directly, the STRING
4353 argument should still be a \"useful\" string for such uses."
4354 (unless (and kill-do-not-save-duplicates
4355 ;; Due to text properties such as 'yank-handler that
4356 ;; can alter the contents to yank, comparison using
4357 ;; `equal' is unsafe.
4358 (equal-including-properties string (car kill-ring)))
4359 (if (fboundp 'menu-bar-update-yank-menu)
4360 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4361 (when save-interprogram-paste-before-kill
4362 (let ((interprogram-paste (and interprogram-paste-function
4363 (funcall interprogram-paste-function))))
4364 (when interprogram-paste
4365 (dolist (s (if (listp interprogram-paste)
4366 (nreverse interprogram-paste)
4367 (list interprogram-paste)))
4368 (unless (and kill-do-not-save-duplicates
4369 (equal-including-properties s (car kill-ring)))
4370 (push s kill-ring))))))
4371 (unless (and kill-do-not-save-duplicates
4372 (equal-including-properties string (car kill-ring)))
4373 (if (and replace kill-ring)
4374 (setcar kill-ring string)
4375 (push string kill-ring)
4376 (if (> (length kill-ring) kill-ring-max)
4377 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4378 (setq kill-ring-yank-pointer kill-ring)
4379 (if interprogram-cut-function
4380 (funcall interprogram-cut-function string)))
4382 ;; It has been argued that this should work similar to `self-insert-command'
4383 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4384 (defcustom kill-append-merge-undo nil
4385 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4386 :type 'boolean
4387 :group 'killing
4388 :version "25.1")
4390 (defun kill-append (string before-p)
4391 "Append STRING to the end of the latest kill in the kill ring.
4392 If BEFORE-P is non-nil, prepend STRING to the kill.
4393 Also removes the last undo boundary in the current buffer,
4394 depending on `kill-append-merge-undo'.
4395 If `interprogram-cut-function' is set, pass the resulting kill to it."
4396 (let* ((cur (car kill-ring)))
4397 (kill-new (if before-p (concat string cur) (concat cur string))
4398 (or (= (length cur) 0)
4399 (equal nil (get-text-property 0 'yank-handler cur))))
4400 (when (and kill-append-merge-undo (not buffer-read-only))
4401 (let ((prev buffer-undo-list)
4402 (next (cdr buffer-undo-list)))
4403 ;; find the next undo boundary
4404 (while (car next)
4405 (pop next)
4406 (pop prev))
4407 ;; remove this undo boundary
4408 (when prev
4409 (setcdr prev (cdr next)))))))
4411 (defcustom yank-pop-change-selection nil
4412 "Whether rotating the kill ring changes the window system selection.
4413 If non-nil, whenever the kill ring is rotated (usually via the
4414 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4415 to copy the new kill to the window system selection."
4416 :type 'boolean
4417 :group 'killing
4418 :version "23.1")
4420 (defun current-kill (n &optional do-not-move)
4421 "Rotate the yanking point by N places, and then return that kill.
4422 If N is zero and `interprogram-paste-function' is set to a
4423 function that returns a string or a list of strings, and if that
4424 function doesn't return nil, then that string (or list) is added
4425 to the front of the kill ring and the string (or first string in
4426 the list) is returned as the latest kill.
4428 If N is not zero, and if `yank-pop-change-selection' is
4429 non-nil, use `interprogram-cut-function' to transfer the
4430 kill at the new yank point into the window system selection.
4432 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4433 move the yanking point; just return the Nth kill forward."
4435 (let ((interprogram-paste (and (= n 0)
4436 interprogram-paste-function
4437 (funcall interprogram-paste-function))))
4438 (if interprogram-paste
4439 (progn
4440 ;; Disable the interprogram cut function when we add the new
4441 ;; text to the kill ring, so Emacs doesn't try to own the
4442 ;; selection, with identical text.
4443 (let ((interprogram-cut-function nil))
4444 (if (listp interprogram-paste)
4445 (mapc 'kill-new (nreverse interprogram-paste))
4446 (kill-new interprogram-paste)))
4447 (car kill-ring))
4448 (or kill-ring (error "Kill ring is empty"))
4449 (let ((ARGth-kill-element
4450 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4451 (length kill-ring))
4452 kill-ring)))
4453 (unless do-not-move
4454 (setq kill-ring-yank-pointer ARGth-kill-element)
4455 (when (and yank-pop-change-selection
4456 (> n 0)
4457 interprogram-cut-function)
4458 (funcall interprogram-cut-function (car ARGth-kill-element))))
4459 (car ARGth-kill-element)))))
4463 ;;;; Commands for manipulating the kill ring.
4465 (defcustom kill-read-only-ok nil
4466 "Non-nil means don't signal an error for killing read-only text."
4467 :type 'boolean
4468 :group 'killing)
4470 (defun kill-region (beg end &optional region)
4471 "Kill (\"cut\") text between point and mark.
4472 This deletes the text from the buffer and saves it in the kill ring.
4473 The command \\[yank] can retrieve it from there.
4474 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4476 If you want to append the killed region to the last killed text,
4477 use \\[append-next-kill] before \\[kill-region].
4479 Any command that calls this function is a \"kill command\".
4480 If the previous command was also a kill command,
4481 the text killed this time appends to the text killed last time
4482 to make one entry in the kill ring.
4484 The killed text is filtered by `filter-buffer-substring' before it is
4485 saved in the kill ring, so the actual saved text might be different
4486 from what was killed.
4488 If the buffer is read-only, Emacs will beep and refrain from deleting
4489 the text, but put the text in the kill ring anyway. This means that
4490 you can use the killing commands to copy text from a read-only buffer.
4492 Lisp programs should use this function for killing text.
4493 (To delete text, use `delete-region'.)
4494 Supply two arguments, character positions BEG and END indicating the
4495 stretch of text to be killed. If the optional argument REGION is
4496 non-nil, the function ignores BEG and END, and kills the current
4497 region instead."
4498 ;; Pass mark first, then point, because the order matters when
4499 ;; calling `kill-append'.
4500 (interactive (list (mark) (point) 'region))
4501 (unless (and beg end)
4502 (user-error "The mark is not set now, so there is no region"))
4503 (condition-case nil
4504 (let ((string (if region
4505 (funcall region-extract-function 'delete)
4506 (filter-buffer-substring beg end 'delete))))
4507 (when string ;STRING is nil if BEG = END
4508 ;; Add that string to the kill ring, one way or another.
4509 (if (eq last-command 'kill-region)
4510 (kill-append string (< end beg))
4511 (kill-new string)))
4512 (when (or string (eq last-command 'kill-region))
4513 (setq this-command 'kill-region))
4514 (setq deactivate-mark t)
4515 nil)
4516 ((buffer-read-only text-read-only)
4517 ;; The code above failed because the buffer, or some of the characters
4518 ;; in the region, are read-only.
4519 ;; We should beep, in case the user just isn't aware of this.
4520 ;; However, there's no harm in putting
4521 ;; the region's text in the kill ring, anyway.
4522 (copy-region-as-kill beg end region)
4523 ;; Set this-command now, so it will be set even if we get an error.
4524 (setq this-command 'kill-region)
4525 ;; This should barf, if appropriate, and give us the correct error.
4526 (if kill-read-only-ok
4527 (progn (message "Read only text copied to kill ring") nil)
4528 ;; Signal an error if the buffer is read-only.
4529 (barf-if-buffer-read-only)
4530 ;; If the buffer isn't read-only, the text is.
4531 (signal 'text-read-only (list (current-buffer)))))))
4533 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4534 ;; to get two copies of the text when the user accidentally types M-w and
4535 ;; then corrects it with the intended C-w.
4536 (defun copy-region-as-kill (beg end &optional region)
4537 "Save the region as if killed, but don't kill it.
4538 In Transient Mark mode, deactivate the mark.
4539 If `interprogram-cut-function' is non-nil, also save the text for a window
4540 system cut and paste.
4542 The copied text is filtered by `filter-buffer-substring' before it is
4543 saved in the kill ring, so the actual saved text might be different
4544 from what was in the buffer.
4546 When called from Lisp, save in the kill ring the stretch of text
4547 between BEG and END, unless the optional argument REGION is
4548 non-nil, in which case ignore BEG and END, and save the current
4549 region instead.
4551 This command's old key binding has been given to `kill-ring-save'."
4552 ;; Pass mark first, then point, because the order matters when
4553 ;; calling `kill-append'.
4554 (interactive (list (mark) (point)
4555 (prefix-numeric-value current-prefix-arg)))
4556 (let ((str (if region
4557 (funcall region-extract-function nil)
4558 (filter-buffer-substring beg end))))
4559 (if (eq last-command 'kill-region)
4560 (kill-append str (< end beg))
4561 (kill-new str)))
4562 (setq deactivate-mark t)
4563 nil)
4565 (defun kill-ring-save (beg end &optional region)
4566 "Save the region as if killed, but don't kill it.
4567 In Transient Mark mode, deactivate the mark.
4568 If `interprogram-cut-function' is non-nil, also save the text for a window
4569 system cut and paste.
4571 If you want to append the killed line to the last killed text,
4572 use \\[append-next-kill] before \\[kill-ring-save].
4574 The copied text is filtered by `filter-buffer-substring' before it is
4575 saved in the kill ring, so the actual saved text might be different
4576 from what was in the buffer.
4578 When called from Lisp, save in the kill ring the stretch of text
4579 between BEG and END, unless the optional argument REGION is
4580 non-nil, in which case ignore BEG and END, and save the current
4581 region instead.
4583 This command is similar to `copy-region-as-kill', except that it gives
4584 visual feedback indicating the extent of the region being copied."
4585 ;; Pass mark first, then point, because the order matters when
4586 ;; calling `kill-append'.
4587 (interactive (list (mark) (point)
4588 (prefix-numeric-value current-prefix-arg)))
4589 (copy-region-as-kill beg end region)
4590 ;; This use of called-interactively-p is correct because the code it
4591 ;; controls just gives the user visual feedback.
4592 (if (called-interactively-p 'interactive)
4593 (indicate-copied-region)))
4595 (defun indicate-copied-region (&optional message-len)
4596 "Indicate that the region text has been copied interactively.
4597 If the mark is visible in the selected window, blink the cursor
4598 between point and mark if there is currently no active region
4599 highlighting.
4601 If the mark lies outside the selected window, display an
4602 informative message containing a sample of the copied text. The
4603 optional argument MESSAGE-LEN, if non-nil, specifies the length
4604 of this sample text; it defaults to 40."
4605 (let ((mark (mark t))
4606 (point (point))
4607 ;; Inhibit quitting so we can make a quit here
4608 ;; look like a C-g typed as a command.
4609 (inhibit-quit t))
4610 (if (pos-visible-in-window-p mark (selected-window))
4611 ;; Swap point-and-mark quickly so as to show the region that
4612 ;; was selected. Don't do it if the region is highlighted.
4613 (unless (and (region-active-p)
4614 (face-background 'region))
4615 ;; Swap point and mark.
4616 (set-marker (mark-marker) (point) (current-buffer))
4617 (goto-char mark)
4618 (sit-for blink-matching-delay)
4619 ;; Swap back.
4620 (set-marker (mark-marker) mark (current-buffer))
4621 (goto-char point)
4622 ;; If user quit, deactivate the mark
4623 ;; as C-g would as a command.
4624 (and quit-flag (region-active-p)
4625 (deactivate-mark)))
4626 (let ((len (min (abs (- mark point))
4627 (or message-len 40))))
4628 (if (< point mark)
4629 ;; Don't say "killed"; that is misleading.
4630 (message "Saved text until \"%s\""
4631 (buffer-substring-no-properties (- mark len) mark))
4632 (message "Saved text from \"%s\""
4633 (buffer-substring-no-properties mark (+ mark len))))))))
4635 (defun append-next-kill (&optional interactive)
4636 "Cause following command, if it kills, to add to previous kill.
4637 If the next command kills forward from point, the kill is
4638 appended to the previous killed text. If the command kills
4639 backward, the kill is prepended. Kill commands that act on the
4640 region, such as `kill-region', are regarded as killing forward if
4641 point is after mark, and killing backward if point is before
4642 mark.
4644 If the next command is not a kill command, `append-next-kill' has
4645 no effect.
4647 The argument is used for internal purposes; do not supply one."
4648 (interactive "p")
4649 ;; We don't use (interactive-p), since that breaks kbd macros.
4650 (if interactive
4651 (progn
4652 (setq this-command 'kill-region)
4653 (message "If the next command is a kill, it will append"))
4654 (setq last-command 'kill-region)))
4656 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4657 "Character set that matches bidirectional formatting control characters.")
4659 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4660 "Character set that matches any character except bidirectional controls.")
4662 (defun squeeze-bidi-context-1 (from to category replacement)
4663 "A subroutine of `squeeze-bidi-context'.
4664 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4665 (let ((pt (copy-marker from))
4666 (limit (copy-marker to))
4667 (old-pt 0)
4668 lim1)
4669 (setq lim1 limit)
4670 (goto-char pt)
4671 (while (< pt limit)
4672 (if (> pt old-pt)
4673 (move-marker lim1
4674 (save-excursion
4675 ;; L and R categories include embedding and
4676 ;; override controls, but we don't want to
4677 ;; replace them, because that might change
4678 ;; the visual order. Likewise with PDF and
4679 ;; isolate controls.
4680 (+ pt (skip-chars-forward
4681 bidi-directional-non-controls-chars
4682 limit)))))
4683 ;; Replace any run of non-RTL characters by a single LRM.
4684 (if (null (re-search-forward category lim1 t))
4685 ;; No more characters of CATEGORY, we are done.
4686 (setq pt limit)
4687 (replace-match replacement nil t)
4688 (move-marker pt (point)))
4689 (setq old-pt pt)
4690 ;; Skip directional controls, if any.
4691 (move-marker
4692 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4694 (defun squeeze-bidi-context (from to)
4695 "Replace characters between FROM and TO while keeping bidi context.
4697 This function replaces the region of text with as few characters
4698 as possible, while preserving the effect that region will have on
4699 bidirectional display before and after the region."
4700 (let ((start (set-marker (make-marker)
4701 (if (> from 0) from (+ (point-max) from))))
4702 (end (set-marker (make-marker) to))
4703 ;; This is for when they copy text with read-only text
4704 ;; properties.
4705 (inhibit-read-only t))
4706 (if (null (marker-position end))
4707 (setq end (point-max-marker)))
4708 ;; Replace each run of non-RTL characters with a single LRM.
4709 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4710 ;; Replace each run of non-LTR characters with a single RLM. Note
4711 ;; that the \cR category includes both the Arabic Letter (AL) and
4712 ;; R characters; here we ignore the distinction between them,
4713 ;; because that distinction only affects Arabic Number (AN)
4714 ;; characters, which are weak and don't affect the reordering.
4715 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4717 (defun line-substring-with-bidi-context (start end &optional no-properties)
4718 "Return buffer text between START and END with its bidi context.
4720 START and END are assumed to belong to the same physical line
4721 of buffer text. This function prepends and appends to the text
4722 between START and END bidi control characters that preserve the
4723 visual order of that text when it is inserted at some other place."
4724 (if (or (< start (point-min))
4725 (> end (point-max)))
4726 (signal 'args-out-of-range (list (current-buffer) start end)))
4727 (let ((buf (current-buffer))
4728 substr para-dir from to)
4729 (save-excursion
4730 (goto-char start)
4731 (setq para-dir (current-bidi-paragraph-direction))
4732 (setq from (line-beginning-position)
4733 to (line-end-position))
4734 (goto-char from)
4735 ;; If we don't have any mixed directional characters in the
4736 ;; entire line, we can just copy the substring without adding
4737 ;; any context.
4738 (if (or (looking-at-p "\\CR*$")
4739 (looking-at-p "\\CL*$"))
4740 (setq substr (if no-properties
4741 (buffer-substring-no-properties start end)
4742 (buffer-substring start end)))
4743 (setq substr
4744 (with-temp-buffer
4745 (if no-properties
4746 (insert-buffer-substring-no-properties buf from to)
4747 (insert-buffer-substring buf from to))
4748 (squeeze-bidi-context 1 (1+ (- start from)))
4749 (squeeze-bidi-context (- end to) nil)
4750 (buffer-substring 1 (point-max)))))
4752 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4753 ;; (1) force the string to have the same base embedding
4754 ;; direction as the paragraph direction at the source, no matter
4755 ;; what is the paragraph direction at destination; and (2) avoid
4756 ;; affecting the visual order of the surrounding text at
4757 ;; destination if there are characters of different
4758 ;; directionality there.
4759 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4760 substr "\x2069"))))
4762 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4763 "Return portion of current buffer between START and END with bidi context.
4765 This function works similar to `buffer-substring', but it prepends and
4766 appends to the text bidi directional control characters necessary to
4767 preserve the visual appearance of the text if it is inserted at another
4768 place. This is useful when the buffer substring includes bidirectional
4769 text and control characters that cause non-trivial reordering on display.
4770 If copied verbatim, such text can have a very different visual appearance,
4771 and can also change the visual appearance of the surrounding text at the
4772 destination of the copy.
4774 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4775 the text properties."
4776 (let (line-end substr)
4777 (if (or (< start (point-min))
4778 (> end (point-max)))
4779 (signal 'args-out-of-range (list (current-buffer) start end)))
4780 (save-excursion
4781 (goto-char start)
4782 (setq line-end (min end (line-end-position)))
4783 (while (< start end)
4784 (setq substr
4785 (concat substr
4786 (if substr "\n" "")
4787 (line-substring-with-bidi-context start line-end
4788 no-properties)))
4789 (forward-line 1)
4790 (setq start (point))
4791 (setq line-end (min end (line-end-position))))
4792 substr)))
4794 ;; Yanking.
4796 (defcustom yank-handled-properties
4797 '((font-lock-face . yank-handle-font-lock-face-property)
4798 (category . yank-handle-category-property))
4799 "List of special text property handling conditions for yanking.
4800 Each element should have the form (PROP . FUN), where PROP is a
4801 property symbol and FUN is a function. When the `yank' command
4802 inserts text into the buffer, it scans the inserted text for
4803 stretches of text that have `eq' values of the text property
4804 PROP; for each such stretch of text, FUN is called with three
4805 arguments: the property's value in that text, and the start and
4806 end positions of the text.
4808 This is done prior to removing the properties specified by
4809 `yank-excluded-properties'."
4810 :group 'killing
4811 :type '(repeat (cons (symbol :tag "property symbol")
4812 function))
4813 :version "24.3")
4815 ;; This is actually used in subr.el but defcustom does not work there.
4816 (defcustom yank-excluded-properties
4817 '(category field follow-link fontified font-lock-face help-echo
4818 intangible invisible keymap local-map mouse-face read-only
4819 yank-handler)
4820 "Text properties to discard when yanking.
4821 The value should be a list of text properties to discard or t,
4822 which means to discard all text properties.
4824 See also `yank-handled-properties'."
4825 :type '(choice (const :tag "All" t) (repeat symbol))
4826 :group 'killing
4827 :version "24.3")
4829 (defvar yank-window-start nil)
4830 (defvar yank-undo-function nil
4831 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4832 Function is called with two parameters, START and END corresponding to
4833 the value of the mark and point; it is guaranteed that START <= END.
4834 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4836 (defun yank-pop (&optional arg)
4837 "Replace just-yanked stretch of killed text with a different stretch.
4838 This command is allowed only immediately after a `yank' or a `yank-pop'.
4839 At such a time, the region contains a stretch of reinserted
4840 previously-killed text. `yank-pop' deletes that text and inserts in its
4841 place a different stretch of killed text.
4843 With no argument, the previous kill is inserted.
4844 With argument N, insert the Nth previous kill.
4845 If N is negative, this is a more recent kill.
4847 The sequence of kills wraps around, so that after the oldest one
4848 comes the newest one.
4850 This command honors the `yank-handled-properties' and
4851 `yank-excluded-properties' variables, and the `yank-handler' text
4852 property, in the way that `yank' does."
4853 (interactive "*p")
4854 (if (not (eq last-command 'yank))
4855 (user-error "Previous command was not a yank"))
4856 (setq this-command 'yank)
4857 (unless arg (setq arg 1))
4858 (let ((inhibit-read-only t)
4859 (before (< (point) (mark t))))
4860 (if before
4861 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4862 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4863 (setq yank-undo-function nil)
4864 (set-marker (mark-marker) (point) (current-buffer))
4865 (insert-for-yank (current-kill arg))
4866 ;; Set the window start back where it was in the yank command,
4867 ;; if possible.
4868 (set-window-start (selected-window) yank-window-start t)
4869 (if before
4870 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4871 ;; It is cleaner to avoid activation, even though the command
4872 ;; loop would deactivate the mark because we inserted text.
4873 (goto-char (prog1 (mark t)
4874 (set-marker (mark-marker) (point) (current-buffer))))))
4875 nil)
4877 (defun yank (&optional arg)
4878 "Reinsert (\"paste\") the last stretch of killed text.
4879 More precisely, reinsert the most recent kill, which is the
4880 stretch of killed text most recently killed OR yanked. Put point
4881 at the end, and set mark at the beginning without activating it.
4882 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4883 With argument N, reinsert the Nth most recent kill.
4885 This command honors the `yank-handled-properties' and
4886 `yank-excluded-properties' variables, and the `yank-handler' text
4887 property, as described below.
4889 Properties listed in `yank-handled-properties' are processed,
4890 then those listed in `yank-excluded-properties' are discarded.
4892 If STRING has a non-nil `yank-handler' property anywhere, the
4893 normal insert behavior is altered, and instead, for each contiguous
4894 segment of STRING that has a given value of the `yank-handler'
4895 property, that value is used as follows:
4897 The value of a `yank-handler' property must be a list of one to four
4898 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4899 FUNCTION, if non-nil, should be a function of one argument (the
4900 object to insert); FUNCTION is called instead of `insert'.
4901 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4902 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4903 PARAM may be a list of strings to insert as a rectangle). If PARAM
4904 is nil, then the current segment of STRING is used.
4905 If NOEXCLUDE is present and non-nil, the normal removal of
4906 `yank-excluded-properties' is not performed; instead FUNCTION is
4907 responsible for the removal. This may be necessary if FUNCTION
4908 adjusts point before or after inserting the object.
4909 UNDO, if present and non-nil, should be a function to be called
4910 by `yank-pop' to undo the insertion of the current PARAM. It is
4911 given two arguments, the start and end of the region. FUNCTION
4912 may set `yank-undo-function' to override UNDO.
4914 See also the command `yank-pop' (\\[yank-pop])."
4915 (interactive "*P")
4916 (setq yank-window-start (window-start))
4917 ;; If we don't get all the way thru, make last-command indicate that
4918 ;; for the following command.
4919 (setq this-command t)
4920 (push-mark)
4921 (insert-for-yank (current-kill (cond
4922 ((listp arg) 0)
4923 ((eq arg '-) -2)
4924 (t (1- arg)))))
4925 (if (consp arg)
4926 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4927 ;; It is cleaner to avoid activation, even though the command
4928 ;; loop would deactivate the mark because we inserted text.
4929 (goto-char (prog1 (mark t)
4930 (set-marker (mark-marker) (point) (current-buffer)))))
4931 ;; If we do get all the way thru, make this-command indicate that.
4932 (if (eq this-command t)
4933 (setq this-command 'yank))
4934 nil)
4936 (defun rotate-yank-pointer (arg)
4937 "Rotate the yanking point in the kill ring.
4938 With ARG, rotate that many kills forward (or backward, if negative)."
4939 (interactive "p")
4940 (current-kill arg))
4942 ;; Some kill commands.
4944 ;; Internal subroutine of delete-char
4945 (defun kill-forward-chars (arg)
4946 (if (listp arg) (setq arg (car arg)))
4947 (if (eq arg '-) (setq arg -1))
4948 (kill-region (point) (+ (point) arg)))
4950 ;; Internal subroutine of backward-delete-char
4951 (defun kill-backward-chars (arg)
4952 (if (listp arg) (setq arg (car arg)))
4953 (if (eq arg '-) (setq arg -1))
4954 (kill-region (point) (- (point) arg)))
4956 (defcustom backward-delete-char-untabify-method 'untabify
4957 "The method for untabifying when deleting backward.
4958 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4959 `hungry' -- delete all whitespace, both tabs and spaces;
4960 `all' -- delete all whitespace, including tabs, spaces and newlines;
4961 nil -- just delete one character."
4962 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4963 :version "20.3"
4964 :group 'killing)
4966 (defun backward-delete-char-untabify (arg &optional killp)
4967 "Delete characters backward, changing tabs into spaces.
4968 The exact behavior depends on `backward-delete-char-untabify-method'.
4969 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4970 Interactively, ARG is the prefix arg (default 1)
4971 and KILLP is t if a prefix arg was specified."
4972 (interactive "*p\nP")
4973 (when (eq backward-delete-char-untabify-method 'untabify)
4974 (let ((count arg))
4975 (save-excursion
4976 (while (and (> count 0) (not (bobp)))
4977 (if (= (preceding-char) ?\t)
4978 (let ((col (current-column)))
4979 (forward-char -1)
4980 (setq col (- col (current-column)))
4981 (insert-char ?\s col)
4982 (delete-char 1)))
4983 (forward-char -1)
4984 (setq count (1- count))))))
4985 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4986 ((eq backward-delete-char-untabify-method 'all)
4987 " \t\n\r")))
4988 (n (if skip
4989 (let* ((oldpt (point))
4990 (wh (- oldpt (save-excursion
4991 (skip-chars-backward skip)
4992 (constrain-to-field nil oldpt)))))
4993 (+ arg (if (zerop wh) 0 (1- wh))))
4994 arg)))
4995 ;; Avoid warning about delete-backward-char
4996 (with-no-warnings (delete-backward-char n killp))))
4998 (defun zap-to-char (arg char)
4999 "Kill up to and including ARGth occurrence of CHAR.
5000 Case is ignored if `case-fold-search' is non-nil in the current buffer.
5001 Goes backward if ARG is negative; error if CHAR not found."
5002 (interactive (list (prefix-numeric-value current-prefix-arg)
5003 (read-char "Zap to char: " t)))
5004 ;; Avoid "obsolete" warnings for translation-table-for-input.
5005 (with-no-warnings
5006 (if (char-table-p translation-table-for-input)
5007 (setq char (or (aref translation-table-for-input char) char))))
5008 (kill-region (point) (progn
5009 (search-forward (char-to-string char) nil nil arg)
5010 (point))))
5012 ;; kill-line and its subroutines.
5014 (defcustom kill-whole-line nil
5015 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
5016 :type 'boolean
5017 :group 'killing)
5019 (defun kill-line (&optional arg)
5020 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
5021 With prefix argument ARG, kill that many lines from point.
5022 Negative arguments kill lines backward.
5023 With zero argument, kills the text before point on the current line.
5025 When calling from a program, nil means \"no arg\",
5026 a number counts as a prefix arg.
5028 To kill a whole line, when point is not at the beginning, type \
5029 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
5031 If `show-trailing-whitespace' is non-nil, this command will just
5032 kill the rest of the current line, even if there are no nonblanks
5033 there.
5035 If option `kill-whole-line' is non-nil, then this command kills the whole line
5036 including its terminating newline, when used at the beginning of a line
5037 with no argument. As a consequence, you can always kill a whole line
5038 by typing \\[move-beginning-of-line] \\[kill-line].
5040 If you want to append the killed line to the last killed text,
5041 use \\[append-next-kill] before \\[kill-line].
5043 If the buffer is read-only, Emacs will beep and refrain from deleting
5044 the line, but put the line in the kill ring anyway. This means that
5045 you can use this command to copy text from a read-only buffer.
5046 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5047 even beep.)"
5048 (interactive "P")
5049 (kill-region (point)
5050 ;; It is better to move point to the other end of the kill
5051 ;; before killing. That way, in a read-only buffer, point
5052 ;; moves across the text that is copied to the kill ring.
5053 ;; The choice has no effect on undo now that undo records
5054 ;; the value of point from before the command was run.
5055 (progn
5056 (if arg
5057 (forward-visible-line (prefix-numeric-value arg))
5058 (if (eobp)
5059 (signal 'end-of-buffer nil))
5060 (let ((end
5061 (save-excursion
5062 (end-of-visible-line) (point))))
5063 (if (or (save-excursion
5064 ;; If trailing whitespace is visible,
5065 ;; don't treat it as nothing.
5066 (unless show-trailing-whitespace
5067 (skip-chars-forward " \t" end))
5068 (= (point) end))
5069 (and kill-whole-line (bolp)))
5070 (forward-visible-line 1)
5071 (goto-char end))))
5072 (point))))
5074 (defun kill-whole-line (&optional arg)
5075 "Kill current line.
5076 With prefix ARG, kill that many lines starting from the current line.
5077 If ARG is negative, kill backward. Also kill the preceding newline.
5078 \(This is meant to make \\[repeat] work well with negative arguments.)
5079 If ARG is zero, kill current line but exclude the trailing newline."
5080 (interactive "p")
5081 (or arg (setq arg 1))
5082 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5083 (signal 'end-of-buffer nil))
5084 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5085 (signal 'beginning-of-buffer nil))
5086 (unless (eq last-command 'kill-region)
5087 (kill-new "")
5088 (setq last-command 'kill-region))
5089 (cond ((zerop arg)
5090 ;; We need to kill in two steps, because the previous command
5091 ;; could have been a kill command, in which case the text
5092 ;; before point needs to be prepended to the current kill
5093 ;; ring entry and the text after point appended. Also, we
5094 ;; need to use save-excursion to avoid copying the same text
5095 ;; twice to the kill ring in read-only buffers.
5096 (save-excursion
5097 (kill-region (point) (progn (forward-visible-line 0) (point))))
5098 (kill-region (point) (progn (end-of-visible-line) (point))))
5099 ((< arg 0)
5100 (save-excursion
5101 (kill-region (point) (progn (end-of-visible-line) (point))))
5102 (kill-region (point)
5103 (progn (forward-visible-line (1+ arg))
5104 (unless (bobp) (backward-char))
5105 (point))))
5107 (save-excursion
5108 (kill-region (point) (progn (forward-visible-line 0) (point))))
5109 (kill-region (point)
5110 (progn (forward-visible-line arg) (point))))))
5112 (defun forward-visible-line (arg)
5113 "Move forward by ARG lines, ignoring currently invisible newlines only.
5114 If ARG is negative, move backward -ARG lines.
5115 If ARG is zero, move to the beginning of the current line."
5116 (condition-case nil
5117 (if (> arg 0)
5118 (progn
5119 (while (> arg 0)
5120 (or (zerop (forward-line 1))
5121 (signal 'end-of-buffer nil))
5122 ;; If the newline we just skipped is invisible,
5123 ;; don't count it.
5124 (let ((prop
5125 (get-char-property (1- (point)) 'invisible)))
5126 (if (if (eq buffer-invisibility-spec t)
5127 prop
5128 (or (memq prop buffer-invisibility-spec)
5129 (assq prop buffer-invisibility-spec)))
5130 (setq arg (1+ arg))))
5131 (setq arg (1- arg)))
5132 ;; If invisible text follows, and it is a number of complete lines,
5133 ;; skip it.
5134 (let ((opoint (point)))
5135 (while (and (not (eobp))
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 (goto-char
5143 (if (get-text-property (point) 'invisible)
5144 (or (next-single-property-change (point) 'invisible)
5145 (point-max))
5146 (next-overlay-change (point)))))
5147 (unless (bolp)
5148 (goto-char opoint))))
5149 (let ((first t))
5150 (while (or first (<= arg 0))
5151 (if first
5152 (beginning-of-line)
5153 (or (zerop (forward-line -1))
5154 (signal 'beginning-of-buffer nil)))
5155 ;; If the newline we just moved to is invisible,
5156 ;; don't count it.
5157 (unless (bobp)
5158 (let ((prop
5159 (get-char-property (1- (point)) 'invisible)))
5160 (unless (if (eq buffer-invisibility-spec t)
5161 prop
5162 (or (memq prop buffer-invisibility-spec)
5163 (assq prop buffer-invisibility-spec)))
5164 (setq arg (1+ arg)))))
5165 (setq first nil))
5166 ;; If invisible text follows, and it is a number of complete lines,
5167 ;; skip it.
5168 (let ((opoint (point)))
5169 (while (and (not (bobp))
5170 (let ((prop
5171 (get-char-property (1- (point)) 'invisible)))
5172 (if (eq buffer-invisibility-spec t)
5173 prop
5174 (or (memq prop buffer-invisibility-spec)
5175 (assq prop buffer-invisibility-spec)))))
5176 (goto-char
5177 (if (get-text-property (1- (point)) 'invisible)
5178 (or (previous-single-property-change (point) 'invisible)
5179 (point-min))
5180 (previous-overlay-change (point)))))
5181 (unless (bolp)
5182 (goto-char opoint)))))
5183 ((beginning-of-buffer end-of-buffer)
5184 nil)))
5186 (defun end-of-visible-line ()
5187 "Move to end of current visible line."
5188 (end-of-line)
5189 ;; If the following character is currently invisible,
5190 ;; skip all characters with that same `invisible' property value,
5191 ;; then find the next newline.
5192 (while (and (not (eobp))
5193 (save-excursion
5194 (skip-chars-forward "^\n")
5195 (let ((prop
5196 (get-char-property (point) 'invisible)))
5197 (if (eq buffer-invisibility-spec t)
5198 prop
5199 (or (memq prop buffer-invisibility-spec)
5200 (assq prop buffer-invisibility-spec))))))
5201 (skip-chars-forward "^\n")
5202 (if (get-text-property (point) 'invisible)
5203 (goto-char (or (next-single-property-change (point) 'invisible)
5204 (point-max)))
5205 (goto-char (next-overlay-change (point))))
5206 (end-of-line)))
5208 (defun kill-current-buffer ()
5209 "Kill the current buffer.
5210 When called in the minibuffer, get out of the minibuffer
5211 using `abort-recursive-edit'.
5213 This is like `kill-this-buffer', but it doesn't have to be invoked
5214 via the menu bar, and pays no attention to the menu-bar's frame."
5215 (interactive)
5216 (let ((frame (selected-frame)))
5217 (if (and (frame-live-p frame)
5218 (not (window-minibuffer-p (frame-selected-window frame))))
5219 (kill-buffer (current-buffer))
5220 (abort-recursive-edit))))
5223 (defun insert-buffer (buffer)
5224 "Insert after point the contents of BUFFER.
5225 Puts mark after the inserted text.
5226 BUFFER may be a buffer or a buffer name."
5227 (declare (interactive-only insert-buffer-substring))
5228 (interactive
5229 (list
5230 (progn
5231 (barf-if-buffer-read-only)
5232 (read-buffer "Insert buffer: "
5233 (if (eq (selected-window) (next-window))
5234 (other-buffer (current-buffer))
5235 (window-buffer (next-window)))
5236 t))))
5237 (push-mark
5238 (save-excursion
5239 (insert-buffer-substring (get-buffer buffer))
5240 (point)))
5241 nil)
5243 (defun append-to-buffer (buffer start end)
5244 "Append to specified buffer the text of the region.
5245 It is inserted into that buffer before its point.
5247 When calling from a program, give three arguments:
5248 BUFFER (or buffer name), START and END.
5249 START and END specify the portion of the current buffer to be copied."
5250 (interactive
5251 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5252 (region-beginning) (region-end)))
5253 (let* ((oldbuf (current-buffer))
5254 (append-to (get-buffer-create buffer))
5255 (windows (get-buffer-window-list append-to t t))
5256 point)
5257 (save-excursion
5258 (with-current-buffer append-to
5259 (setq point (point))
5260 (barf-if-buffer-read-only)
5261 (insert-buffer-substring oldbuf start end)
5262 (dolist (window windows)
5263 (when (= (window-point window) point)
5264 (set-window-point window (point))))))))
5266 (defun prepend-to-buffer (buffer start end)
5267 "Prepend to specified buffer the text of the region.
5268 It is inserted into that buffer after its point.
5270 When calling from a program, give three arguments:
5271 BUFFER (or buffer name), START and END.
5272 START and END specify the portion of the current buffer to be copied."
5273 (interactive "BPrepend to buffer: \nr")
5274 (let ((oldbuf (current-buffer)))
5275 (with-current-buffer (get-buffer-create buffer)
5276 (barf-if-buffer-read-only)
5277 (save-excursion
5278 (insert-buffer-substring oldbuf start end)))))
5280 (defun copy-to-buffer (buffer start end)
5281 "Copy to specified buffer the text of the region.
5282 It is inserted into that buffer, replacing existing text there.
5284 When calling from a program, give three arguments:
5285 BUFFER (or buffer name), START and END.
5286 START and END specify the portion of the current buffer to be copied."
5287 (interactive "BCopy to buffer: \nr")
5288 (let ((oldbuf (current-buffer)))
5289 (with-current-buffer (get-buffer-create buffer)
5290 (barf-if-buffer-read-only)
5291 (erase-buffer)
5292 (save-excursion
5293 (insert-buffer-substring oldbuf start end)))))
5295 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5297 (defvar activate-mark-hook nil
5298 "Hook run when the mark becomes active.
5299 It is also run at the end of a command, if the mark is active and
5300 it is possible that the region may have changed.")
5302 (defvar deactivate-mark-hook nil
5303 "Hook run when the mark becomes inactive.")
5305 (defun mark (&optional force)
5306 "Return this buffer's mark value as integer, or nil if never set.
5308 In Transient Mark mode, this function signals an error if
5309 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5310 or the argument FORCE is non-nil, it disregards whether the mark
5311 is active, and returns an integer or nil in the usual way.
5313 If you are using this in an editing command, you are most likely making
5314 a mistake; see the documentation of `set-mark'."
5315 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5316 (marker-position (mark-marker))
5317 (signal 'mark-inactive nil)))
5319 ;; Behind display-selections-p.
5321 (defun deactivate-mark (&optional force)
5322 "Deactivate the mark.
5323 If Transient Mark mode is disabled, this function normally does
5324 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5326 Deactivating the mark sets `mark-active' to nil, updates the
5327 primary selection according to `select-active-regions', and runs
5328 `deactivate-mark-hook'.
5330 If Transient Mark mode was temporarily enabled, reset the value
5331 of the variable `transient-mark-mode'; if this causes Transient
5332 Mark mode to be disabled, don't change `mark-active' to nil or
5333 run `deactivate-mark-hook'."
5334 (when (or (region-active-p) force)
5335 (when (and (if (eq select-active-regions 'only)
5336 (eq (car-safe transient-mark-mode) 'only)
5337 select-active-regions)
5338 (region-active-p)
5339 (display-selections-p))
5340 ;; The var `saved-region-selection', if non-nil, is the text in
5341 ;; the region prior to the last command modifying the buffer.
5342 ;; Set the selection to that, or to the current region.
5343 (cond (saved-region-selection
5344 (if (gui-backend-selection-owner-p 'PRIMARY)
5345 (gui-set-selection 'PRIMARY saved-region-selection))
5346 (setq saved-region-selection nil))
5347 ;; If another program has acquired the selection, region
5348 ;; deactivation should not clobber it (Bug#11772).
5349 ((and (/= (region-beginning) (region-end))
5350 (or (gui-backend-selection-owner-p 'PRIMARY)
5351 (null (gui-backend-selection-exists-p 'PRIMARY))))
5352 (gui-set-selection 'PRIMARY
5353 (funcall region-extract-function nil)))))
5354 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5355 (cond
5356 ((eq (car-safe transient-mark-mode) 'only)
5357 (setq transient-mark-mode (cdr transient-mark-mode))
5358 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5359 (kill-local-variable 'transient-mark-mode)))
5360 ((eq transient-mark-mode 'lambda)
5361 (kill-local-variable 'transient-mark-mode)))
5362 (setq mark-active nil)
5363 (run-hooks 'deactivate-mark-hook)
5364 (redisplay--update-region-highlight (selected-window))))
5366 (defun activate-mark (&optional no-tmm)
5367 "Activate the mark.
5368 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5369 (when (mark t)
5370 (unless (region-active-p)
5371 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5372 (setq mark-active t)
5373 (unless (or transient-mark-mode no-tmm)
5374 (setq-local transient-mark-mode 'lambda))
5375 (run-hooks 'activate-mark-hook))))
5377 (defun set-mark (pos)
5378 "Set this buffer's mark to POS. Don't use this function!
5379 That is to say, don't use this function unless you want
5380 the user to see that the mark has moved, and you want the previous
5381 mark position to be lost.
5383 Normally, when a new mark is set, the old one should go on the stack.
5384 This is why most applications should use `push-mark', not `set-mark'.
5386 Novice Emacs Lisp programmers often try to use the mark for the wrong
5387 purposes. The mark saves a location for the user's convenience.
5388 Most editing commands should not alter the mark.
5389 To remember a location for internal use in the Lisp program,
5390 store it in a Lisp variable. Example:
5392 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5393 (if pos
5394 (progn
5395 (set-marker (mark-marker) pos (current-buffer))
5396 (activate-mark 'no-tmm))
5397 ;; Normally we never clear mark-active except in Transient Mark mode.
5398 ;; But when we actually clear out the mark value too, we must
5399 ;; clear mark-active in any mode.
5400 (deactivate-mark t)
5401 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5402 ;; it should never be nil if the mark is nil.
5403 (setq mark-active nil)
5404 (set-marker (mark-marker) nil)))
5406 (defun save-mark-and-excursion--save ()
5407 (cons
5408 (let ((mark (mark-marker)))
5409 (and (marker-position mark) (copy-marker mark)))
5410 mark-active))
5412 (defun save-mark-and-excursion--restore (saved-mark-info)
5413 (let ((saved-mark (car saved-mark-info))
5414 (omark (marker-position (mark-marker)))
5415 (nmark nil)
5416 (saved-mark-active (cdr saved-mark-info)))
5417 ;; Mark marker
5418 (if (null saved-mark)
5419 (set-marker (mark-marker) nil)
5420 (setf nmark (marker-position saved-mark))
5421 (set-marker (mark-marker) nmark)
5422 (set-marker saved-mark nil))
5423 ;; Mark active
5424 (let ((cur-mark-active mark-active))
5425 (setq mark-active saved-mark-active)
5426 ;; If mark is active now, and either was not active or was at a
5427 ;; different place, run the activate hook.
5428 (if saved-mark-active
5429 (when (or (not cur-mark-active)
5430 (not (eq omark nmark)))
5431 (run-hooks 'activate-mark-hook))
5432 ;; If mark has ceased to be active, run deactivate hook.
5433 (when cur-mark-active
5434 (run-hooks 'deactivate-mark-hook))))))
5436 (defmacro save-mark-and-excursion (&rest body)
5437 "Like `save-excursion', but also save and restore the mark state.
5438 This macro does what `save-excursion' did before Emacs 25.1."
5439 (declare (indent 0) (debug t))
5440 (let ((saved-marker-sym (make-symbol "saved-marker")))
5441 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5442 (unwind-protect
5443 (save-excursion ,@body)
5444 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5446 (defcustom use-empty-active-region nil
5447 "Whether \"region-aware\" commands should act on empty regions.
5448 If nil, region-aware commands treat the empty region as inactive.
5449 If non-nil, region-aware commands treat the region as active as
5450 long as the mark is active, even if the region is empty.
5452 Region-aware commands are those that act on the region if it is
5453 active and Transient Mark mode is enabled, and on the text near
5454 point otherwise."
5455 :type 'boolean
5456 :version "23.1"
5457 :group 'editing-basics)
5459 (defun use-region-p ()
5460 "Return t if the region is active and it is appropriate to act on it.
5461 This is used by commands that act specially on the region under
5462 Transient Mark mode.
5464 The return value is t if Transient Mark mode is enabled and the
5465 mark is active; furthermore, if `use-empty-active-region' is nil,
5466 the region must not be empty. Otherwise, the return value is nil.
5468 For some commands, it may be appropriate to ignore the value of
5469 `use-empty-active-region'; in that case, use `region-active-p'."
5470 (and (region-active-p)
5471 (or use-empty-active-region (> (region-end) (region-beginning)))))
5473 (defun region-active-p ()
5474 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5476 Some commands act specially on the region when Transient Mark
5477 mode is enabled. Usually, such commands should use
5478 `use-region-p' instead of this function, because `use-region-p'
5479 also checks the value of `use-empty-active-region'."
5480 (and transient-mark-mode mark-active
5481 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5482 ;; without the mark being set (e.g. bug#17324). We really should fix
5483 ;; that problem, but in the mean time, let's make sure we don't say the
5484 ;; region is active when there's no mark.
5485 (progn (cl-assert (mark)) t)))
5487 (defun region-bounds ()
5488 "Return the boundaries of the region as a pair of positions.
5489 Value is a list of cons cells of the form (START . END)."
5490 (funcall region-extract-function 'bounds))
5492 (defun region-noncontiguous-p ()
5493 "Return non-nil if the region contains several pieces.
5494 An example is a rectangular region handled as a list of
5495 separate contiguous regions for each line."
5496 (> (length (region-bounds)) 1))
5498 (defvar redisplay-unhighlight-region-function
5499 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5501 (defvar redisplay-highlight-region-function
5502 (lambda (start end window rol)
5503 (if (not (overlayp rol))
5504 (let ((nrol (make-overlay start end)))
5505 (funcall redisplay-unhighlight-region-function rol)
5506 (overlay-put nrol 'window window)
5507 (overlay-put nrol 'face 'region)
5508 ;; Normal priority so that a large region doesn't hide all the
5509 ;; overlays within it, but high secondary priority so that if it
5510 ;; ends/starts in the middle of a small overlay, that small overlay
5511 ;; won't hide the region's boundaries.
5512 (overlay-put nrol 'priority '(nil . 100))
5513 nrol)
5514 (unless (and (eq (overlay-buffer rol) (current-buffer))
5515 (eq (overlay-start rol) start)
5516 (eq (overlay-end rol) end))
5517 (move-overlay rol start end (current-buffer)))
5518 rol)))
5520 (defun redisplay--update-region-highlight (window)
5521 (let ((rol (window-parameter window 'internal-region-overlay)))
5522 (if (not (and (region-active-p)
5523 (or highlight-nonselected-windows
5524 (eq window (selected-window))
5525 (and (window-minibuffer-p)
5526 (eq window (minibuffer-selected-window))))))
5527 (funcall redisplay-unhighlight-region-function rol)
5528 (let* ((pt (window-point window))
5529 (mark (mark))
5530 (start (min pt mark))
5531 (end (max pt mark))
5532 (new
5533 (funcall redisplay-highlight-region-function
5534 start end window rol)))
5535 (unless (equal new rol)
5536 (set-window-parameter window 'internal-region-overlay
5537 new))))))
5539 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5540 "Hook run just before redisplay.
5541 It is called in each window that is to be redisplayed. It takes one argument,
5542 which is the window that will be redisplayed. When run, the `current-buffer'
5543 is set to the buffer displayed in that window.")
5545 (defun redisplay--pre-redisplay-functions (windows)
5546 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5547 (if (null windows)
5548 (with-current-buffer (window-buffer (selected-window))
5549 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5550 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5551 (with-current-buffer (window-buffer win)
5552 (run-hook-with-args 'pre-redisplay-functions win))))))
5554 (add-function :before pre-redisplay-function
5555 #'redisplay--pre-redisplay-functions)
5558 (defvar-local mark-ring nil
5559 "The list of former marks of the current buffer, most recent first.")
5560 (put 'mark-ring 'permanent-local t)
5562 (defcustom mark-ring-max 16
5563 "Maximum size of mark ring. Start discarding off end if gets this big."
5564 :type 'integer
5565 :group 'editing-basics)
5567 (defvar global-mark-ring nil
5568 "The list of saved global marks, most recent first.")
5570 (defcustom global-mark-ring-max 16
5571 "Maximum size of global mark ring. \
5572 Start discarding off end if gets this big."
5573 :type 'integer
5574 :group 'editing-basics)
5576 (defun pop-to-mark-command ()
5577 "Jump to mark, and pop a new position for mark off the ring.
5578 \(Does not affect global mark ring)."
5579 (interactive)
5580 (if (null (mark t))
5581 (user-error "No mark set in this buffer")
5582 (if (= (point) (mark t))
5583 (message "Mark popped"))
5584 (goto-char (mark t))
5585 (pop-mark)))
5587 (defun push-mark-command (arg &optional nomsg)
5588 "Set mark at where point is.
5589 If no prefix ARG and mark is already set there, just activate it.
5590 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5591 (interactive "P")
5592 (let ((mark (mark t)))
5593 (if (or arg (null mark) (/= mark (point)))
5594 (push-mark nil nomsg t)
5595 (activate-mark 'no-tmm)
5596 (unless nomsg
5597 (message "Mark activated")))))
5599 (defcustom set-mark-command-repeat-pop nil
5600 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5601 That means that C-u \\[set-mark-command] \\[set-mark-command]
5602 will pop the mark twice, and
5603 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5604 will pop the mark three times.
5606 A value of nil means \\[set-mark-command]'s behavior does not change
5607 after C-u \\[set-mark-command]."
5608 :type 'boolean
5609 :group 'editing-basics)
5611 (defun set-mark-command (arg)
5612 "Set the mark where point is, and activate it; or jump to the mark.
5613 Setting the mark also alters the region, which is the text
5614 between point and mark; this is the closest equivalent in
5615 Emacs to what some editors call the \"selection\".
5617 With no prefix argument, set the mark at point, and push the
5618 old mark position on local mark ring. Also push the new mark on
5619 global mark ring, if the previous mark was set in another buffer.
5621 When Transient Mark Mode is off, immediately repeating this
5622 command activates `transient-mark-mode' temporarily.
5624 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5625 jump to the mark, and set the mark from
5626 position popped off the local mark ring (this does not affect the global
5627 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5628 mark ring (see `pop-global-mark').
5630 If `set-mark-command-repeat-pop' is non-nil, repeating
5631 the \\[set-mark-command] command with no prefix argument pops the next position
5632 off the local (or global) mark ring and jumps there.
5634 With \\[universal-argument] \\[universal-argument] as prefix
5635 argument, unconditionally set mark where point is, even if
5636 `set-mark-command-repeat-pop' is non-nil.
5638 Novice Emacs Lisp programmers often try to use the mark for the wrong
5639 purposes. See the documentation of `set-mark' for more information."
5640 (interactive "P")
5641 (cond ((eq transient-mark-mode 'lambda)
5642 (kill-local-variable 'transient-mark-mode))
5643 ((eq (car-safe transient-mark-mode) 'only)
5644 (deactivate-mark)))
5645 (cond
5646 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5647 (push-mark-command nil))
5648 ((not (eq this-command 'set-mark-command))
5649 (if arg
5650 (pop-to-mark-command)
5651 (push-mark-command t)))
5652 ((and set-mark-command-repeat-pop
5653 (eq last-command 'pop-global-mark)
5654 (not arg))
5655 (setq this-command 'pop-global-mark)
5656 (pop-global-mark))
5657 ((or (and set-mark-command-repeat-pop
5658 (eq last-command 'pop-to-mark-command))
5659 arg)
5660 (setq this-command 'pop-to-mark-command)
5661 (pop-to-mark-command))
5662 ((eq last-command 'set-mark-command)
5663 (if (region-active-p)
5664 (progn
5665 (deactivate-mark)
5666 (message "Mark deactivated"))
5667 (activate-mark)
5668 (message "Mark activated")))
5670 (push-mark-command nil))))
5672 (defun push-mark (&optional location nomsg activate)
5673 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5674 If the last global mark pushed was not in the current buffer,
5675 also push LOCATION on the global mark ring.
5676 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5678 Novice Emacs Lisp programmers often try to use the mark for the wrong
5679 purposes. See the documentation of `set-mark' for more information.
5681 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5682 (unless (null (mark t))
5683 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5684 (when (> (length mark-ring) mark-ring-max)
5685 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5686 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5687 (set-marker (mark-marker) (or location (point)) (current-buffer))
5688 ;; Now push the mark on the global mark ring.
5689 (if (and global-mark-ring
5690 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5691 ;; The last global mark pushed was in this same buffer.
5692 ;; Don't push another one.
5694 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5695 (when (> (length global-mark-ring) global-mark-ring-max)
5696 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5697 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5698 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5699 (message "Mark set"))
5700 (if (or activate (not transient-mark-mode))
5701 (set-mark (mark t)))
5702 nil)
5704 (defun pop-mark ()
5705 "Pop off mark ring into the buffer's actual mark.
5706 Does not set point. Does nothing if mark ring is empty."
5707 (when mark-ring
5708 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5709 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5710 (move-marker (car mark-ring) nil)
5711 (if (null (mark t)) (ding))
5712 (setq mark-ring (cdr mark-ring)))
5713 (deactivate-mark))
5715 (define-obsolete-function-alias
5716 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5717 (defun exchange-point-and-mark (&optional arg)
5718 "Put the mark where point is now, and point where the mark is now.
5719 This command works even when the mark is not active,
5720 and it reactivates the mark.
5722 If Transient Mark mode is on, a prefix ARG deactivates the mark
5723 if it is active, and otherwise avoids reactivating it. If
5724 Transient Mark mode is off, a prefix ARG enables Transient Mark
5725 mode temporarily."
5726 (interactive "P")
5727 (let ((omark (mark t))
5728 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5729 (if (null omark)
5730 (user-error "No mark set in this buffer"))
5731 (set-mark (point))
5732 (goto-char omark)
5733 (cond (temp-highlight
5734 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5735 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5736 (not (or arg (region-active-p))))
5737 (deactivate-mark))
5738 (t (activate-mark)))
5739 nil))
5741 (defcustom shift-select-mode t
5742 "When non-nil, shifted motion keys activate the mark momentarily.
5744 While the mark is activated in this way, any shift-translated point
5745 motion key extends the region, and if Transient Mark mode was off, it
5746 is temporarily turned on. Furthermore, the mark will be deactivated
5747 by any subsequent point motion key that was not shift-translated, or
5748 by any action that normally deactivates the mark in Transient Mark mode.
5750 See `this-command-keys-shift-translated' for the meaning of
5751 shift-translation."
5752 :type 'boolean
5753 :group 'editing-basics)
5755 (defun handle-shift-selection ()
5756 "Activate/deactivate mark depending on invocation thru shift translation.
5757 This function is called by `call-interactively' when a command
5758 with a `^' character in its `interactive' spec is invoked, before
5759 running the command itself.
5761 If `shift-select-mode' is enabled and the command was invoked
5762 through shift translation, set the mark and activate the region
5763 temporarily, unless it was already set in this way. See
5764 `this-command-keys-shift-translated' for the meaning of shift
5765 translation.
5767 Otherwise, if the region has been activated temporarily,
5768 deactivate it, and restore the variable `transient-mark-mode' to
5769 its earlier value."
5770 (cond ((and shift-select-mode this-command-keys-shift-translated)
5771 (unless (and mark-active
5772 (eq (car-safe transient-mark-mode) 'only))
5773 (setq-local transient-mark-mode
5774 (cons 'only
5775 (unless (eq transient-mark-mode 'lambda)
5776 transient-mark-mode)))
5777 (push-mark nil nil t)))
5778 ((eq (car-safe transient-mark-mode) 'only)
5779 (setq transient-mark-mode (cdr transient-mark-mode))
5780 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5781 (kill-local-variable 'transient-mark-mode))
5782 (deactivate-mark))))
5784 (define-minor-mode transient-mark-mode
5785 "Toggle Transient Mark mode.
5786 With a prefix argument ARG, enable Transient Mark mode if ARG is
5787 positive, and disable it otherwise. If called from Lisp, enable
5788 Transient Mark mode if ARG is omitted or nil.
5790 Transient Mark mode is a global minor mode. When enabled, the
5791 region is highlighted with the `region' face whenever the mark
5792 is active. The mark is \"deactivated\" by changing the buffer,
5793 and after certain other operations that set the mark but whose
5794 main purpose is something else--for example, incremental search,
5795 \\[beginning-of-buffer], and \\[end-of-buffer].
5797 You can also deactivate the mark by typing \\[keyboard-quit] or
5798 \\[keyboard-escape-quit].
5800 Many commands change their behavior when Transient Mark mode is
5801 in effect and the mark is active, by acting on the region instead
5802 of their usual default part of the buffer's text. Examples of
5803 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5804 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5805 To see the documentation of commands which are sensitive to the
5806 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5807 or \"mark.*active\" at the prompt."
5808 :global t
5809 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5810 :variable (default-value 'transient-mark-mode))
5812 (defvar widen-automatically t
5813 "Non-nil means it is ok for commands to call `widen' when they want to.
5814 Some commands will do this in order to go to positions outside
5815 the current accessible part of the buffer.
5817 If `widen-automatically' is nil, these commands will do something else
5818 as a fallback, and won't change the buffer bounds.")
5820 (defvar non-essential nil
5821 "Whether the currently executing code is performing an essential task.
5822 This variable should be non-nil only when running code which should not
5823 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5824 user for a password when we are simply scanning a set of files in the
5825 background or displaying possible completions before the user even asked
5826 for it.")
5828 (defun pop-global-mark ()
5829 "Pop off global mark ring and jump to the top location."
5830 (interactive)
5831 ;; Pop entries which refer to non-existent buffers.
5832 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5833 (setq global-mark-ring (cdr global-mark-ring)))
5834 (or global-mark-ring
5835 (error "No global mark set"))
5836 (let* ((marker (car global-mark-ring))
5837 (buffer (marker-buffer marker))
5838 (position (marker-position marker)))
5839 (setq global-mark-ring (nconc (cdr global-mark-ring)
5840 (list (car global-mark-ring))))
5841 (set-buffer buffer)
5842 (or (and (>= position (point-min))
5843 (<= position (point-max)))
5844 (if widen-automatically
5845 (widen)
5846 (error "Global mark position is outside accessible part of buffer")))
5847 (goto-char position)
5848 (switch-to-buffer buffer)))
5850 (defcustom next-line-add-newlines nil
5851 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5852 :type 'boolean
5853 :version "21.1"
5854 :group 'editing-basics)
5856 (defun next-line (&optional arg try-vscroll)
5857 "Move cursor vertically down ARG lines.
5858 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5859 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5860 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5861 function will not vscroll.
5863 ARG defaults to 1.
5865 If there is no character in the target line exactly under the current column,
5866 the cursor is positioned after the character in that line which spans this
5867 column, or at the end of the line if it is not long enough.
5868 If there is no line in the buffer after this one, behavior depends on the
5869 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5870 to create a line, and moves the cursor to that line. Otherwise it moves the
5871 cursor to the end of the buffer.
5873 If the variable `line-move-visual' is non-nil, this command moves
5874 by display lines. Otherwise, it moves by buffer lines, without
5875 taking variable-width characters or continued lines into account.
5876 See \\[next-logical-line] for a command that always moves by buffer lines.
5878 The command \\[set-goal-column] can be used to create
5879 a semipermanent goal column for this command.
5880 Then instead of trying to move exactly vertically (or as close as possible),
5881 this command moves to the specified goal column (or as close as possible).
5882 The goal column is stored in the variable `goal-column', which is nil
5883 when there is no goal column. Note that setting `goal-column'
5884 overrides `line-move-visual' and causes this command to move by buffer
5885 lines rather than by display lines."
5886 (declare (interactive-only forward-line))
5887 (interactive "^p\np")
5888 (or arg (setq arg 1))
5889 (if (and next-line-add-newlines (= arg 1))
5890 (if (save-excursion (end-of-line) (eobp))
5891 ;; When adding a newline, don't expand an abbrev.
5892 (let ((abbrev-mode nil))
5893 (end-of-line)
5894 (insert (if use-hard-newlines hard-newline "\n")))
5895 (line-move arg nil nil try-vscroll))
5896 (if (called-interactively-p 'interactive)
5897 (condition-case err
5898 (line-move arg nil nil try-vscroll)
5899 ((beginning-of-buffer end-of-buffer)
5900 (signal (car err) (cdr err))))
5901 (line-move arg nil nil try-vscroll)))
5902 nil)
5904 (defun previous-line (&optional arg try-vscroll)
5905 "Move cursor vertically up ARG lines.
5906 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5907 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5908 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5909 function will not vscroll.
5911 ARG defaults to 1.
5913 If there is no character in the target line exactly over the current column,
5914 the cursor is positioned after the character in that line which spans this
5915 column, or at the end of the line if it is not long enough.
5917 If the variable `line-move-visual' is non-nil, this command moves
5918 by display lines. Otherwise, it moves by buffer lines, without
5919 taking variable-width characters or continued lines into account.
5920 See \\[previous-logical-line] for a command that always moves by buffer lines.
5922 The command \\[set-goal-column] can be used to create
5923 a semipermanent goal column for this command.
5924 Then instead of trying to move exactly vertically (or as close as possible),
5925 this command moves to the specified goal column (or as close as possible).
5926 The goal column is stored in the variable `goal-column', which is nil
5927 when there is no goal column. Note that setting `goal-column'
5928 overrides `line-move-visual' and causes this command to move by buffer
5929 lines rather than by display lines."
5930 (declare (interactive-only
5931 "use `forward-line' with negative argument instead."))
5932 (interactive "^p\np")
5933 (or arg (setq arg 1))
5934 (if (called-interactively-p 'interactive)
5935 (condition-case err
5936 (line-move (- arg) nil nil try-vscroll)
5937 ((beginning-of-buffer end-of-buffer)
5938 (signal (car err) (cdr err))))
5939 (line-move (- arg) nil nil try-vscroll))
5940 nil)
5942 (defcustom track-eol nil
5943 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5944 This means moving to the end of each line moved onto.
5945 The beginning of a blank line does not count as the end of a line.
5946 This has no effect when the variable `line-move-visual' is non-nil."
5947 :type 'boolean
5948 :group 'editing-basics)
5950 (defcustom goal-column nil
5951 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5952 A non-nil setting overrides the variable `line-move-visual', which see."
5953 :type '(choice integer
5954 (const :tag "None" nil))
5955 :group 'editing-basics)
5956 (make-variable-buffer-local 'goal-column)
5958 (defvar temporary-goal-column 0
5959 "Current goal column for vertical motion.
5960 It is the column where point was at the start of the current run
5961 of vertical motion commands.
5963 When moving by visual lines via the function `line-move-visual', it is a cons
5964 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5965 divided by the default column width, and HSCROLL is the number of
5966 columns by which window is scrolled from left margin.
5968 When the `track-eol' feature is doing its job, the value is
5969 `most-positive-fixnum'.")
5971 (defvar last--line-number-width 0
5972 "Last value of width used for displaying line numbers.
5973 Used internally by `line-move-visual'.")
5975 (defcustom line-move-ignore-invisible t
5976 "Non-nil means commands that move by lines ignore invisible newlines.
5977 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5978 as if newlines that are invisible didn't exist, and count
5979 only visible newlines. Thus, moving across 2 newlines
5980 one of which is invisible will be counted as a one-line move.
5981 Also, a non-nil value causes invisible text to be ignored when
5982 counting columns for the purposes of keeping point in the same
5983 column by \\[next-line] and \\[previous-line].
5985 Outline mode sets this."
5986 :type 'boolean
5987 :group 'editing-basics)
5989 (defcustom line-move-visual t
5990 "When non-nil, `line-move' moves point by visual lines.
5991 This movement is based on where the cursor is displayed on the
5992 screen, instead of relying on buffer contents alone. It takes
5993 into account variable-width characters and line continuation.
5994 If nil, `line-move' moves point by logical lines.
5995 A non-nil setting of `goal-column' overrides the value of this variable
5996 and forces movement by logical lines.
5997 A window that is horizontally scrolled also forces movement by logical
5998 lines."
5999 :type 'boolean
6000 :group 'editing-basics
6001 :version "23.1")
6003 ;; Only used if display-graphic-p.
6004 (declare-function font-info "font.c" (name &optional frame))
6006 (defun default-font-height ()
6007 "Return the height in pixels of the current buffer's default face font.
6009 If the default font is remapped (see `face-remapping-alist'), the
6010 function returns the height of the remapped face."
6011 (let ((default-font (face-font 'default)))
6012 (cond
6013 ((and (display-multi-font-p)
6014 ;; Avoid calling font-info if the frame's default font was
6015 ;; not changed since the frame was created. That's because
6016 ;; font-info is expensive for some fonts, see bug #14838.
6017 (not (string= (frame-parameter nil 'font) default-font)))
6018 (aref (font-info default-font) 3))
6019 (t (frame-char-height)))))
6021 (defun default-font-width ()
6022 "Return the width in pixels of the current buffer's default face font.
6024 If the default font is remapped (see `face-remapping-alist'), the
6025 function returns the width of the remapped face."
6026 (let ((default-font (face-font 'default)))
6027 (cond
6028 ((and (display-multi-font-p)
6029 ;; Avoid calling font-info if the frame's default font was
6030 ;; not changed since the frame was created. That's because
6031 ;; font-info is expensive for some fonts, see bug #14838.
6032 (not (string= (frame-parameter nil 'font) default-font)))
6033 (let* ((info (font-info (face-font 'default)))
6034 (width (aref info 11)))
6035 (if (> width 0)
6036 width
6037 (aref info 10))))
6038 (t (frame-char-width)))))
6040 (defun default-line-height ()
6041 "Return the pixel height of current buffer's default-face text line.
6043 The value includes `line-spacing', if any, defined for the buffer
6044 or the frame."
6045 (let ((dfh (default-font-height))
6046 (lsp (if (display-graphic-p)
6047 (or line-spacing
6048 (default-value 'line-spacing)
6049 (frame-parameter nil 'line-spacing)
6051 0)))
6052 (if (floatp lsp)
6053 (setq lsp (truncate (* (frame-char-height) lsp))))
6054 (+ dfh lsp)))
6056 (defun window-screen-lines ()
6057 "Return the number of screen lines in the text area of the selected window.
6059 This is different from `window-text-height' in that this function counts
6060 lines in units of the height of the font used by the default face displayed
6061 in the window, not in units of the frame's default font, and also accounts
6062 for `line-spacing', if any, defined for the window's buffer or frame.
6064 The value is a floating-point number."
6065 (let ((edges (window-inside-pixel-edges))
6066 (dlh (default-line-height)))
6067 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
6069 ;; Returns non-nil if partial move was done.
6070 (defun line-move-partial (arg noerror &optional _to-end)
6071 (if (< arg 0)
6072 ;; Move backward (up).
6073 ;; If already vscrolled, reduce vscroll
6074 (let ((vs (window-vscroll nil t))
6075 (dlh (default-line-height)))
6076 (when (> vs dlh)
6077 (set-window-vscroll nil (- vs dlh) t)))
6079 ;; Move forward (down).
6080 (let* ((lh (window-line-height -1))
6081 (rowh (car lh))
6082 (vpos (nth 1 lh))
6083 (ypos (nth 2 lh))
6084 (rbot (nth 3 lh))
6085 (this-lh (window-line-height))
6086 (this-height (car this-lh))
6087 (this-ypos (nth 2 this-lh))
6088 (dlh (default-line-height))
6089 (wslines (window-screen-lines))
6090 (edges (window-inside-pixel-edges))
6091 (winh (- (nth 3 edges) (nth 1 edges) 1))
6092 py vs last-line)
6093 (if (> (mod wslines 1.0) 0.0)
6094 (setq wslines (round (+ wslines 0.5))))
6095 (when (or (null lh)
6096 (>= rbot dlh)
6097 (<= ypos (- dlh))
6098 (null this-lh)
6099 (<= this-ypos (- dlh)))
6100 (unless lh
6101 (let ((wend (pos-visible-in-window-p t nil t)))
6102 (setq rbot (nth 3 wend)
6103 rowh (nth 4 wend)
6104 vpos (nth 5 wend))))
6105 (unless this-lh
6106 (let ((wstart (pos-visible-in-window-p nil nil t)))
6107 (setq this-ypos (nth 2 wstart)
6108 this-height (nth 4 wstart))))
6109 (setq py
6110 (or (nth 1 this-lh)
6111 (let ((ppos (posn-at-point))
6112 col-row)
6113 (setq col-row (posn-actual-col-row ppos))
6114 (if col-row
6115 (- (cdr col-row) (window-vscroll))
6116 (cdr (posn-col-row ppos))))))
6117 ;; VPOS > 0 means the last line is only partially visible.
6118 ;; But if the part that is visible is at least as tall as the
6119 ;; default font, that means the line is actually fully
6120 ;; readable, and something like line-spacing is hidden. So in
6121 ;; that case we accept the last line in the window as still
6122 ;; visible, and consider the margin as starting one line
6123 ;; later.
6124 (if (and vpos (> vpos 0))
6125 (if (and rowh
6126 (>= rowh (default-font-height))
6127 (< rowh dlh))
6128 (setq last-line (min (- wslines scroll-margin) vpos))
6129 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6130 (cond
6131 ;; If last line of window is fully visible, and vscrolling
6132 ;; more would make this line invisible, move forward.
6133 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6134 (null this-height)
6135 (<= this-height dlh))
6136 (or (null rbot) (= rbot 0)))
6137 nil)
6138 ;; If cursor is not in the bottom scroll margin, and the
6139 ;; current line is not too tall, move forward.
6140 ((and (or (null this-height) (<= this-height winh))
6141 vpos
6142 (> vpos 0)
6143 (< py last-line))
6144 nil)
6145 ;; When already vscrolled, we vscroll some more if we can,
6146 ;; or clear vscroll and move forward at end of tall image.
6147 ((> vs 0)
6148 (when (or (and rbot (> rbot 0))
6149 (and this-height (> this-height dlh)))
6150 (set-window-vscroll nil (+ vs dlh) t)))
6151 ;; If cursor just entered the bottom scroll margin, move forward,
6152 ;; but also optionally vscroll one line so redisplay won't recenter.
6153 ((and vpos
6154 (> vpos 0)
6155 (= py last-line))
6156 ;; Don't vscroll if the partially-visible line at window
6157 ;; bottom is not too tall (a.k.a. "just one more text
6158 ;; line"): in that case, we do want redisplay to behave
6159 ;; normally, i.e. recenter or whatever.
6161 ;; Note: ROWH + RBOT from the value returned by
6162 ;; pos-visible-in-window-p give the total height of the
6163 ;; partially-visible glyph row at the end of the window. As
6164 ;; we are dealing with floats, we disregard sub-pixel
6165 ;; discrepancies between that and DLH.
6166 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6167 (set-window-vscroll nil dlh t))
6168 (line-move-1 arg noerror)
6170 ;; If there are lines above the last line, scroll-up one line.
6171 ((and vpos (> vpos 0))
6172 (scroll-up 1)
6174 ;; Finally, start vscroll.
6176 (set-window-vscroll nil dlh t)))))))
6179 ;; This is like line-move-1 except that it also performs
6180 ;; vertical scrolling of tall images if appropriate.
6181 ;; That is not really a clean thing to do, since it mixes
6182 ;; scrolling with cursor motion. But so far we don't have
6183 ;; a cleaner solution to the problem of making C-n do something
6184 ;; useful given a tall image.
6185 (defun line-move (arg &optional noerror _to-end try-vscroll)
6186 "Move forward ARG lines.
6187 If NOERROR, don't signal an error if we can't move ARG lines.
6188 TO-END is unused.
6189 TRY-VSCROLL controls whether to vscroll tall lines: if either
6190 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6191 not vscroll."
6192 (if noninteractive
6193 (line-move-1 arg noerror)
6194 (unless (and auto-window-vscroll try-vscroll
6195 ;; Only vscroll for single line moves
6196 (= (abs arg) 1)
6197 ;; Under scroll-conservatively, the display engine
6198 ;; does this better.
6199 (zerop scroll-conservatively)
6200 ;; But don't vscroll in a keyboard macro.
6201 (not defining-kbd-macro)
6202 (not executing-kbd-macro)
6203 (line-move-partial arg noerror))
6204 (set-window-vscroll nil 0 t)
6205 (if (and line-move-visual
6206 ;; Display-based column are incompatible with goal-column.
6207 (not goal-column)
6208 ;; When the text in the window is scrolled to the left,
6209 ;; display-based motion doesn't make sense (because each
6210 ;; logical line occupies exactly one screen line).
6211 (not (> (window-hscroll) 0))
6212 ;; Likewise when the text _was_ scrolled to the left
6213 ;; when the current run of vertical motion commands
6214 ;; started.
6215 (not (and (memq last-command
6216 `(next-line previous-line ,this-command))
6217 auto-hscroll-mode
6218 (numberp temporary-goal-column)
6219 (>= temporary-goal-column
6220 (- (window-width) hscroll-margin)))))
6221 (prog1 (line-move-visual arg noerror)
6222 ;; If we moved into a tall line, set vscroll to make
6223 ;; scrolling through tall images more smooth.
6224 (let ((lh (line-pixel-height))
6225 (edges (window-inside-pixel-edges))
6226 (dlh (default-line-height))
6227 winh)
6228 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6229 (if (and (< arg 0)
6230 (< (point) (window-start))
6231 (> lh winh))
6232 (set-window-vscroll
6234 (- lh dlh) t))))
6235 (line-move-1 arg noerror)))))
6237 ;; Display-based alternative to line-move-1.
6238 ;; Arg says how many lines to move. The value is t if we can move the
6239 ;; specified number of lines.
6240 (defun line-move-visual (arg &optional noerror)
6241 "Move ARG lines forward.
6242 If NOERROR, don't signal an error if we can't move that many lines."
6243 (let ((opoint (point))
6244 (hscroll (window-hscroll))
6245 (lnum-width (line-number-display-width t))
6246 target-hscroll)
6247 ;; Check if the previous command was a line-motion command, or if
6248 ;; we were called from some other command.
6249 (if (and (consp temporary-goal-column)
6250 (memq last-command `(next-line previous-line ,this-command)))
6251 ;; If so, there's no need to reset `temporary-goal-column',
6252 ;; but we may need to hscroll.
6253 (progn
6254 (if (or (/= (cdr temporary-goal-column) hscroll)
6255 (> (cdr temporary-goal-column) 0))
6256 (setq target-hscroll (cdr temporary-goal-column)))
6257 ;; Update the COLUMN part of temporary-goal-column if the
6258 ;; line-number display changed its width since the last
6259 ;; time.
6260 (setq temporary-goal-column
6261 (cons (+ (car temporary-goal-column)
6262 (/ (float (- lnum-width last--line-number-width))
6263 (frame-char-width)))
6264 (cdr temporary-goal-column)))
6265 (setq last--line-number-width lnum-width))
6266 ;; Otherwise, we should reset `temporary-goal-column'.
6267 (let ((posn (posn-at-point))
6268 x-pos)
6269 (cond
6270 ;; Handle the `overflow-newline-into-fringe' case
6271 ;; (left-fringe is for the R2L case):
6272 ((memq (nth 1 posn) '(right-fringe left-fringe))
6273 (setq temporary-goal-column (cons (window-width) hscroll)))
6274 ((car (posn-x-y posn))
6275 (setq x-pos (car (posn-x-y posn)))
6276 ;; In R2L lines, the X pixel coordinate is measured from the
6277 ;; left edge of the window, but columns are still counted
6278 ;; from the logical-order beginning of the line, i.e. from
6279 ;; the right edge in this case. We need to adjust for that.
6280 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6281 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6282 (setq temporary-goal-column
6283 (cons (/ (float x-pos)
6284 (frame-char-width))
6285 hscroll)))
6286 (executing-kbd-macro
6287 ;; When we move beyond the first/last character visible in
6288 ;; the window, posn-at-point will return nil, so we need to
6289 ;; approximate the goal column as below.
6290 (setq temporary-goal-column
6291 (mod (current-column) (window-text-width)))))))
6292 (if target-hscroll
6293 (set-window-hscroll (selected-window) target-hscroll))
6294 ;; vertical-motion can move more than it was asked to if it moves
6295 ;; across display strings with newlines. We don't want to ring
6296 ;; the bell and announce beginning/end of buffer in that case.
6297 (or (and (or (and (>= arg 0)
6298 (>= (vertical-motion
6299 (cons (or goal-column
6300 (if (consp temporary-goal-column)
6301 (car temporary-goal-column)
6302 temporary-goal-column))
6303 arg))
6304 arg))
6305 (and (< arg 0)
6306 (<= (vertical-motion
6307 (cons (or goal-column
6308 (if (consp temporary-goal-column)
6309 (car temporary-goal-column)
6310 temporary-goal-column))
6311 arg))
6312 arg)))
6313 (or (>= arg 0)
6314 (/= (point) opoint)
6315 ;; If the goal column lies on a display string,
6316 ;; `vertical-motion' advances the cursor to the end
6317 ;; of the string. For arg < 0, this can cause the
6318 ;; cursor to get stuck. (Bug#3020).
6319 (= (vertical-motion arg) arg)))
6320 (unless noerror
6321 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6322 nil)))))
6324 ;; This is the guts of next-line and previous-line.
6325 ;; Arg says how many lines to move.
6326 ;; The value is t if we can move the specified number of lines.
6327 (defun line-move-1 (arg &optional noerror _to-end)
6328 ;; Don't run any point-motion hooks, and disregard intangibility,
6329 ;; for intermediate positions.
6330 (let ((inhibit-point-motion-hooks t)
6331 (opoint (point))
6332 (orig-arg arg))
6333 (if (consp temporary-goal-column)
6334 (setq temporary-goal-column (+ (car temporary-goal-column)
6335 (cdr temporary-goal-column))))
6336 (unwind-protect
6337 (progn
6338 (if (not (memq last-command '(next-line previous-line)))
6339 (setq temporary-goal-column
6340 (if (and track-eol (eolp)
6341 ;; Don't count beg of empty line as end of line
6342 ;; unless we just did explicit end-of-line.
6343 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6344 most-positive-fixnum
6345 (current-column))))
6347 (if (not (or (integerp selective-display)
6348 line-move-ignore-invisible))
6349 ;; Use just newline characters.
6350 ;; Set ARG to 0 if we move as many lines as requested.
6351 (or (if (> arg 0)
6352 (progn (if (> arg 1) (forward-line (1- arg)))
6353 ;; This way of moving forward ARG lines
6354 ;; verifies that we have a newline after the last one.
6355 ;; It doesn't get confused by intangible text.
6356 (end-of-line)
6357 (if (zerop (forward-line 1))
6358 (setq arg 0)))
6359 (and (zerop (forward-line arg))
6360 (bolp)
6361 (setq arg 0)))
6362 (unless noerror
6363 (signal (if (< arg 0)
6364 'beginning-of-buffer
6365 'end-of-buffer)
6366 nil)))
6367 ;; Move by arg lines, but ignore invisible ones.
6368 (let (done)
6369 (while (and (> arg 0) (not done))
6370 ;; If the following character is currently invisible,
6371 ;; skip all characters with that same `invisible' property value.
6372 (while (and (not (eobp)) (invisible-p (point)))
6373 (goto-char (next-char-property-change (point))))
6374 ;; Move a line.
6375 ;; We don't use `end-of-line', since we want to escape
6376 ;; from field boundaries occurring exactly at point.
6377 (goto-char (constrain-to-field
6378 (let ((inhibit-field-text-motion t))
6379 (line-end-position))
6380 (point) t t
6381 'inhibit-line-move-field-capture))
6382 ;; If there's no invisibility here, move over the newline.
6383 (cond
6384 ((eobp)
6385 (if (not noerror)
6386 (signal 'end-of-buffer nil)
6387 (setq done t)))
6388 ((and (> arg 1) ;; Use vertical-motion for last move
6389 (not (integerp selective-display))
6390 (not (invisible-p (point))))
6391 ;; We avoid vertical-motion when possible
6392 ;; because that has to fontify.
6393 (forward-line 1))
6394 ;; Otherwise move a more sophisticated way.
6395 ((zerop (vertical-motion 1))
6396 (if (not noerror)
6397 (signal 'end-of-buffer nil)
6398 (setq done t))))
6399 (unless done
6400 (setq arg (1- arg))))
6401 ;; The logic of this is the same as the loop above,
6402 ;; it just goes in the other direction.
6403 (while (and (< arg 0) (not done))
6404 ;; For completely consistency with the forward-motion
6405 ;; case, we should call beginning-of-line here.
6406 ;; However, if point is inside a field and on a
6407 ;; continued line, the call to (vertical-motion -1)
6408 ;; below won't move us back far enough; then we return
6409 ;; to the same column in line-move-finish, and point
6410 ;; gets stuck -- cyd
6411 (forward-line 0)
6412 (cond
6413 ((bobp)
6414 (if (not noerror)
6415 (signal 'beginning-of-buffer nil)
6416 (setq done t)))
6417 ((and (< arg -1) ;; Use vertical-motion for last move
6418 (not (integerp selective-display))
6419 (not (invisible-p (1- (point)))))
6420 (forward-line -1))
6421 ((zerop (vertical-motion -1))
6422 (if (not noerror)
6423 (signal 'beginning-of-buffer nil)
6424 (setq done t))))
6425 (unless done
6426 (setq arg (1+ arg))
6427 (while (and ;; Don't move over previous invis lines
6428 ;; if our target is the middle of this line.
6429 (or (zerop (or goal-column temporary-goal-column))
6430 (< arg 0))
6431 (not (bobp)) (invisible-p (1- (point))))
6432 (goto-char (previous-char-property-change (point))))))))
6433 ;; This is the value the function returns.
6434 (= arg 0))
6436 (cond ((> arg 0)
6437 ;; If we did not move down as far as desired, at least go
6438 ;; to end of line. Be sure to call point-entered and
6439 ;; point-left-hooks.
6440 (let* ((npoint (prog1 (line-end-position)
6441 (goto-char opoint)))
6442 (inhibit-point-motion-hooks nil))
6443 (goto-char npoint)))
6444 ((< arg 0)
6445 ;; If we did not move up as far as desired,
6446 ;; at least go to beginning of line.
6447 (let* ((npoint (prog1 (line-beginning-position)
6448 (goto-char opoint)))
6449 (inhibit-point-motion-hooks nil))
6450 (goto-char npoint)))
6452 (line-move-finish (or goal-column temporary-goal-column)
6453 opoint (> orig-arg 0)))))))
6455 (defun line-move-finish (column opoint forward)
6456 (let ((repeat t))
6457 (while repeat
6458 ;; Set REPEAT to t to repeat the whole thing.
6459 (setq repeat nil)
6461 (let (new
6462 (old (point))
6463 (line-beg (line-beginning-position))
6464 (line-end
6465 ;; Compute the end of the line
6466 ;; ignoring effectively invisible newlines.
6467 (save-excursion
6468 ;; Like end-of-line but ignores fields.
6469 (skip-chars-forward "^\n")
6470 (while (and (not (eobp)) (invisible-p (point)))
6471 (goto-char (next-char-property-change (point)))
6472 (skip-chars-forward "^\n"))
6473 (point))))
6475 ;; Move to the desired column.
6476 (if (and line-move-visual
6477 (not (or truncate-lines truncate-partial-width-windows)))
6478 ;; Under line-move-visual, goal-column should be
6479 ;; interpreted in units of the frame's canonical character
6480 ;; width, which is exactly what vertical-motion does.
6481 (vertical-motion (cons column 0))
6482 (line-move-to-column (truncate column)))
6484 ;; Corner case: suppose we start out in a field boundary in
6485 ;; the middle of a continued line. When we get to
6486 ;; line-move-finish, point is at the start of a new *screen*
6487 ;; line but the same text line; then line-move-to-column would
6488 ;; move us backwards. Test using C-n with point on the "x" in
6489 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6490 (and forward
6491 (< (point) old)
6492 (goto-char old))
6494 (setq new (point))
6496 ;; Process intangibility within a line.
6497 ;; With inhibit-point-motion-hooks bound to nil, a call to
6498 ;; goto-char moves point past intangible text.
6500 ;; However, inhibit-point-motion-hooks controls both the
6501 ;; intangibility and the point-entered/point-left hooks. The
6502 ;; following hack avoids calling the point-* hooks
6503 ;; unnecessarily. Note that we move *forward* past intangible
6504 ;; text when the initial and final points are the same.
6505 (goto-char new)
6506 (let ((inhibit-point-motion-hooks nil))
6507 (goto-char new)
6509 ;; If intangibility moves us to a different (later) place
6510 ;; in the same line, use that as the destination.
6511 (if (<= (point) line-end)
6512 (setq new (point))
6513 ;; If that position is "too late",
6514 ;; try the previous allowable position.
6515 ;; See if it is ok.
6516 (backward-char)
6517 (if (if forward
6518 ;; If going forward, don't accept the previous
6519 ;; allowable position if it is before the target line.
6520 (< line-beg (point))
6521 ;; If going backward, don't accept the previous
6522 ;; allowable position if it is still after the target line.
6523 (<= (point) line-end))
6524 (setq new (point))
6525 ;; As a last resort, use the end of the line.
6526 (setq new line-end))))
6528 ;; Now move to the updated destination, processing fields
6529 ;; as well as intangibility.
6530 (goto-char opoint)
6531 (let ((inhibit-point-motion-hooks nil))
6532 (goto-char
6533 ;; Ignore field boundaries if the initial and final
6534 ;; positions have the same `field' property, even if the
6535 ;; fields are non-contiguous. This seems to be "nicer"
6536 ;; behavior in many situations.
6537 (if (eq (get-char-property new 'field)
6538 (get-char-property opoint 'field))
6540 (constrain-to-field new opoint t t
6541 'inhibit-line-move-field-capture))))
6543 ;; If all this moved us to a different line,
6544 ;; retry everything within that new line.
6545 (when (or (< (point) line-beg) (> (point) line-end))
6546 ;; Repeat the intangibility and field processing.
6547 (setq repeat t))))))
6549 (defun line-move-to-column (col)
6550 "Try to find column COL, considering invisibility.
6551 This function works only in certain cases,
6552 because what we really need is for `move-to-column'
6553 and `current-column' to be able to ignore invisible text."
6554 (if (zerop col)
6555 (beginning-of-line)
6556 (move-to-column col))
6558 (when (and line-move-ignore-invisible
6559 (not (bolp)) (invisible-p (1- (point))))
6560 (let ((normal-location (point))
6561 (normal-column (current-column)))
6562 ;; If the following character is currently invisible,
6563 ;; skip all characters with that same `invisible' property value.
6564 (while (and (not (eobp))
6565 (invisible-p (point)))
6566 (goto-char (next-char-property-change (point))))
6567 ;; Have we advanced to a larger column position?
6568 (if (> (current-column) normal-column)
6569 ;; We have made some progress towards the desired column.
6570 ;; See if we can make any further progress.
6571 (line-move-to-column (+ (current-column) (- col normal-column)))
6572 ;; Otherwise, go to the place we originally found
6573 ;; and move back over invisible text.
6574 ;; that will get us to the same place on the screen
6575 ;; but with a more reasonable buffer position.
6576 (goto-char normal-location)
6577 (let ((line-beg
6578 ;; We want the real line beginning, so it's consistent
6579 ;; with bolp below, otherwise we might infloop.
6580 (let ((inhibit-field-text-motion t))
6581 (line-beginning-position))))
6582 (while (and (not (bolp)) (invisible-p (1- (point))))
6583 (goto-char (previous-char-property-change (point) line-beg))))))))
6585 (defun move-end-of-line (arg)
6586 "Move point to end of current line as displayed.
6587 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6588 If point reaches the beginning or end of buffer, it stops there.
6590 To ignore the effects of the `intangible' text or overlay
6591 property, bind `inhibit-point-motion-hooks' to t.
6592 If there is an image in the current line, this function
6593 disregards newlines that are part of the text on which the image
6594 rests."
6595 (interactive "^p")
6596 (or arg (setq arg 1))
6597 (let (done)
6598 (while (not done)
6599 (let ((newpos
6600 (save-excursion
6601 (let ((goal-column 0)
6602 (line-move-visual nil))
6603 (and (line-move arg t)
6604 ;; With bidi reordering, we may not be at bol,
6605 ;; so make sure we are.
6606 (skip-chars-backward "^\n")
6607 (not (bobp))
6608 (progn
6609 (while (and (not (bobp)) (invisible-p (1- (point))))
6610 (goto-char (previous-single-char-property-change
6611 (point) 'invisible)))
6612 (backward-char 1)))
6613 (point)))))
6614 (goto-char newpos)
6615 (if (and (> (point) newpos)
6616 (eq (preceding-char) ?\n))
6617 (backward-char 1)
6618 (if (and (> (point) newpos) (not (eobp))
6619 (not (eq (following-char) ?\n)))
6620 ;; If we skipped something intangible and now we're not
6621 ;; really at eol, keep going.
6622 (setq arg 1)
6623 (setq done t)))))))
6625 (defun move-beginning-of-line (arg)
6626 "Move point to beginning of current line as displayed.
6627 \(If there's an image in the line, this disregards newlines
6628 which are part of the text that the image rests on.)
6630 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6631 If point reaches the beginning or end of buffer, it stops there.
6632 \(But if the buffer doesn't end in a newline, it stops at the
6633 beginning of the last line.)
6634 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6635 (interactive "^p")
6636 (or arg (setq arg 1))
6638 (let ((orig (point))
6639 first-vis first-vis-field-value)
6641 ;; Move by lines, if ARG is not 1 (the default).
6642 (if (/= arg 1)
6643 (let ((line-move-visual nil))
6644 (line-move (1- arg) t)))
6646 ;; Move to beginning-of-line, ignoring fields and invisible text.
6647 (skip-chars-backward "^\n")
6648 (while (and (not (bobp)) (invisible-p (1- (point))))
6649 (goto-char (previous-char-property-change (point)))
6650 (skip-chars-backward "^\n"))
6652 ;; Now find first visible char in the line.
6653 (while (and (< (point) orig) (invisible-p (point)))
6654 (goto-char (next-char-property-change (point) orig)))
6655 (setq first-vis (point))
6657 ;; See if fields would stop us from reaching FIRST-VIS.
6658 (setq first-vis-field-value
6659 (constrain-to-field first-vis orig (/= arg 1) t nil))
6661 (goto-char (if (/= first-vis-field-value first-vis)
6662 ;; If yes, obey them.
6663 first-vis-field-value
6664 ;; Otherwise, move to START with attention to fields.
6665 ;; (It is possible that fields never matter in this case.)
6666 (constrain-to-field (point) orig
6667 (/= arg 1) t nil)))))
6670 ;; Many people have said they rarely use this feature, and often type
6671 ;; it by accident. Maybe it shouldn't even be on a key.
6672 (put 'set-goal-column 'disabled t)
6674 (defun set-goal-column (arg)
6675 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6676 Those commands will move to this position in the line moved to
6677 rather than trying to keep the same horizontal position.
6678 With a non-nil argument ARG, clears out the goal column
6679 so that \\[next-line] and \\[previous-line] resume vertical motion.
6680 The goal column is stored in the variable `goal-column'.
6681 This is a buffer-local setting."
6682 (interactive "P")
6683 (if arg
6684 (progn
6685 (setq goal-column nil)
6686 (message "No goal column"))
6687 (setq goal-column (current-column))
6688 ;; The older method below can be erroneous if `set-goal-column' is bound
6689 ;; to a sequence containing %
6690 ;;(message (substitute-command-keys
6691 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6692 ;;goal-column)
6693 (message "%s"
6694 (concat
6695 (format "Goal column %d " goal-column)
6696 (substitute-command-keys
6697 "(use \\[set-goal-column] with an arg to unset it)")))
6700 nil)
6702 ;;; Editing based on visual lines, as opposed to logical lines.
6704 (defun end-of-visual-line (&optional n)
6705 "Move point to end of current visual line.
6706 With argument N not nil or 1, move forward N - 1 visual lines first.
6707 If point reaches the beginning or end of buffer, it stops there.
6708 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6709 (interactive "^p")
6710 (or n (setq n 1))
6711 (if (/= n 1)
6712 (let ((line-move-visual t))
6713 (line-move (1- n) t)))
6714 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6715 ;; constrain to field boundaries, so we don't either.
6716 (vertical-motion (cons (window-width) 0)))
6718 (defun beginning-of-visual-line (&optional n)
6719 "Move point to beginning of current visual line.
6720 With argument N not nil or 1, move forward N - 1 visual lines first.
6721 If point reaches the beginning or end of buffer, it stops there.
6722 \(But if the buffer doesn't end in a newline, it stops at the
6723 beginning of the last visual line.)
6724 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6725 (interactive "^p")
6726 (or n (setq n 1))
6727 (let ((opoint (point)))
6728 (if (/= n 1)
6729 (let ((line-move-visual t))
6730 (line-move (1- n) t)))
6731 (vertical-motion 0)
6732 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6733 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6735 (defun kill-visual-line (&optional arg)
6736 "Kill the rest of the visual line.
6737 With prefix argument ARG, kill that many visual lines from point.
6738 If ARG is negative, kill visual lines backward.
6739 If ARG is zero, kill the text before point on the current visual
6740 line.
6742 If you want to append the killed line to the last killed text,
6743 use \\[append-next-kill] before \\[kill-line].
6745 If the buffer is read-only, Emacs will beep and refrain from deleting
6746 the line, but put the line in the kill ring anyway. This means that
6747 you can use this command to copy text from a read-only buffer.
6748 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6749 even beep.)"
6750 (interactive "P")
6751 ;; Like in `kill-line', it's better to move point to the other end
6752 ;; of the kill before killing.
6753 (let ((opoint (point))
6754 (kill-whole-line (and kill-whole-line (bolp))))
6755 (if arg
6756 (vertical-motion (prefix-numeric-value arg))
6757 (end-of-visual-line 1)
6758 (if (= (point) opoint)
6759 (vertical-motion 1)
6760 ;; Skip any trailing whitespace at the end of the visual line.
6761 ;; We used to do this only if `show-trailing-whitespace' is
6762 ;; nil, but that's wrong; the correct thing would be to check
6763 ;; whether the trailing whitespace is highlighted. But, it's
6764 ;; OK to just do this unconditionally.
6765 (skip-chars-forward " \t")))
6766 (kill-region opoint (if (and kill-whole-line (= (following-char) ?\n))
6767 (1+ (point))
6768 (point)))))
6770 (defun next-logical-line (&optional arg try-vscroll)
6771 "Move cursor vertically down ARG lines.
6772 This is identical to `next-line', except that it always moves
6773 by logical lines instead of visual lines, ignoring the value of
6774 the variable `line-move-visual'."
6775 (interactive "^p\np")
6776 (let ((line-move-visual nil))
6777 (with-no-warnings
6778 (next-line arg try-vscroll))))
6780 (defun previous-logical-line (&optional arg try-vscroll)
6781 "Move cursor vertically up ARG lines.
6782 This is identical to `previous-line', except that it always moves
6783 by logical lines instead of visual lines, ignoring the value of
6784 the variable `line-move-visual'."
6785 (interactive "^p\np")
6786 (let ((line-move-visual nil))
6787 (with-no-warnings
6788 (previous-line arg try-vscroll))))
6790 (defgroup visual-line nil
6791 "Editing based on visual lines."
6792 :group 'convenience
6793 :version "23.1")
6795 (defvar visual-line-mode-map
6796 (let ((map (make-sparse-keymap)))
6797 (define-key map [remap kill-line] 'kill-visual-line)
6798 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6799 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6800 ;; These keybindings interfere with xterm function keys. Are
6801 ;; there any other suitable bindings?
6802 ;; (define-key map "\M-[" 'previous-logical-line)
6803 ;; (define-key map "\M-]" 'next-logical-line)
6804 map))
6806 (defcustom visual-line-fringe-indicators '(nil nil)
6807 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6808 The value should be a list of the form (LEFT RIGHT), where LEFT
6809 and RIGHT are symbols representing the bitmaps to display, to
6810 indicate wrapped lines, in the left and right fringes respectively.
6811 See also `fringe-indicator-alist'.
6812 The default is not to display fringe indicators for wrapped lines.
6813 This variable does not affect fringe indicators displayed for
6814 other purposes."
6815 :type '(list (choice (const :tag "Hide left indicator" nil)
6816 (const :tag "Left curly arrow" left-curly-arrow)
6817 (symbol :tag "Other bitmap"))
6818 (choice (const :tag "Hide right indicator" nil)
6819 (const :tag "Right curly arrow" right-curly-arrow)
6820 (symbol :tag "Other bitmap")))
6821 :set (lambda (symbol value)
6822 (dolist (buf (buffer-list))
6823 (with-current-buffer buf
6824 (when (and (boundp 'visual-line-mode)
6825 (symbol-value 'visual-line-mode))
6826 (setq fringe-indicator-alist
6827 (cons (cons 'continuation value)
6828 (assq-delete-all
6829 'continuation
6830 (copy-tree fringe-indicator-alist)))))))
6831 (set-default symbol value)))
6833 (defvar visual-line--saved-state nil)
6835 (define-minor-mode visual-line-mode
6836 "Toggle visual line based editing (Visual Line mode) in the current buffer.
6837 Interactively, with a prefix argument, enable
6838 Visual Line mode if the prefix argument is positive,
6839 and disable it otherwise. If called from Lisp, toggle
6840 the mode if ARG is `toggle', disable the mode if ARG is
6841 a non-positive integer, and enable the mode otherwise
6842 \(including if ARG is omitted or nil or a positive integer).
6844 When Visual Line mode is enabled, `word-wrap' is turned on in
6845 this buffer, and simple editing commands are redefined to act on
6846 visual lines, not logical lines. See Info node `Visual Line
6847 Mode' for details."
6848 :keymap visual-line-mode-map
6849 :group 'visual-line
6850 :lighter " Wrap"
6851 (if visual-line-mode
6852 (progn
6853 (set (make-local-variable 'visual-line--saved-state) nil)
6854 ;; Save the local values of some variables, to be restored if
6855 ;; visual-line-mode is turned off.
6856 (dolist (var '(line-move-visual truncate-lines
6857 truncate-partial-width-windows
6858 word-wrap fringe-indicator-alist))
6859 (if (local-variable-p var)
6860 (push (cons var (symbol-value var))
6861 visual-line--saved-state)))
6862 (set (make-local-variable 'line-move-visual) t)
6863 (set (make-local-variable 'truncate-partial-width-windows) nil)
6864 (setq truncate-lines nil
6865 word-wrap t
6866 fringe-indicator-alist
6867 (cons (cons 'continuation visual-line-fringe-indicators)
6868 fringe-indicator-alist)))
6869 (kill-local-variable 'line-move-visual)
6870 (kill-local-variable 'word-wrap)
6871 (kill-local-variable 'truncate-lines)
6872 (kill-local-variable 'truncate-partial-width-windows)
6873 (kill-local-variable 'fringe-indicator-alist)
6874 (dolist (saved visual-line--saved-state)
6875 (set (make-local-variable (car saved)) (cdr saved)))
6876 (kill-local-variable 'visual-line--saved-state)))
6878 (defun turn-on-visual-line-mode ()
6879 (visual-line-mode 1))
6881 (define-globalized-minor-mode global-visual-line-mode
6882 visual-line-mode turn-on-visual-line-mode)
6885 (defun transpose-chars (arg)
6886 "Interchange characters around point, moving forward one character.
6887 With prefix arg ARG, effect is to take character before point
6888 and drag it forward past ARG other characters (backward if ARG negative).
6889 If no argument and at end of line, the previous two chars are exchanged."
6890 (interactive "*P")
6891 (when (and (null arg) (eolp) (not (bobp))
6892 (not (get-text-property (1- (point)) 'read-only)))
6893 (forward-char -1))
6894 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6896 (defun transpose-words (arg)
6897 "Interchange words around point, leaving point at end of them.
6898 With prefix arg ARG, effect is to take word before or around point
6899 and drag it forward past ARG other words (backward if ARG negative).
6900 If ARG is zero, the words around or after point and around or after mark
6901 are interchanged."
6902 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6903 (interactive "*p")
6904 (transpose-subr 'forward-word arg))
6906 (defun transpose-sexps (arg)
6907 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6908 Unlike `transpose-words', point must be between the two sexps and not
6909 in the middle of a sexp to be transposed.
6910 With non-zero prefix arg ARG, effect is to take the sexp before point
6911 and drag it forward past ARG other sexps (backward if ARG is negative).
6912 If ARG is zero, the sexps ending at or after point and at or after mark
6913 are interchanged."
6914 (interactive "*p")
6915 (transpose-subr
6916 (lambda (arg)
6917 ;; Here we should try to simulate the behavior of
6918 ;; (cons (progn (forward-sexp x) (point))
6919 ;; (progn (forward-sexp (- x)) (point)))
6920 ;; Except that we don't want to rely on the second forward-sexp
6921 ;; putting us back to where we want to be, since forward-sexp-function
6922 ;; might do funny things like infix-precedence.
6923 (if (if (> arg 0)
6924 (looking-at "\\sw\\|\\s_")
6925 (and (not (bobp))
6926 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6927 ;; Jumping over a symbol. We might be inside it, mind you.
6928 (progn (funcall (if (> arg 0)
6929 'skip-syntax-backward 'skip-syntax-forward)
6930 "w_")
6931 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6932 ;; Otherwise, we're between sexps. Take a step back before jumping
6933 ;; to make sure we'll obey the same precedence no matter which direction
6934 ;; we're going.
6935 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6936 (cons (save-excursion (forward-sexp arg) (point))
6937 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6938 (not (zerop (funcall (if (> arg 0)
6939 'skip-syntax-forward
6940 'skip-syntax-backward)
6941 ".")))))
6942 (point)))))
6943 arg 'special))
6945 (defun transpose-lines (arg)
6946 "Exchange current line and previous line, leaving point after both.
6947 With argument ARG, takes previous line and moves it past ARG lines.
6948 With argument 0, interchanges line point is in with line mark is in."
6949 (interactive "*p")
6950 (transpose-subr (function
6951 (lambda (arg)
6952 (if (> arg 0)
6953 (progn
6954 ;; Move forward over ARG lines,
6955 ;; but create newlines if necessary.
6956 (setq arg (forward-line arg))
6957 (if (/= (preceding-char) ?\n)
6958 (setq arg (1+ arg)))
6959 (if (> arg 0)
6960 (newline arg)))
6961 (forward-line arg))))
6962 arg))
6964 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6965 ;; which seems inconsistent with the ARG /= 0 case.
6966 ;; FIXME document SPECIAL.
6967 (defun transpose-subr (mover arg &optional special)
6968 "Subroutine to do the work of transposing objects.
6969 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6970 moves forward by units of the given object (e.g. forward-sentence,
6971 forward-paragraph). If ARG is zero, exchanges the current object
6972 with the one containing mark. If ARG is an integer, moves the
6973 current object past ARG following (if ARG is positive) or
6974 preceding (if ARG is negative) objects, leaving point after the
6975 current object."
6976 (let ((aux (if special mover
6977 (lambda (x)
6978 (cons (progn (funcall mover x) (point))
6979 (progn (funcall mover (- x)) (point))))))
6980 pos1 pos2)
6981 (cond
6982 ((= arg 0)
6983 (save-excursion
6984 (setq pos1 (funcall aux 1))
6985 (goto-char (or (mark) (error "No mark set in this buffer")))
6986 (setq pos2 (funcall aux 1))
6987 (transpose-subr-1 pos1 pos2))
6988 (exchange-point-and-mark))
6989 ((> arg 0)
6990 (setq pos1 (funcall aux -1))
6991 (setq pos2 (funcall aux arg))
6992 (transpose-subr-1 pos1 pos2)
6993 (goto-char (car pos2)))
6995 (setq pos1 (funcall aux -1))
6996 (goto-char (car pos1))
6997 (setq pos2 (funcall aux arg))
6998 (transpose-subr-1 pos1 pos2)
6999 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
7001 (defun transpose-subr-1 (pos1 pos2)
7002 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
7003 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
7004 (when (> (car pos1) (car pos2))
7005 (let ((swap pos1))
7006 (setq pos1 pos2 pos2 swap)))
7007 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
7008 (atomic-change-group
7009 ;; This sequence of insertions attempts to preserve marker
7010 ;; positions at the start and end of the transposed objects.
7011 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
7012 (len1 (- (cdr pos1) (car pos1)))
7013 (len2 (length word))
7014 (boundary (make-marker)))
7015 (set-marker boundary (car pos2))
7016 (goto-char (cdr pos1))
7017 (insert-before-markers word)
7018 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
7019 (goto-char boundary)
7020 (insert word)
7021 (goto-char (+ boundary len1))
7022 (delete-region (point) (+ (point) len2))
7023 (set-marker boundary nil))))
7025 (defun backward-word (&optional arg)
7026 "Move backward until encountering the beginning of a word.
7027 With argument ARG, do this that many times.
7028 If ARG is omitted or nil, move point backward one word.
7030 The word boundaries are normally determined by the buffer's syntax
7031 table, but `find-word-boundary-function-table', such as set up
7032 by `subword-mode', can change that. If a Lisp program needs to
7033 move by words determined strictly by the syntax table, it should
7034 use `backward-word-strictly' instead."
7035 (interactive "^p")
7036 (forward-word (- (or arg 1))))
7038 (defun mark-word (&optional arg allow-extend)
7039 "Set mark ARG words away from point.
7040 The place mark goes is the same place \\[forward-word] would
7041 move to with the same argument.
7042 Interactively, if this command is repeated
7043 or (in Transient Mark mode) if the mark is active,
7044 it marks the next ARG words after the ones already marked."
7045 (interactive "P\np")
7046 (cond ((and allow-extend
7047 (or (and (eq last-command this-command) (mark t))
7048 (region-active-p)))
7049 (setq arg (if arg (prefix-numeric-value arg)
7050 (if (< (mark) (point)) -1 1)))
7051 (set-mark
7052 (save-excursion
7053 (goto-char (mark))
7054 (forward-word arg)
7055 (point))))
7057 (push-mark
7058 (save-excursion
7059 (forward-word (prefix-numeric-value arg))
7060 (point))
7061 nil t))))
7063 (defun kill-word (arg)
7064 "Kill characters forward until encountering the end of a word.
7065 With argument ARG, do this that many times."
7066 (interactive "p")
7067 (kill-region (point) (progn (forward-word arg) (point))))
7069 (defun backward-kill-word (arg)
7070 "Kill characters backward until encountering the beginning of a word.
7071 With argument ARG, do this that many times."
7072 (interactive "p")
7073 (kill-word (- arg)))
7075 (defun current-word (&optional strict really-word)
7076 "Return the word at or near point, as a string.
7077 The return value includes no text properties.
7079 If optional arg STRICT is non-nil, return nil unless point is
7080 within or adjacent to a word, otherwise look for a word within
7081 point's line. If there is no word anywhere on point's line, the
7082 value is nil regardless of STRICT.
7084 By default, this function treats as a single word any sequence of
7085 characters that have either word or symbol syntax. If optional
7086 arg REALLY-WORD is non-nil, only characters of word syntax can
7087 constitute a word."
7088 (save-excursion
7089 (let* ((oldpoint (point)) (start (point)) (end (point))
7090 (syntaxes (if really-word "w" "w_"))
7091 (not-syntaxes (concat "^" syntaxes)))
7092 (skip-syntax-backward syntaxes) (setq start (point))
7093 (goto-char oldpoint)
7094 (skip-syntax-forward syntaxes) (setq end (point))
7095 (when (and (eq start oldpoint) (eq end oldpoint)
7096 ;; Point is neither within nor adjacent to a word.
7097 (not strict))
7098 ;; Look for preceding word in same line.
7099 (skip-syntax-backward not-syntaxes (line-beginning-position))
7100 (if (bolp)
7101 ;; No preceding word in same line.
7102 ;; Look for following word in same line.
7103 (progn
7104 (skip-syntax-forward not-syntaxes (line-end-position))
7105 (setq start (point))
7106 (skip-syntax-forward syntaxes)
7107 (setq end (point)))
7108 (setq end (point))
7109 (skip-syntax-backward syntaxes)
7110 (setq start (point))))
7111 ;; If we found something nonempty, return it as a string.
7112 (unless (= start end)
7113 (buffer-substring-no-properties start end)))))
7115 (defcustom fill-prefix nil
7116 "String for filling to insert at front of new line, or nil for none."
7117 :type '(choice (const :tag "None" nil)
7118 string)
7119 :group 'fill)
7120 (make-variable-buffer-local 'fill-prefix)
7121 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
7123 (defcustom auto-fill-inhibit-regexp nil
7124 "Regexp to match lines which should not be auto-filled."
7125 :type '(choice (const :tag "None" nil)
7126 regexp)
7127 :group 'fill)
7129 (defun do-auto-fill ()
7130 "The default value for `normal-auto-fill-function'.
7131 This is the default auto-fill function, some major modes use a different one.
7132 Returns t if it really did any work."
7133 (let (fc justify give-up
7134 (fill-prefix fill-prefix))
7135 (if (or (not (setq justify (current-justification)))
7136 (null (setq fc (current-fill-column)))
7137 (and (eq justify 'left)
7138 (<= (current-column) fc))
7139 (and auto-fill-inhibit-regexp
7140 (save-excursion (beginning-of-line)
7141 (looking-at auto-fill-inhibit-regexp))))
7142 nil ;; Auto-filling not required
7143 (if (memq justify '(full center right))
7144 (save-excursion (unjustify-current-line)))
7146 ;; Choose a fill-prefix automatically.
7147 (when (and adaptive-fill-mode
7148 (or (null fill-prefix) (string= fill-prefix "")))
7149 (let ((prefix
7150 (fill-context-prefix
7151 (save-excursion (fill-forward-paragraph -1) (point))
7152 (save-excursion (fill-forward-paragraph 1) (point)))))
7153 (and prefix (not (equal prefix ""))
7154 ;; Use auto-indentation rather than a guessed empty prefix.
7155 (not (and fill-indent-according-to-mode
7156 (string-match "\\`[ \t]*\\'" prefix)))
7157 (setq fill-prefix prefix))))
7159 (while (and (not give-up) (> (current-column) fc))
7160 ;; Determine where to split the line.
7161 (let ((fill-point
7162 (save-excursion
7163 (beginning-of-line)
7164 ;; Don't split earlier in the line than the length of the
7165 ;; fill prefix, since the resulting line would be longer.
7166 (when fill-prefix
7167 (move-to-column (string-width fill-prefix)))
7168 (let ((after-prefix (point)))
7169 (move-to-column (1+ fc))
7170 (fill-move-to-break-point after-prefix)
7171 (point)))))
7173 ;; See whether the place we found is any good.
7174 (if (save-excursion
7175 (goto-char fill-point)
7176 (or (bolp)
7177 ;; There is no use breaking at end of line.
7178 (save-excursion (skip-chars-forward " ") (eolp))
7179 ;; Don't split right after a comment starter
7180 ;; since we would just make another comment starter.
7181 (and comment-start-skip
7182 (let ((limit (point)))
7183 (beginning-of-line)
7184 (and (re-search-forward comment-start-skip
7185 limit t)
7186 (eq (point) limit))))))
7187 ;; No good place to break => stop trying.
7188 (setq give-up t)
7189 ;; Ok, we have a useful place to break the line. Do it.
7190 (let ((prev-column (current-column)))
7191 ;; If point is at the fill-point, do not `save-excursion'.
7192 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7193 ;; point will end up before it rather than after it.
7194 (if (save-excursion
7195 (skip-chars-backward " \t")
7196 (= (point) fill-point))
7197 (default-indent-new-line t)
7198 (save-excursion
7199 (goto-char fill-point)
7200 (default-indent-new-line t)))
7201 ;; Now do justification, if required
7202 (if (not (eq justify 'left))
7203 (save-excursion
7204 (end-of-line 0)
7205 (justify-current-line justify nil t)))
7206 ;; If making the new line didn't reduce the hpos of
7207 ;; the end of the line, then give up now;
7208 ;; trying again will not help.
7209 (if (>= (current-column) prev-column)
7210 (setq give-up t))))))
7211 ;; Justify last line.
7212 (justify-current-line justify t t)
7213 t)))
7215 (defvar comment-line-break-function 'comment-indent-new-line
7216 "Mode-specific function which line breaks and continues a comment.
7217 This function is called during auto-filling when a comment syntax
7218 is defined.
7219 The function should take a single optional argument, which is a flag
7220 indicating whether it should use soft newlines.")
7222 (defun default-indent-new-line (&optional soft)
7223 "Break line at point and indent.
7224 If a comment syntax is defined, call `comment-indent-new-line'.
7226 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7227 unless optional argument SOFT is non-nil."
7228 (interactive)
7229 (if comment-start
7230 (funcall comment-line-break-function soft)
7231 ;; Insert the newline before removing empty space so that markers
7232 ;; get preserved better.
7233 (if soft (insert-and-inherit ?\n) (newline 1))
7234 (save-excursion (forward-char -1) (delete-horizontal-space))
7235 (delete-horizontal-space)
7237 (if (and fill-prefix (not adaptive-fill-mode))
7238 ;; Blindly trust a non-adaptive fill-prefix.
7239 (progn
7240 (indent-to-left-margin)
7241 (insert-before-markers-and-inherit fill-prefix))
7243 (cond
7244 ;; If there's an adaptive prefix, use it unless we're inside
7245 ;; a comment and the prefix is not a comment starter.
7246 (fill-prefix
7247 (indent-to-left-margin)
7248 (insert-and-inherit fill-prefix))
7249 ;; If we're not inside a comment, just try to indent.
7250 (t (indent-according-to-mode))))))
7252 (defun internal-auto-fill ()
7253 "The function called by `self-insert-command' to perform auto-filling."
7254 (when (or (not comment-start)
7255 (not comment-auto-fill-only-comments)
7256 (nth 4 (syntax-ppss)))
7257 (funcall auto-fill-function)))
7259 (defvar normal-auto-fill-function 'do-auto-fill
7260 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7261 Some major modes set this.")
7263 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7264 ;; `functions' and `hooks' are usually unsafe to set, but setting
7265 ;; auto-fill-function to nil in a file-local setting is safe and
7266 ;; can be useful to prevent auto-filling.
7267 (put 'auto-fill-function 'safe-local-variable 'null)
7269 (define-minor-mode auto-fill-mode
7270 "Toggle automatic line breaking (Auto Fill mode).
7271 Interactively, with a prefix argument, enable
7272 Auto Fill mode if the prefix argument is positive,
7273 and disable it otherwise. If called from Lisp, toggle
7274 the mode if ARG is `toggle', disable the mode if ARG is
7275 a non-positive integer, and enable the mode otherwise
7276 \(including if ARG is omitted or nil or a positive integer).
7278 When Auto Fill mode is enabled, inserting a space at a column
7279 beyond `current-fill-column' automatically breaks the line at a
7280 previous space.
7282 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7283 non-nil.
7285 The value of `normal-auto-fill-function' specifies the function to use
7286 for `auto-fill-function' when turning Auto Fill mode on."
7287 :variable (auto-fill-function
7288 . (lambda (v) (setq auto-fill-function
7289 (if v normal-auto-fill-function)))))
7291 ;; This holds a document string used to document auto-fill-mode.
7292 (defun auto-fill-function ()
7293 "Automatically break line at a previous space, in insertion of text."
7294 nil)
7296 (defun turn-on-auto-fill ()
7297 "Unconditionally turn on Auto Fill mode."
7298 (auto-fill-mode 1))
7300 (defun turn-off-auto-fill ()
7301 "Unconditionally turn off Auto Fill mode."
7302 (auto-fill-mode -1))
7304 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7306 (defun set-fill-column (arg)
7307 "Set `fill-column' to specified argument.
7308 Use \\[universal-argument] followed by a number to specify a column.
7309 Just \\[universal-argument] as argument means to use the current column."
7310 (interactive
7311 (list (or current-prefix-arg
7312 ;; We used to use current-column silently, but C-x f is too easily
7313 ;; typed as a typo for C-x C-f, so we turned it into an error and
7314 ;; now an interactive prompt.
7315 (read-number "Set fill-column to: " (current-column)))))
7316 (if (consp arg)
7317 (setq arg (current-column)))
7318 (if (not (integerp arg))
7319 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7320 (error "set-fill-column requires an explicit argument")
7321 (message "Fill column set to %d (was %d)" arg fill-column)
7322 (setq fill-column arg)))
7324 (defun set-selective-display (arg)
7325 "Set `selective-display' to ARG; clear it if no arg.
7326 When the value of `selective-display' is a number > 0,
7327 lines whose indentation is >= that value are not displayed.
7328 The variable `selective-display' has a separate value for each buffer."
7329 (interactive "P")
7330 (if (eq selective-display t)
7331 (error "selective-display already in use for marked lines"))
7332 (let ((current-vpos
7333 (save-restriction
7334 (narrow-to-region (point-min) (point))
7335 (goto-char (window-start))
7336 (vertical-motion (window-height)))))
7337 (setq selective-display
7338 (and arg (prefix-numeric-value arg)))
7339 (recenter current-vpos))
7340 (set-window-start (selected-window) (window-start))
7341 (princ "selective-display set to " t)
7342 (prin1 selective-display t)
7343 (princ "." t))
7345 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7347 (defun toggle-truncate-lines (&optional arg)
7348 "Toggle truncating of long lines for the current buffer.
7349 When truncating is off, long lines are folded.
7350 With prefix argument ARG, truncate long lines if ARG is positive,
7351 otherwise fold them. Note that in side-by-side windows, this
7352 command has no effect if `truncate-partial-width-windows' is
7353 non-nil."
7354 (interactive "P")
7355 (setq truncate-lines
7356 (if (null arg)
7357 (not truncate-lines)
7358 (> (prefix-numeric-value arg) 0)))
7359 (force-mode-line-update)
7360 (unless truncate-lines
7361 (let ((buffer (current-buffer)))
7362 (walk-windows (lambda (window)
7363 (if (eq buffer (window-buffer window))
7364 (set-window-hscroll window 0)))
7365 nil t)))
7366 (message "Truncate long lines %s"
7367 (if truncate-lines "enabled" "disabled")))
7369 (defun toggle-word-wrap (&optional arg)
7370 "Toggle whether to use word-wrapping for continuation lines.
7371 With prefix argument ARG, wrap continuation lines at word boundaries
7372 if ARG is positive, otherwise wrap them at the right screen edge.
7373 This command toggles the value of `word-wrap'. It has no effect
7374 if long lines are truncated."
7375 (interactive "P")
7376 (setq word-wrap
7377 (if (null arg)
7378 (not word-wrap)
7379 (> (prefix-numeric-value arg) 0)))
7380 (force-mode-line-update)
7381 (message "Word wrapping %s"
7382 (if word-wrap "enabled" "disabled")))
7384 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7385 "The string displayed in the mode line when in overwrite mode.")
7386 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7387 "The string displayed in the mode line when in binary overwrite mode.")
7389 (define-minor-mode overwrite-mode
7390 "Toggle Overwrite mode.
7391 With a prefix argument ARG, enable Overwrite mode if ARG is
7392 positive, and disable it otherwise. If called from Lisp, enable
7393 the mode if ARG is omitted or nil.
7395 When Overwrite mode is enabled, printing characters typed in
7396 replace existing text on a one-for-one basis, rather than pushing
7397 it to the right. At the end of a line, such characters extend
7398 the line. Before a tab, such characters insert until the tab is
7399 filled in. \\[quoted-insert] still inserts characters in
7400 overwrite mode; this is supposed to make it easier to insert
7401 characters when necessary."
7402 :variable (overwrite-mode
7403 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7405 (define-minor-mode binary-overwrite-mode
7406 "Toggle Binary Overwrite mode.
7407 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7408 is positive, and disable it otherwise. If called from Lisp,
7409 enable the mode if ARG is omitted or nil.
7411 When Binary Overwrite mode is enabled, printing characters typed
7412 in replace existing text. Newlines are not treated specially, so
7413 typing at the end of a line joins the line to the next, with the
7414 typed character between them. Typing before a tab character
7415 simply replaces the tab with the character typed.
7416 \\[quoted-insert] replaces the text at the cursor, just as
7417 ordinary typing characters do.
7419 Note that Binary Overwrite mode is not its own minor mode; it is
7420 a specialization of overwrite mode, entered by setting the
7421 `overwrite-mode' variable to `overwrite-mode-binary'."
7422 :variable (overwrite-mode
7423 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7425 (define-minor-mode line-number-mode
7426 "Toggle line number display in the mode line (Line Number mode).
7427 With a prefix argument ARG, enable Line Number mode if ARG is
7428 positive, and disable it otherwise. If called from Lisp, enable
7429 the mode if ARG is omitted or nil.
7431 Line numbers do not appear for very large buffers and buffers
7432 with very long lines; see variables `line-number-display-limit'
7433 and `line-number-display-limit-width'."
7434 :init-value t :global t :group 'mode-line)
7436 (define-minor-mode column-number-mode
7437 "Toggle column number display in the mode line (Column Number mode).
7438 With a prefix argument ARG, enable Column Number mode if ARG is
7439 positive, and disable it otherwise.
7441 If called from Lisp, enable the mode if ARG is omitted or nil."
7442 :global t :group 'mode-line)
7444 (define-minor-mode size-indication-mode
7445 "Toggle buffer size display in the mode line (Size Indication mode).
7446 With a prefix argument ARG, enable Size Indication mode if ARG is
7447 positive, and disable it otherwise.
7449 If called from Lisp, enable the mode if ARG is omitted or nil."
7450 :global t :group 'mode-line)
7452 (define-minor-mode auto-save-mode
7453 "Toggle auto-saving in the current buffer (Auto Save mode).
7454 With a prefix argument ARG, enable Auto Save mode if ARG is
7455 positive, and disable it otherwise.
7457 If called from Lisp, enable the mode if ARG is omitted or nil."
7458 :variable ((and buffer-auto-save-file-name
7459 ;; If auto-save is off because buffer has shrunk,
7460 ;; then toggling should turn it on.
7461 (>= buffer-saved-size 0))
7462 . (lambda (val)
7463 (setq buffer-auto-save-file-name
7464 (cond
7465 ((null val) nil)
7466 ((and buffer-file-name auto-save-visited-file-name
7467 (not buffer-read-only))
7468 buffer-file-name)
7469 (t (make-auto-save-file-name))))))
7470 ;; If -1 was stored here, to temporarily turn off saving,
7471 ;; turn it back on.
7472 (and (< buffer-saved-size 0)
7473 (setq buffer-saved-size 0)))
7475 (defgroup paren-blinking nil
7476 "Blinking matching of parens and expressions."
7477 :prefix "blink-matching-"
7478 :group 'paren-matching)
7480 (defcustom blink-matching-paren t
7481 "Non-nil means show matching open-paren when close-paren is inserted.
7482 If t, highlight the paren. If `jump', briefly move cursor to its
7483 position. If `jump-offscreen', move cursor there even if the
7484 position is off screen. With any other non-nil value, the
7485 off-screen position of the opening paren will be shown in the
7486 echo area."
7487 :type '(choice
7488 (const :tag "Disable" nil)
7489 (const :tag "Highlight" t)
7490 (const :tag "Move cursor" jump)
7491 (const :tag "Move cursor, even if off screen" jump-offscreen))
7492 :group 'paren-blinking)
7494 (defcustom blink-matching-paren-on-screen t
7495 "Non-nil means show matching open-paren when it is on screen.
7496 If nil, don't show it (but the open-paren can still be shown
7497 in the echo area when it is off screen).
7499 This variable has no effect if `blink-matching-paren' is nil.
7500 \(In that case, the open-paren is never shown.)
7501 It is also ignored if `show-paren-mode' is enabled."
7502 :type 'boolean
7503 :group 'paren-blinking)
7505 (defcustom blink-matching-paren-distance (* 100 1024)
7506 "If non-nil, maximum distance to search backwards for matching open-paren.
7507 If nil, search stops at the beginning of the accessible portion of the buffer."
7508 :version "23.2" ; 25->100k
7509 :type '(choice (const nil) integer)
7510 :group 'paren-blinking)
7512 (defcustom blink-matching-delay 1
7513 "Time in seconds to delay after showing a matching paren."
7514 :type 'number
7515 :group 'paren-blinking)
7517 (defcustom blink-matching-paren-dont-ignore-comments nil
7518 "If nil, `blink-matching-paren' ignores comments.
7519 More precisely, when looking for the matching parenthesis,
7520 it skips the contents of comments that end before point."
7521 :type 'boolean
7522 :group 'paren-blinking)
7524 (defun blink-matching-check-mismatch (start end)
7525 "Return whether or not START...END are matching parens.
7526 END is the current point and START is the blink position.
7527 START might be nil if no matching starter was found.
7528 Returns non-nil if we find there is a mismatch."
7529 (let* ((end-syntax (syntax-after (1- end)))
7530 (matching-paren (and (consp end-syntax)
7531 (eq (syntax-class end-syntax) 5)
7532 (cdr end-syntax))))
7533 ;; For self-matched chars like " and $, we can't know when they're
7534 ;; mismatched or unmatched, so we can only do it for parens.
7535 (when matching-paren
7536 (not (and start
7538 (eq (char-after start) matching-paren)
7539 ;; The cdr might hold a new paren-class info rather than
7540 ;; a matching-char info, in which case the two CDRs
7541 ;; should match.
7542 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7544 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7545 "Function to check parentheses mismatches.
7546 The function takes two arguments (START and END) where START is the
7547 position just before the opening token and END is the position right after.
7548 START can be nil, if it was not found.
7549 The function should return non-nil if the two tokens do not match.")
7551 (defvar blink-matching--overlay
7552 (let ((ol (make-overlay (point) (point) nil t)))
7553 (overlay-put ol 'face 'show-paren-match)
7554 (delete-overlay ol)
7556 "Overlay used to highlight the matching paren.")
7558 (defun blink-matching-open ()
7559 "Momentarily highlight the beginning of the sexp before point."
7560 (interactive)
7561 (when (and (not (bobp))
7562 blink-matching-paren)
7563 (let* ((oldpos (point))
7564 (message-log-max nil) ; Don't log messages about paren matching.
7565 (blinkpos
7566 (save-excursion
7567 (save-restriction
7568 (if blink-matching-paren-distance
7569 (narrow-to-region
7570 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7571 (- (point) blink-matching-paren-distance))
7572 oldpos))
7573 (let ((parse-sexp-ignore-comments
7574 (and parse-sexp-ignore-comments
7575 (not blink-matching-paren-dont-ignore-comments))))
7576 (condition-case ()
7577 (progn
7578 (syntax-propertize (point))
7579 (forward-sexp -1)
7580 ;; backward-sexp skips backward over prefix chars,
7581 ;; so move back to the matching paren.
7582 (while (and (< (point) (1- oldpos))
7583 (let ((code (syntax-after (point))))
7584 (or (eq (syntax-class code) 6)
7585 (eq (logand 1048576 (car code))
7586 1048576))))
7587 (forward-char 1))
7588 (point))
7589 (error nil))))))
7590 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7591 (cond
7592 (mismatch
7593 (if blinkpos
7594 (if (minibufferp)
7595 (minibuffer-message "Mismatched parentheses")
7596 (message "Mismatched parentheses"))
7597 (if (minibufferp)
7598 (minibuffer-message "No matching parenthesis found")
7599 (message "No matching parenthesis found"))))
7600 ((not blinkpos) nil)
7601 ((or
7602 (eq blink-matching-paren 'jump-offscreen)
7603 (pos-visible-in-window-p blinkpos))
7604 ;; Matching open within window, temporarily move to or highlight
7605 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7606 ;; is non-nil.
7607 (and blink-matching-paren-on-screen
7608 (not show-paren-mode)
7609 (if (memq blink-matching-paren '(jump jump-offscreen))
7610 (save-excursion
7611 (goto-char blinkpos)
7612 (sit-for blink-matching-delay))
7613 (unwind-protect
7614 (progn
7615 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7616 (current-buffer))
7617 (sit-for blink-matching-delay))
7618 (delete-overlay blink-matching--overlay)))))
7620 (let ((open-paren-line-string
7621 (save-excursion
7622 (goto-char blinkpos)
7623 ;; Show what precedes the open in its line, if anything.
7624 (cond
7625 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7626 (buffer-substring (line-beginning-position)
7627 (1+ blinkpos)))
7628 ;; Show what follows the open in its line, if anything.
7629 ((save-excursion
7630 (forward-char 1)
7631 (skip-chars-forward " \t")
7632 (not (eolp)))
7633 (buffer-substring blinkpos
7634 (line-end-position)))
7635 ;; Otherwise show the previous nonblank line,
7636 ;; if there is one.
7637 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7638 (concat
7639 (buffer-substring (progn
7640 (skip-chars-backward "\n \t")
7641 (line-beginning-position))
7642 (progn (end-of-line)
7643 (skip-chars-backward " \t")
7644 (point)))
7645 ;; Replace the newline and other whitespace with `...'.
7646 "..."
7647 (buffer-substring blinkpos (1+ blinkpos))))
7648 ;; There is nothing to show except the char itself.
7649 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7650 (minibuffer-message
7651 "Matches %s"
7652 (substring-no-properties open-paren-line-string))))))))
7654 (defvar blink-paren-function 'blink-matching-open
7655 "Function called, if non-nil, whenever a close parenthesis is inserted.
7656 More precisely, a char with closeparen syntax is self-inserted.")
7658 (defun blink-paren-post-self-insert-function ()
7659 (when (and (eq (char-before) last-command-event) ; Sanity check.
7660 (memq (char-syntax last-command-event) '(?\) ?\$))
7661 blink-paren-function
7662 (not executing-kbd-macro)
7663 (not noninteractive)
7664 ;; Verify an even number of quoting characters precede the close.
7665 ;; FIXME: Also check if this parenthesis closes a comment as
7666 ;; can happen in Pascal and SML.
7667 (= 1 (logand 1 (- (point)
7668 (save-excursion
7669 (forward-char -1)
7670 (skip-syntax-backward "/\\")
7671 (point))))))
7672 (funcall blink-paren-function)))
7674 (put 'blink-paren-post-self-insert-function 'priority 100)
7676 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7677 ;; Most likely, this hook is nil, so this arg doesn't matter,
7678 ;; but I use it as a reminder that this function usually
7679 ;; likes to be run after others since it does
7680 ;; `sit-for'. That's also the reason it get a `priority' prop
7681 ;; of 100.
7682 'append)
7684 ;; This executes C-g typed while Emacs is waiting for a command.
7685 ;; Quitting out of a program does not go through here;
7686 ;; that happens in the maybe_quit function at the C code level.
7687 (defun keyboard-quit ()
7688 "Signal a `quit' condition.
7689 During execution of Lisp code, this character causes a quit directly.
7690 At top-level, as an editor command, this simply beeps."
7691 (interactive)
7692 ;; Avoid adding the region to the window selection.
7693 (setq saved-region-selection nil)
7694 (let (select-active-regions)
7695 (deactivate-mark))
7696 (if (fboundp 'kmacro-keyboard-quit)
7697 (kmacro-keyboard-quit))
7698 (when completion-in-region-mode
7699 (completion-in-region-mode -1))
7700 ;; Force the next redisplay cycle to remove the "Def" indicator from
7701 ;; all the mode lines.
7702 (if defining-kbd-macro
7703 (force-mode-line-update t))
7704 (setq defining-kbd-macro nil)
7705 (let ((debug-on-quit nil))
7706 (signal 'quit nil)))
7708 (defvar buffer-quit-function nil
7709 "Function to call to \"quit\" the current buffer, or nil if none.
7710 \\[keyboard-escape-quit] calls this function when its more local actions
7711 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7713 (defun keyboard-escape-quit ()
7714 "Exit the current \"mode\" (in a generalized sense of the word).
7715 This command can exit an interactive command such as `query-replace',
7716 can clear out a prefix argument or a region,
7717 can get out of the minibuffer or other recursive edit,
7718 cancel the use of the current buffer (for special-purpose buffers),
7719 or go back to just one window (by deleting all but the selected window)."
7720 (interactive)
7721 (cond ((eq last-command 'mode-exited) nil)
7722 ((region-active-p)
7723 (deactivate-mark))
7724 ((> (minibuffer-depth) 0)
7725 (abort-recursive-edit))
7726 (current-prefix-arg
7727 nil)
7728 ((> (recursion-depth) 0)
7729 (exit-recursive-edit))
7730 (buffer-quit-function
7731 (funcall buffer-quit-function))
7732 ((not (one-window-p t))
7733 (delete-other-windows))
7734 ((string-match "^ \\*" (buffer-name (current-buffer)))
7735 (bury-buffer))))
7737 (defun play-sound-file (file &optional volume device)
7738 "Play sound stored in FILE.
7739 VOLUME and DEVICE correspond to the keywords of the sound
7740 specification for `play-sound'."
7741 (interactive "fPlay sound file: ")
7742 (let ((sound (list :file file)))
7743 (if volume
7744 (plist-put sound :volume volume))
7745 (if device
7746 (plist-put sound :device device))
7747 (push 'sound sound)
7748 (play-sound sound)))
7751 (defcustom read-mail-command 'rmail
7752 "Your preference for a mail reading package.
7753 This is used by some keybindings which support reading mail.
7754 See also `mail-user-agent' concerning sending mail."
7755 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7756 (function-item :tag "Gnus" :format "%t\n" gnus)
7757 (function-item :tag "Emacs interface to MH"
7758 :format "%t\n" mh-rmail)
7759 (function :tag "Other"))
7760 :version "21.1"
7761 :group 'mail)
7763 (defcustom mail-user-agent 'message-user-agent
7764 "Your preference for a mail composition package.
7765 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7766 outgoing email message. This variable lets you specify which
7767 mail-sending package you prefer.
7769 Valid values include:
7771 `message-user-agent' -- use the Message package.
7772 See Info node `(message)'.
7773 `sendmail-user-agent' -- use the Mail package.
7774 See Info node `(emacs)Sending Mail'.
7775 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7776 See Info node `(mh-e)'.
7777 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7778 paraphernalia if Gnus is running, particularly
7779 the Gcc: header for archiving.
7781 Additional valid symbols may be available; check with the author of
7782 your package for details. The function should return non-nil if it
7783 succeeds.
7785 See also `read-mail-command' concerning reading mail."
7786 :type '(radio (function-item :tag "Message package"
7787 :format "%t\n"
7788 message-user-agent)
7789 (function-item :tag "Mail package"
7790 :format "%t\n"
7791 sendmail-user-agent)
7792 (function-item :tag "Emacs interface to MH"
7793 :format "%t\n"
7794 mh-e-user-agent)
7795 (function-item :tag "Message with full Gnus features"
7796 :format "%t\n"
7797 gnus-user-agent)
7798 (function :tag "Other"))
7799 :version "23.2" ; sendmail->message
7800 :group 'mail)
7802 (defcustom compose-mail-user-agent-warnings t
7803 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7804 If the value of `mail-user-agent' is the default, and the user
7805 appears to have customizations applying to the old default,
7806 `compose-mail' issues a warning."
7807 :type 'boolean
7808 :version "23.2"
7809 :group 'mail)
7811 (defun rfc822-goto-eoh ()
7812 "If the buffer starts with a mail header, move point to the header's end.
7813 Otherwise, moves to `point-min'.
7814 The end of the header is the start of the next line, if there is one,
7815 else the end of the last line. This function obeys RFC822."
7816 (goto-char (point-min))
7817 (when (re-search-forward
7818 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7819 (goto-char (match-beginning 0))))
7821 ;; Used by Rmail (e.g., rmail-forward).
7822 (defvar mail-encode-mml nil
7823 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7824 the outgoing message before sending it.")
7826 (defun compose-mail (&optional to subject other-headers continue
7827 switch-function yank-action send-actions
7828 return-action)
7829 "Start composing a mail message to send.
7830 This uses the user's chosen mail composition package
7831 as selected with the variable `mail-user-agent'.
7832 The optional arguments TO and SUBJECT specify recipients
7833 and the initial Subject field, respectively.
7835 OTHER-HEADERS is an alist specifying additional
7836 header fields. Elements look like (HEADER . VALUE) where both
7837 HEADER and VALUE are strings.
7839 CONTINUE, if non-nil, says to continue editing a message already
7840 being composed. Interactively, CONTINUE is the prefix argument.
7842 SWITCH-FUNCTION, if non-nil, is a function to use to
7843 switch to and display the buffer used for mail composition.
7845 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7846 to insert the raw text of the message being replied to.
7847 It has the form (FUNCTION . ARGS). The user agent will apply
7848 FUNCTION to ARGS, to insert the raw text of the original message.
7849 \(The user agent will also run `mail-citation-hook', *after* the
7850 original text has been inserted in this way.)
7852 SEND-ACTIONS is a list of actions to call when the message is sent.
7853 Each action has the form (FUNCTION . ARGS).
7855 RETURN-ACTION, if non-nil, is an action for returning to the
7856 caller. It has the form (FUNCTION . ARGS). The function is
7857 called after the mail has been sent or put aside, and the mail
7858 buffer buried."
7859 (interactive
7860 (list nil nil nil current-prefix-arg))
7862 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7863 ;; from sendmail-user-agent to message-user-agent. Some users may
7864 ;; encounter incompatibilities. This hack tries to detect problems
7865 ;; and warn about them.
7866 (and compose-mail-user-agent-warnings
7867 (eq mail-user-agent 'message-user-agent)
7868 (let (warn-vars)
7869 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7870 mail-yank-hooks mail-archive-file-name
7871 mail-default-reply-to mail-mailing-lists
7872 mail-self-blind))
7873 (and (boundp var)
7874 (symbol-value var)
7875 (push var warn-vars)))
7876 (when warn-vars
7877 (display-warning 'mail
7878 (format-message "\
7879 The default mail mode is now Message mode.
7880 You have the following Mail mode variable%s customized:
7881 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7882 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7883 (if (> (length warn-vars) 1) "s" "")
7884 (mapconcat 'symbol-name
7885 warn-vars " "))))))
7887 (let ((function (get mail-user-agent 'composefunc)))
7888 (funcall function to subject other-headers continue switch-function
7889 yank-action send-actions return-action)))
7891 (defun compose-mail-other-window (&optional to subject other-headers continue
7892 yank-action send-actions
7893 return-action)
7894 "Like \\[compose-mail], but edit the outgoing message in another window."
7895 (interactive (list nil nil nil current-prefix-arg))
7896 (compose-mail to subject other-headers continue
7897 'switch-to-buffer-other-window yank-action send-actions
7898 return-action))
7900 (defun compose-mail-other-frame (&optional to subject other-headers continue
7901 yank-action send-actions
7902 return-action)
7903 "Like \\[compose-mail], but edit the outgoing message in another frame."
7904 (interactive (list nil nil nil current-prefix-arg))
7905 (compose-mail to subject other-headers continue
7906 'switch-to-buffer-other-frame yank-action send-actions
7907 return-action))
7910 (defvar set-variable-value-history nil
7911 "History of values entered with `set-variable'.
7913 Maximum length of the history list is determined by the value
7914 of `history-length', which see.")
7916 (defun set-variable (variable value &optional make-local)
7917 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7918 VARIABLE should be a user option variable name, a Lisp variable
7919 meant to be customized by users. You should enter VALUE in Lisp syntax,
7920 so if you want VALUE to be a string, you must surround it with doublequotes.
7921 VALUE is used literally, not evaluated.
7923 If VARIABLE has a `variable-interactive' property, that is used as if
7924 it were the arg to `interactive' (which see) to interactively read VALUE.
7926 If VARIABLE has been defined with `defcustom', then the type information
7927 in the definition is used to check that VALUE is valid.
7929 Note that this function is at heart equivalent to the basic `set' function.
7930 For a variable defined with `defcustom', it does not pay attention to
7931 any :set property that the variable might have (if you want that, use
7932 \\[customize-set-variable] instead).
7934 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7935 (interactive
7936 (let* ((default-var (variable-at-point))
7937 (var (if (custom-variable-p default-var)
7938 (read-variable (format "Set variable (default %s): " default-var)
7939 default-var)
7940 (read-variable "Set variable: ")))
7941 (minibuffer-help-form '(describe-variable var))
7942 (prop (get var 'variable-interactive))
7943 (obsolete (car (get var 'byte-obsolete-variable)))
7944 (prompt (format "Set %s %s to value: " var
7945 (cond ((local-variable-p var)
7946 "(buffer-local)")
7947 ((or current-prefix-arg
7948 (local-variable-if-set-p var))
7949 "buffer-locally")
7950 (t "globally"))))
7951 (val (progn
7952 (when obsolete
7953 (message (concat "`%S' is obsolete; "
7954 (if (symbolp obsolete) "use `%S' instead" "%s"))
7955 var obsolete)
7956 (sit-for 3))
7957 (if prop
7958 ;; Use VAR's `variable-interactive' property
7959 ;; as an interactive spec for prompting.
7960 (call-interactively `(lambda (arg)
7961 (interactive ,prop)
7962 arg))
7963 (read-from-minibuffer prompt nil
7964 read-expression-map t
7965 'set-variable-value-history
7966 (format "%S" (symbol-value var)))))))
7967 (list var val current-prefix-arg)))
7969 (and (custom-variable-p variable)
7970 (not (get variable 'custom-type))
7971 (custom-load-symbol variable))
7972 (let ((type (get variable 'custom-type)))
7973 (when type
7974 ;; Match with custom type.
7975 (require 'cus-edit)
7976 (setq type (widget-convert type))
7977 (unless (widget-apply type :match value)
7978 (user-error "Value `%S' does not match type %S of %S"
7979 value (car type) variable))))
7981 (if make-local
7982 (make-local-variable variable))
7984 (set variable value)
7986 ;; Force a thorough redisplay for the case that the variable
7987 ;; has an effect on the display, like `tab-width' has.
7988 (force-mode-line-update))
7990 ;; Define the major mode for lists of completions.
7992 (defvar completion-list-mode-map
7993 (let ((map (make-sparse-keymap)))
7994 (define-key map [mouse-2] 'choose-completion)
7995 (define-key map [follow-link] 'mouse-face)
7996 (define-key map [down-mouse-2] nil)
7997 (define-key map "\C-m" 'choose-completion)
7998 (define-key map "\e\e\e" 'delete-completion-window)
7999 (define-key map [left] 'previous-completion)
8000 (define-key map [right] 'next-completion)
8001 (define-key map [?\t] 'next-completion)
8002 (define-key map [backtab] 'previous-completion)
8003 (define-key map "q" 'quit-window)
8004 (define-key map "z" 'kill-current-buffer)
8005 map)
8006 "Local map for completion list buffers.")
8008 ;; Completion mode is suitable only for specially formatted data.
8009 (put 'completion-list-mode 'mode-class 'special)
8011 (defvar completion-reference-buffer nil
8012 "Record the buffer that was current when the completion list was requested.
8013 This is a local variable in the completion list buffer.
8014 Initial value is nil to avoid some compiler warnings.")
8016 (defvar completion-no-auto-exit nil
8017 "Non-nil means `choose-completion-string' should never exit the minibuffer.
8018 This also applies to other functions such as `choose-completion'.")
8020 (defvar completion-base-position nil
8021 "Position of the base of the text corresponding to the shown completions.
8022 This variable is used in the *Completions* buffers.
8023 Its value is a list of the form (START END) where START is the place
8024 where the completion should be inserted and END (if non-nil) is the end
8025 of the text to replace. If END is nil, point is used instead.")
8027 (defvar completion-list-insert-choice-function #'completion--replace
8028 "Function to use to insert the text chosen in *Completions*.
8029 Called with three arguments (BEG END TEXT), it should replace the text
8030 between BEG and END with TEXT. Expected to be set buffer-locally
8031 in the *Completions* buffer.")
8033 (defvar completion-base-size nil
8034 "Number of chars before point not involved in completion.
8035 This is a local variable in the completion list buffer.
8036 It refers to the chars in the minibuffer if completing in the
8037 minibuffer, or in `completion-reference-buffer' otherwise.
8038 Only characters in the field at point are included.
8040 If nil, Emacs determines which part of the tail end of the
8041 buffer's text is involved in completion by comparing the text
8042 directly.")
8043 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
8045 (defun delete-completion-window ()
8046 "Delete the completion list window.
8047 Go to the window from which completion was requested."
8048 (interactive)
8049 (let ((buf completion-reference-buffer))
8050 (if (one-window-p t)
8051 (if (window-dedicated-p) (delete-frame))
8052 (delete-window (selected-window))
8053 (if (get-buffer-window buf)
8054 (select-window (get-buffer-window buf))))))
8056 (defun previous-completion (n)
8057 "Move to the previous item in the completion list."
8058 (interactive "p")
8059 (next-completion (- n)))
8061 (defun next-completion (n)
8062 "Move to the next item in the completion list.
8063 With prefix argument N, move N items (negative N means move backward)."
8064 (interactive "p")
8065 (let ((beg (point-min)) (end (point-max)))
8066 (while (and (> n 0) (not (eobp)))
8067 ;; If in a completion, move to the end of it.
8068 (when (get-text-property (point) 'mouse-face)
8069 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8070 ;; Move to start of next one.
8071 (unless (get-text-property (point) 'mouse-face)
8072 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8073 (setq n (1- n)))
8074 (while (and (< n 0) (not (bobp)))
8075 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
8076 ;; If in a completion, move to the start of it.
8077 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
8078 (goto-char (previous-single-property-change
8079 (point) 'mouse-face nil beg)))
8080 ;; Move to end of the previous completion.
8081 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
8082 (goto-char (previous-single-property-change
8083 (point) 'mouse-face nil beg)))
8084 ;; Move to the start of that one.
8085 (goto-char (previous-single-property-change
8086 (point) 'mouse-face nil beg))
8087 (setq n (1+ n))))))
8089 (defun choose-completion (&optional event)
8090 "Choose the completion at point.
8091 If EVENT, use EVENT's position to determine the starting position."
8092 (interactive (list last-nonmenu-event))
8093 ;; In case this is run via the mouse, give temporary modes such as
8094 ;; isearch a chance to turn off.
8095 (run-hooks 'mouse-leave-buffer-hook)
8096 (with-current-buffer (window-buffer (posn-window (event-start event)))
8097 (let ((buffer completion-reference-buffer)
8098 (base-size completion-base-size)
8099 (base-position completion-base-position)
8100 (insert-function completion-list-insert-choice-function)
8101 (choice
8102 (save-excursion
8103 (goto-char (posn-point (event-start event)))
8104 (let (beg end)
8105 (cond
8106 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
8107 (setq end (point) beg (1+ (point))))
8108 ((and (not (bobp))
8109 (get-text-property (1- (point)) 'mouse-face))
8110 (setq end (1- (point)) beg (point)))
8111 (t (error "No completion here")))
8112 (setq beg (previous-single-property-change beg 'mouse-face))
8113 (setq end (or (next-single-property-change end 'mouse-face)
8114 (point-max)))
8115 (buffer-substring-no-properties beg end)))))
8117 (unless (buffer-live-p buffer)
8118 (error "Destination buffer is dead"))
8119 (quit-window nil (posn-window (event-start event)))
8121 (with-current-buffer buffer
8122 (choose-completion-string
8123 choice buffer
8124 (or base-position
8125 (when base-size
8126 ;; Someone's using old completion code that doesn't know
8127 ;; about base-position yet.
8128 (list (+ base-size (field-beginning))))
8129 ;; If all else fails, just guess.
8130 (list (choose-completion-guess-base-position choice)))
8131 insert-function)))))
8133 ;; Delete the longest partial match for STRING
8134 ;; that can be found before POINT.
8135 (defun choose-completion-guess-base-position (string)
8136 (save-excursion
8137 (let ((opoint (point))
8138 len)
8139 ;; Try moving back by the length of the string.
8140 (goto-char (max (- (point) (length string))
8141 (minibuffer-prompt-end)))
8142 ;; See how far back we were actually able to move. That is the
8143 ;; upper bound on how much we can match and delete.
8144 (setq len (- opoint (point)))
8145 (if completion-ignore-case
8146 (setq string (downcase string)))
8147 (while (and (> len 0)
8148 (let ((tail (buffer-substring (point) opoint)))
8149 (if completion-ignore-case
8150 (setq tail (downcase tail)))
8151 (not (string= tail (substring string 0 len)))))
8152 (setq len (1- len))
8153 (forward-char 1))
8154 (point))))
8156 (defun choose-completion-delete-max-match (string)
8157 (declare (obsolete choose-completion-guess-base-position "23.2"))
8158 (delete-region (choose-completion-guess-base-position string) (point)))
8160 (defvar choose-completion-string-functions nil
8161 "Functions that may override the normal insertion of a completion choice.
8162 These functions are called in order with three arguments:
8163 CHOICE - the string to insert in the buffer,
8164 BUFFER - the buffer in which the choice should be inserted,
8165 BASE-POSITION - where to insert the completion.
8167 If a function in the list returns non-nil, that function is supposed
8168 to have inserted the CHOICE in the BUFFER, and possibly exited
8169 the minibuffer; no further functions will be called.
8171 If all functions in the list return nil, that means to use
8172 the default method of inserting the completion in BUFFER.")
8174 (defun choose-completion-string (choice &optional
8175 buffer base-position insert-function)
8176 "Switch to BUFFER and insert the completion choice CHOICE.
8177 BASE-POSITION says where to insert the completion.
8178 INSERT-FUNCTION says how to insert the completion and falls
8179 back on `completion-list-insert-choice-function' when nil."
8181 ;; If BUFFER is the minibuffer, exit the minibuffer
8182 ;; unless it is reading a file name and CHOICE is a directory,
8183 ;; or completion-no-auto-exit is non-nil.
8185 ;; Some older code may call us passing `base-size' instead of
8186 ;; `base-position'. It's difficult to make any use of `base-size',
8187 ;; so we just ignore it.
8188 (unless (consp base-position)
8189 (message "Obsolete `base-size' passed to choose-completion-string")
8190 (setq base-position nil))
8192 (let* ((buffer (or buffer completion-reference-buffer))
8193 (mini-p (minibufferp buffer)))
8194 ;; If BUFFER is a minibuffer, barf unless it's the currently
8195 ;; active minibuffer.
8196 (if (and mini-p
8197 (not (and (active-minibuffer-window)
8198 (equal buffer
8199 (window-buffer (active-minibuffer-window))))))
8200 (error "Minibuffer is not active for completion")
8201 ;; Set buffer so buffer-local choose-completion-string-functions works.
8202 (set-buffer buffer)
8203 (unless (run-hook-with-args-until-success
8204 'choose-completion-string-functions
8205 ;; The fourth arg used to be `mini-p' but was useless
8206 ;; (since minibufferp can be used on the `buffer' arg)
8207 ;; and indeed unused. The last used to be `base-size', so we
8208 ;; keep it to try and avoid breaking old code.
8209 choice buffer base-position nil)
8210 ;; This remove-text-properties should be unnecessary since `choice'
8211 ;; comes from buffer-substring-no-properties.
8212 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8213 ;; Insert the completion into the buffer where it was requested.
8214 (funcall (or insert-function completion-list-insert-choice-function)
8215 (or (car base-position) (point))
8216 (or (cadr base-position) (point))
8217 choice)
8218 ;; Update point in the window that BUFFER is showing in.
8219 (let ((window (get-buffer-window buffer t)))
8220 (set-window-point window (point)))
8221 ;; If completing for the minibuffer, exit it with this choice.
8222 (and (not completion-no-auto-exit)
8223 (minibufferp buffer)
8224 minibuffer-completion-table
8225 ;; If this is reading a file name, and the file name chosen
8226 ;; is a directory, don't exit the minibuffer.
8227 (let* ((result (buffer-substring (field-beginning) (point)))
8228 (bounds
8229 (completion-boundaries result minibuffer-completion-table
8230 minibuffer-completion-predicate
8231 "")))
8232 (if (eq (car bounds) (length result))
8233 ;; The completion chosen leads to a new set of completions
8234 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8235 (let ((mini (active-minibuffer-window)))
8236 (select-window mini)
8237 (when minibuffer-auto-raise
8238 (raise-frame (window-frame mini))))
8239 (exit-minibuffer))))))))
8241 (define-derived-mode completion-list-mode nil "Completion List"
8242 "Major mode for buffers showing lists of possible completions.
8243 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8244 to select the completion near point.
8245 Or click to select one with the mouse.
8247 \\{completion-list-mode-map}"
8248 (set (make-local-variable 'completion-base-size) nil))
8250 (defun completion-list-mode-finish ()
8251 "Finish setup of the completions buffer.
8252 Called from `temp-buffer-show-hook'."
8253 (when (eq major-mode 'completion-list-mode)
8254 (setq buffer-read-only t)))
8256 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8259 ;; Variables and faces used in `completion-setup-function'.
8261 (defcustom completion-show-help t
8262 "Non-nil means show help message in *Completions* buffer."
8263 :type 'boolean
8264 :version "22.1"
8265 :group 'completion)
8267 ;; This function goes in completion-setup-hook, so that it is called
8268 ;; after the text of the completion list buffer is written.
8269 (defun completion-setup-function ()
8270 (let* ((mainbuf (current-buffer))
8271 (base-dir
8272 ;; FIXME: This is a bad hack. We try to set the default-directory
8273 ;; in the *Completions* buffer so that the relative file names
8274 ;; displayed there can be treated as valid file names, independently
8275 ;; from the completion context. But this suffers from many problems:
8276 ;; - It's not clear when the completions are file names. With some
8277 ;; completion tables (e.g. bzr revision specs), the listed
8278 ;; completions can mix file names and other things.
8279 ;; - It doesn't pay attention to possible quoting.
8280 ;; - With fancy completion styles, the code below will not always
8281 ;; find the right base directory.
8282 (if minibuffer-completing-file-name
8283 (file-name-as-directory
8284 (expand-file-name
8285 (buffer-substring (minibuffer-prompt-end)
8286 (- (point) (or completion-base-size 0))))))))
8287 (with-current-buffer standard-output
8288 (let ((base-size completion-base-size) ;Read before killing localvars.
8289 (base-position completion-base-position)
8290 (insert-fun completion-list-insert-choice-function))
8291 (completion-list-mode)
8292 (set (make-local-variable 'completion-base-size) base-size)
8293 (set (make-local-variable 'completion-base-position) base-position)
8294 (set (make-local-variable 'completion-list-insert-choice-function)
8295 insert-fun))
8296 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8297 (if base-dir (setq default-directory base-dir))
8298 ;; Maybe insert help string.
8299 (when completion-show-help
8300 (goto-char (point-min))
8301 (if (display-mouse-p)
8302 (insert "Click on a completion to select it.\n"))
8303 (insert (substitute-command-keys
8304 "In this buffer, type \\[choose-completion] to \
8305 select the completion near point.\n\n"))))))
8307 (add-hook 'completion-setup-hook 'completion-setup-function)
8309 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8310 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8312 (defun switch-to-completions ()
8313 "Select the completion list window."
8314 (interactive)
8315 (let ((window (or (get-buffer-window "*Completions*" 0)
8316 ;; Make sure we have a completions window.
8317 (progn (minibuffer-completion-help)
8318 (get-buffer-window "*Completions*" 0)))))
8319 (when window
8320 (select-window window)
8321 ;; In the new buffer, go to the first completion.
8322 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8323 (when (bobp)
8324 (next-completion 1)))))
8326 ;;; Support keyboard commands to turn on various modifiers.
8328 ;; These functions -- which are not commands -- each add one modifier
8329 ;; to the following event.
8331 (defun event-apply-alt-modifier (_ignore-prompt)
8332 "\\<function-key-map>Add the Alt modifier to the following event.
8333 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8334 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8335 (defun event-apply-super-modifier (_ignore-prompt)
8336 "\\<function-key-map>Add the Super modifier to the following event.
8337 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8338 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8339 (defun event-apply-hyper-modifier (_ignore-prompt)
8340 "\\<function-key-map>Add the Hyper modifier to the following event.
8341 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8342 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8343 (defun event-apply-shift-modifier (_ignore-prompt)
8344 "\\<function-key-map>Add the Shift modifier to the following event.
8345 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8346 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8347 (defun event-apply-control-modifier (_ignore-prompt)
8348 "\\<function-key-map>Add the Ctrl modifier to the following event.
8349 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8350 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8351 (defun event-apply-meta-modifier (_ignore-prompt)
8352 "\\<function-key-map>Add the Meta modifier to the following event.
8353 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8354 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8356 (defun event-apply-modifier (event symbol lshiftby prefix)
8357 "Apply a modifier flag to event EVENT.
8358 SYMBOL is the name of this modifier, as a symbol.
8359 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8360 PREFIX is the string that represents this modifier in an event type symbol."
8361 (if (numberp event)
8362 (cond ((eq symbol 'control)
8363 (if (and (<= (downcase event) ?z)
8364 (>= (downcase event) ?a))
8365 (- (downcase event) ?a -1)
8366 (if (and (<= (downcase event) ?Z)
8367 (>= (downcase event) ?A))
8368 (- (downcase event) ?A -1)
8369 (logior (lsh 1 lshiftby) event))))
8370 ((eq symbol 'shift)
8371 (if (and (<= (downcase event) ?z)
8372 (>= (downcase event) ?a))
8373 (upcase event)
8374 (logior (lsh 1 lshiftby) event)))
8376 (logior (lsh 1 lshiftby) event)))
8377 (if (memq symbol (event-modifiers event))
8378 event
8379 (let ((event-type (if (symbolp event) event (car event))))
8380 (setq event-type (intern (concat prefix (symbol-name event-type))))
8381 (if (symbolp event)
8382 event-type
8383 (cons event-type (cdr event)))))))
8385 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8386 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8387 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8388 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8389 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8390 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8392 ;;;; Keypad support.
8394 ;; Make the keypad keys act like ordinary typing keys. If people add
8395 ;; bindings for the function key symbols, then those bindings will
8396 ;; override these, so this shouldn't interfere with any existing
8397 ;; bindings.
8399 ;; Also tell read-char how to handle these keys.
8400 (mapc
8401 (lambda (keypad-normal)
8402 (let ((keypad (nth 0 keypad-normal))
8403 (normal (nth 1 keypad-normal)))
8404 (put keypad 'ascii-character normal)
8405 (define-key function-key-map (vector keypad) (vector normal))))
8406 ;; See also kp-keys bound in bindings.el.
8407 '((kp-space ?\s)
8408 (kp-tab ?\t)
8409 (kp-enter ?\r)
8410 (kp-separator ?,)
8411 (kp-equal ?=)
8412 ;; Do the same for various keys that are represented as symbols under
8413 ;; GUIs but naturally correspond to characters.
8414 (backspace 127)
8415 (delete 127)
8416 (tab ?\t)
8417 (linefeed ?\n)
8418 (clear ?\C-l)
8419 (return ?\C-m)
8420 (escape ?\e)
8423 ;;;;
8424 ;;;; forking a twin copy of a buffer.
8425 ;;;;
8427 (defvar clone-buffer-hook nil
8428 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8430 (defvar clone-indirect-buffer-hook nil
8431 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8433 (defun clone-process (process &optional newname)
8434 "Create a twin copy of PROCESS.
8435 If NEWNAME is nil, it defaults to PROCESS' name;
8436 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8437 If PROCESS is associated with a buffer, the new process will be associated
8438 with the current buffer instead.
8439 Returns nil if PROCESS has already terminated."
8440 (setq newname (or newname (process-name process)))
8441 (if (string-match "<[0-9]+>\\'" newname)
8442 (setq newname (substring newname 0 (match-beginning 0))))
8443 (when (memq (process-status process) '(run stop open))
8444 (let* ((process-connection-type (process-tty-name process))
8445 (new-process
8446 (if (memq (process-status process) '(open))
8447 (let ((args (process-contact process t)))
8448 (setq args (plist-put args :name newname))
8449 (setq args (plist-put args :buffer
8450 (if (process-buffer process)
8451 (current-buffer))))
8452 (apply 'make-network-process args))
8453 (apply 'start-process newname
8454 (if (process-buffer process) (current-buffer))
8455 (process-command process)))))
8456 (set-process-query-on-exit-flag
8457 new-process (process-query-on-exit-flag process))
8458 (set-process-inherit-coding-system-flag
8459 new-process (process-inherit-coding-system-flag process))
8460 (set-process-filter new-process (process-filter process))
8461 (set-process-sentinel new-process (process-sentinel process))
8462 (set-process-plist new-process (copy-sequence (process-plist process)))
8463 new-process)))
8465 ;; things to maybe add (currently partly covered by `funcall mode'):
8466 ;; - syntax-table
8467 ;; - overlays
8468 (defun clone-buffer (&optional newname display-flag)
8469 "Create and return a twin copy of the current buffer.
8470 Unlike an indirect buffer, the new buffer can be edited
8471 independently of the old one (if it is not read-only).
8472 NEWNAME is the name of the new buffer. It may be modified by
8473 adding or incrementing <N> at the end as necessary to create a
8474 unique buffer name. If nil, it defaults to the name of the
8475 current buffer, with the proper suffix. If DISPLAY-FLAG is
8476 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8477 clone a file-visiting buffer, or a buffer whose major mode symbol
8478 has a non-nil `no-clone' property, results in an error.
8480 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8481 current buffer with appropriate suffix. However, if a prefix
8482 argument is given, then the command prompts for NEWNAME in the
8483 minibuffer.
8485 This runs the normal hook `clone-buffer-hook' in the new buffer
8486 after it has been set up properly in other respects."
8487 (interactive
8488 (progn
8489 (if buffer-file-name
8490 (error "Cannot clone a file-visiting buffer"))
8491 (if (get major-mode 'no-clone)
8492 (error "Cannot clone a buffer in %s mode" mode-name))
8493 (list (if current-prefix-arg
8494 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8495 t)))
8496 (if buffer-file-name
8497 (error "Cannot clone a file-visiting buffer"))
8498 (if (get major-mode 'no-clone)
8499 (error "Cannot clone a buffer in %s mode" mode-name))
8500 (setq newname (or newname (buffer-name)))
8501 (if (string-match "<[0-9]+>\\'" newname)
8502 (setq newname (substring newname 0 (match-beginning 0))))
8503 (let ((buf (current-buffer))
8504 (ptmin (point-min))
8505 (ptmax (point-max))
8506 (pt (point))
8507 (mk (if mark-active (mark t)))
8508 (modified (buffer-modified-p))
8509 (mode major-mode)
8510 (lvars (buffer-local-variables))
8511 (process (get-buffer-process (current-buffer)))
8512 (new (generate-new-buffer (or newname (buffer-name)))))
8513 (save-restriction
8514 (widen)
8515 (with-current-buffer new
8516 (insert-buffer-substring buf)))
8517 (with-current-buffer new
8518 (narrow-to-region ptmin ptmax)
8519 (goto-char pt)
8520 (if mk (set-mark mk))
8521 (set-buffer-modified-p modified)
8523 ;; Clone the old buffer's process, if any.
8524 (when process (clone-process process))
8526 ;; Now set up the major mode.
8527 (funcall mode)
8529 ;; Set up other local variables.
8530 (mapc (lambda (v)
8531 (condition-case () ;in case var is read-only
8532 (if (symbolp v)
8533 (makunbound v)
8534 (set (make-local-variable (car v)) (cdr v)))
8535 (error nil)))
8536 lvars)
8538 ;; Run any hooks (typically set up by the major mode
8539 ;; for cloning to work properly).
8540 (run-hooks 'clone-buffer-hook))
8541 (if display-flag
8542 ;; Presumably the current buffer is shown in the selected frame, so
8543 ;; we want to display the clone elsewhere.
8544 (let ((same-window-regexps nil)
8545 (same-window-buffer-names))
8546 (pop-to-buffer new)))
8547 new))
8550 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8551 "Create an indirect buffer that is a twin copy of the current buffer.
8553 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8554 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8555 or if not called with a prefix arg, NEWNAME defaults to the current
8556 buffer's name. The name is modified by adding a `<N>' suffix to it
8557 or by incrementing the N in an existing suffix. Trying to clone a
8558 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8559 property results in an error.
8561 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8562 This is always done when called interactively.
8564 Optional third arg NORECORD non-nil means do not put this buffer at the
8565 front of the list of recently selected ones.
8567 Returns the newly created indirect buffer."
8568 (interactive
8569 (progn
8570 (if (get major-mode 'no-clone-indirect)
8571 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8572 (list (if current-prefix-arg
8573 (read-buffer "Name of indirect buffer: " (current-buffer)))
8574 t)))
8575 (if (get major-mode 'no-clone-indirect)
8576 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8577 (setq newname (or newname (buffer-name)))
8578 (if (string-match "<[0-9]+>\\'" newname)
8579 (setq newname (substring newname 0 (match-beginning 0))))
8580 (let* ((name (generate-new-buffer-name newname))
8581 (buffer (make-indirect-buffer (current-buffer) name t)))
8582 (with-current-buffer buffer
8583 (run-hooks 'clone-indirect-buffer-hook))
8584 (when display-flag
8585 (pop-to-buffer buffer nil norecord))
8586 buffer))
8589 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8590 "Like `clone-indirect-buffer' but display in another window."
8591 (interactive
8592 (progn
8593 (if (get major-mode 'no-clone-indirect)
8594 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8595 (list (if current-prefix-arg
8596 (read-buffer "Name of indirect buffer: " (current-buffer)))
8597 t)))
8598 (let ((pop-up-windows t))
8599 (clone-indirect-buffer newname display-flag norecord)))
8602 ;;; Handling of Backspace and Delete keys.
8604 (defcustom normal-erase-is-backspace 'maybe
8605 "Set the default behavior of the Delete and Backspace keys.
8607 If set to t, Delete key deletes forward and Backspace key deletes
8608 backward.
8610 If set to nil, both Delete and Backspace keys delete backward.
8612 If set to `maybe' (which is the default), Emacs automatically
8613 selects a behavior. On window systems, the behavior depends on
8614 the keyboard used. If the keyboard has both a Backspace key and
8615 a Delete key, and both are mapped to their usual meanings, the
8616 option's default value is set to t, so that Backspace can be used
8617 to delete backward, and Delete can be used to delete forward.
8619 If not running under a window system, customizing this option
8620 accomplishes a similar effect by mapping C-h, which is usually
8621 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8622 via `keyboard-translate'. The former functionality of C-h is
8623 available on the F1 key. You should probably not use this
8624 setting if you don't have both Backspace, Delete and F1 keys.
8626 Setting this variable with setq doesn't take effect. Programmatically,
8627 call `normal-erase-is-backspace-mode' (which see) instead."
8628 :type '(choice (const :tag "Off" nil)
8629 (const :tag "Maybe" maybe)
8630 (other :tag "On" t))
8631 :group 'editing-basics
8632 :version "21.1"
8633 :set (lambda (symbol value)
8634 ;; The fboundp is because of a problem with :set when
8635 ;; dumping Emacs. It doesn't really matter.
8636 (if (fboundp 'normal-erase-is-backspace-mode)
8637 (normal-erase-is-backspace-mode (or value 0))
8638 (set-default symbol value))))
8640 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8641 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8642 (unless frame (setq frame (selected-frame)))
8643 (with-selected-frame frame
8644 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8645 (normal-erase-is-backspace-mode
8646 (if (if (eq normal-erase-is-backspace 'maybe)
8647 (and (not noninteractive)
8648 (or (memq system-type '(ms-dos windows-nt))
8649 (memq window-system '(w32 ns))
8650 (and (memq window-system '(x))
8651 (fboundp 'x-backspace-delete-keys-p)
8652 (x-backspace-delete-keys-p))
8653 ;; If the terminal Emacs is running on has erase char
8654 ;; set to ^H, use the Backspace key for deleting
8655 ;; backward, and the Delete key for deleting forward.
8656 (and (null window-system)
8657 (eq tty-erase-char ?\^H))))
8658 normal-erase-is-backspace)
8659 1 0)))))
8661 (define-minor-mode normal-erase-is-backspace-mode
8662 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8663 With a prefix argument ARG, enable this feature if ARG is
8664 positive, and disable it otherwise. If called from Lisp, enable
8665 the mode if ARG is omitted or nil.
8667 On window systems, when this mode is on, Delete is mapped to C-d
8668 and Backspace is mapped to DEL; when this mode is off, both
8669 Delete and Backspace are mapped to DEL. (The remapping goes via
8670 `local-function-key-map', so binding Delete or Backspace in the
8671 global or local keymap will override that.)
8673 In addition, on window systems, the bindings of C-Delete, M-Delete,
8674 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8675 the global keymap in accordance with the functionality of Delete and
8676 Backspace. For example, if Delete is remapped to C-d, which deletes
8677 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8678 to DEL, which deletes backward, C-Delete is bound to
8679 `backward-kill-word'.
8681 If not running on a window system, a similar effect is accomplished by
8682 remapping C-h (normally produced by the Backspace key) and DEL via
8683 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8684 to C-d; if it's off, the keys are not remapped.
8686 When not running on a window system, and this mode is turned on, the
8687 former functionality of C-h is available on the F1 key. You should
8688 probably not turn on this mode on a text-only terminal if you don't
8689 have both Backspace, Delete and F1 keys.
8691 See also `normal-erase-is-backspace'."
8692 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8693 . (lambda (v)
8694 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8695 (if v 1 0))))
8696 (let ((enabled (eq 1 (terminal-parameter
8697 nil 'normal-erase-is-backspace))))
8699 (cond ((or (memq window-system '(x w32 ns pc))
8700 (memq system-type '(ms-dos windows-nt)))
8701 (let ((bindings
8702 `(([M-delete] [M-backspace])
8703 ([C-M-delete] [C-M-backspace])
8704 ([?\e C-delete] [?\e C-backspace]))))
8706 (if enabled
8707 (progn
8708 (define-key local-function-key-map [delete] [deletechar])
8709 (define-key local-function-key-map [kp-delete] [deletechar])
8710 (define-key local-function-key-map [backspace] [?\C-?])
8711 (dolist (b bindings)
8712 ;; Not sure if input-decode-map is really right, but
8713 ;; keyboard-translate-table (used below) only works
8714 ;; for integer events, and key-translation-table is
8715 ;; global (like the global-map, used earlier).
8716 (define-key input-decode-map (car b) nil)
8717 (define-key input-decode-map (cadr b) nil)))
8718 (define-key local-function-key-map [delete] [?\C-?])
8719 (define-key local-function-key-map [kp-delete] [?\C-?])
8720 (define-key local-function-key-map [backspace] [?\C-?])
8721 (dolist (b bindings)
8722 (define-key input-decode-map (car b) (cadr b))
8723 (define-key input-decode-map (cadr b) (car b))))))
8725 (if enabled
8726 (progn
8727 (keyboard-translate ?\C-h ?\C-?)
8728 (keyboard-translate ?\C-? ?\C-d))
8729 (keyboard-translate ?\C-h ?\C-h)
8730 (keyboard-translate ?\C-? ?\C-?))))
8732 (if (called-interactively-p 'interactive)
8733 (message "Delete key deletes %s"
8734 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8735 "forward" "backward")))))
8737 (defvar vis-mode-saved-buffer-invisibility-spec nil
8738 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8740 (define-minor-mode read-only-mode
8741 "Change whether the current buffer is read-only.
8742 With prefix argument ARG, make the buffer read-only if ARG is
8743 positive, otherwise make it writable. If buffer is read-only
8744 and `view-read-only' is non-nil, enter view mode.
8746 Do not call this from a Lisp program unless you really intend to
8747 do the same thing as the \\[read-only-mode] command, including
8748 possibly enabling or disabling View mode. Also, note that this
8749 command works by setting the variable `buffer-read-only', which
8750 does not affect read-only regions caused by text properties. To
8751 ignore read-only status in a Lisp program (whether due to text
8752 properties or buffer state), bind `inhibit-read-only' temporarily
8753 to a non-nil value."
8754 :variable buffer-read-only
8755 (cond
8756 ((and (not buffer-read-only) view-mode)
8757 (View-exit-and-edit)
8758 (make-local-variable 'view-read-only)
8759 (setq view-read-only t)) ; Must leave view mode.
8760 ((and buffer-read-only view-read-only
8761 ;; If view-mode is already active, `view-mode-enter' is a nop.
8762 (not view-mode)
8763 (not (eq (get major-mode 'mode-class) 'special)))
8764 (view-mode-enter))))
8766 (define-minor-mode visible-mode
8767 "Toggle making all invisible text temporarily visible (Visible mode).
8768 With a prefix argument ARG, enable Visible mode if ARG is
8769 positive, and disable it otherwise. If called from Lisp, enable
8770 the mode if ARG is omitted or nil.
8772 This mode works by saving the value of `buffer-invisibility-spec'
8773 and setting it to nil."
8774 :lighter " Vis"
8775 :group 'editing-basics
8776 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8777 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8778 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8779 (when visible-mode
8780 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8781 buffer-invisibility-spec)
8782 (setq buffer-invisibility-spec nil)))
8784 (defvar messages-buffer-mode-map
8785 (let ((map (make-sparse-keymap)))
8786 (set-keymap-parent map special-mode-map)
8787 (define-key map "g" nil) ; nothing to revert
8788 map))
8790 (define-derived-mode messages-buffer-mode special-mode "Messages"
8791 "Major mode used in the \"*Messages*\" buffer.")
8793 (defun messages-buffer ()
8794 "Return the \"*Messages*\" buffer.
8795 If it does not exist, create and it switch it to `messages-buffer-mode'."
8796 (or (get-buffer "*Messages*")
8797 (with-current-buffer (get-buffer-create "*Messages*")
8798 (messages-buffer-mode)
8799 (current-buffer))))
8802 ;; Minibuffer prompt stuff.
8804 ;;(defun minibuffer-prompt-modification (start end)
8805 ;; (error "You cannot modify the prompt"))
8808 ;;(defun minibuffer-prompt-insertion (start end)
8809 ;; (let ((inhibit-modification-hooks t))
8810 ;; (delete-region start end)
8811 ;; ;; Discard undo information for the text insertion itself
8812 ;; ;; and for the text deletion.above.
8813 ;; (when (consp buffer-undo-list)
8814 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8815 ;; (message "You cannot modify the prompt")))
8818 ;;(setq minibuffer-prompt-properties
8819 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8820 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8823 ;;;; Problematic external packages.
8825 ;; rms says this should be done by specifying symbols that define
8826 ;; versions together with bad values. This is therefore not as
8827 ;; flexible as it could be. See the thread:
8828 ;; https://lists.gnu.org/r/emacs-devel/2007-08/msg00300.html
8829 (defconst bad-packages-alist
8830 ;; Not sure exactly which semantic versions have problems.
8831 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8832 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8833 "The version of `semantic' loaded does not work in Emacs 22.
8834 It can cause constant high CPU load.
8835 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8836 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8837 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8838 ;; provided the `CUA-mode' feature. Since this is no longer true,
8839 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8840 (CUA-mode t nil
8841 "CUA-mode is now part of the standard GNU Emacs distribution,
8842 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8844 You have loaded an older version of CUA-mode which does not work
8845 correctly with this version of Emacs. You should remove the old
8846 version and use the one distributed with Emacs."))
8847 "Alist of packages known to cause problems in this version of Emacs.
8848 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8849 PACKAGE is either a regular expression to match file names, or a
8850 symbol (a feature name), like for `with-eval-after-load'.
8851 SYMBOL is either the name of a string variable, or t. Upon
8852 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8853 warning using STRING as the message.")
8855 (defun bad-package-check (package)
8856 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8857 (condition-case nil
8858 (let* ((list (assoc package bad-packages-alist))
8859 (symbol (nth 1 list)))
8860 (and list
8861 (boundp symbol)
8862 (or (eq symbol t)
8863 (and (stringp (setq symbol (eval symbol)))
8864 (string-match-p (nth 2 list) symbol)))
8865 (display-warning package (nth 3 list) :warning)))
8866 (error nil)))
8868 (dolist (elem bad-packages-alist)
8869 (let ((pkg (car elem)))
8870 (with-eval-after-load pkg
8871 (bad-package-check pkg))))
8874 ;;; Generic dispatcher commands
8876 ;; Macro `define-alternatives' is used to create generic commands.
8877 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8878 ;; that can have different alternative implementations where choosing
8879 ;; among them is exclusively a matter of user preference.
8881 ;; (define-alternatives COMMAND) creates a new interactive command
8882 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8883 ;; Typically, the user will not need to customize this variable; packages
8884 ;; wanting to add alternative implementations should use
8886 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8888 (defmacro define-alternatives (command &rest customizations)
8889 "Define the new command `COMMAND'.
8891 The argument `COMMAND' should be a symbol.
8893 Running `M-x COMMAND RET' for the first time prompts for which
8894 alternative to use and records the selected command as a custom
8895 variable.
8897 Running `C-u M-x COMMAND RET' prompts again for an alternative
8898 and overwrites the previous choice.
8900 The variable `COMMAND-alternatives' contains an alist with
8901 alternative implementations of COMMAND. `define-alternatives'
8902 does not have any effect until this variable is set.
8904 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8905 `defcustom' keywords and values to add to the declaration of
8906 `COMMAND-alternatives' (typically :group and :version)."
8907 (let* ((command-name (symbol-name command))
8908 (varalt-name (concat command-name "-alternatives"))
8909 (varalt-sym (intern varalt-name))
8910 (varimp-sym (intern (concat command-name "--implementation"))))
8911 `(progn
8913 (defcustom ,varalt-sym nil
8914 ,(format "Alist of alternative implementations for the `%s' command.
8916 Each entry must be a pair (ALTNAME . ALTFUN), where:
8917 ALTNAME - The name shown at user to describe the alternative implementation.
8918 ALTFUN - The function called to implement this alternative."
8919 command-name)
8920 :type '(alist :key-type string :value-type function)
8921 ,@customizations)
8923 (put ',varalt-sym 'definition-name ',command)
8924 (defvar ,varimp-sym nil "Internal use only.")
8926 (defun ,command (&optional arg)
8927 ,(format "Run generic command `%s'.
8928 If used for the first time, or with interactive ARG, ask the user which
8929 implementation to use for `%s'. The variable `%s'
8930 contains the list of implementations currently supported for this command."
8931 command-name command-name varalt-name)
8932 (interactive "P")
8933 (when (or arg (null ,varimp-sym))
8934 (let ((val (completing-read
8935 ,(format-message
8936 "Select implementation for command `%s': "
8937 command-name)
8938 ,varalt-sym nil t)))
8939 (unless (string-equal val "")
8940 (when (null ,varimp-sym)
8941 (message
8942 "Use C-u M-x %s RET`to select another implementation"
8943 ,command-name)
8944 (sit-for 3))
8945 (customize-save-variable ',varimp-sym
8946 (cdr (assoc-string val ,varalt-sym))))))
8947 (if ,varimp-sym
8948 (call-interactively ,varimp-sym)
8949 (message "%s" ,(format-message
8950 "No implementation selected for command `%s'"
8951 command-name)))))))
8954 ;;; Functions for changing capitalization that Do What I Mean
8955 (defun upcase-dwim (arg)
8956 "Upcase words in the region, if active; if not, upcase word at point.
8957 If the region is active, this function calls `upcase-region'.
8958 Otherwise, it calls `upcase-word', with prefix argument passed to it
8959 to upcase ARG words."
8960 (interactive "*p")
8961 (if (use-region-p)
8962 (upcase-region (region-beginning) (region-end))
8963 (upcase-word arg)))
8965 (defun downcase-dwim (arg)
8966 "Downcase words in the region, if active; if not, downcase word at point.
8967 If the region is active, this function calls `downcase-region'.
8968 Otherwise, it calls `downcase-word', with prefix argument passed to it
8969 to downcase ARG words."
8970 (interactive "*p")
8971 (if (use-region-p)
8972 (downcase-region (region-beginning) (region-end))
8973 (downcase-word arg)))
8975 (defun capitalize-dwim (arg)
8976 "Capitalize words in the region, if active; if not, capitalize word at point.
8977 If the region is active, this function calls `capitalize-region'.
8978 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8979 to capitalize ARG words."
8980 (interactive "*p")
8981 (if (use-region-p)
8982 (capitalize-region (region-beginning) (region-end))
8983 (capitalize-word arg)))
8987 (provide 'simple)
8989 ;;; simple.el ends here