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