Spelling fixes
[emacs.git] / lisp / simple.el
blob5ef511ce0a0bac365f6db8bd789729cd4c5a60c4
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 "Position of point in the output buffer after command completes.
57 It is a cons cell of the form (BUFFER . POS), where BUFFER is the output
58 buffer, and POS is the point position in BUFFER once the command finishes.
59 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
61 (defcustom idle-update-delay 0.5
62 "Idle time delay before updating various things on the screen.
63 Various Emacs features that update auxiliary information when point moves
64 wait this many seconds after Emacs becomes idle before doing an update."
65 :type 'number
66 :group 'display
67 :version "22.1")
69 (defgroup killing nil
70 "Killing and yanking commands."
71 :group 'editing)
73 (defgroup paren-matching nil
74 "Highlight (un)matching of parens and expressions."
75 :group 'matching)
77 ;;; next-error support framework
79 (defgroup next-error nil
80 "`next-error' support framework."
81 :group 'compilation
82 :version "22.1")
84 (defface next-error
85 '((t (:inherit region)))
86 "Face used to highlight next error locus."
87 :group 'next-error
88 :version "22.1")
90 (defcustom next-error-highlight 0.5
91 "Highlighting of locations in selected source buffers.
92 If a number, highlight the locus in `next-error' face for the given time
93 in seconds, or until the next command is executed.
94 If t, highlight the locus until the next command is executed, or until
95 some other locus replaces it.
96 If nil, don't highlight the locus in the source buffer.
97 If `fringe-arrow', indicate the locus by the fringe arrow
98 indefinitely until some other locus replaces it."
99 :type '(choice (number :tag "Highlight for specified time")
100 (const :tag "Semipermanent highlighting" t)
101 (const :tag "No highlighting" nil)
102 (const :tag "Fringe arrow" fringe-arrow))
103 :group 'next-error
104 :version "22.1")
106 (defcustom next-error-highlight-no-select 0.5
107 "Highlighting of locations in `next-error-no-select'.
108 If number, highlight the locus in `next-error' face for given time in seconds.
109 If t, highlight the locus indefinitely until some other locus replaces it.
110 If nil, don't highlight the locus in the source buffer.
111 If `fringe-arrow', indicate the locus by the fringe arrow
112 indefinitely until some other locus replaces it."
113 :type '(choice (number :tag "Highlight for specified time")
114 (const :tag "Semipermanent highlighting" t)
115 (const :tag "No highlighting" nil)
116 (const :tag "Fringe arrow" fringe-arrow))
117 :group 'next-error
118 :version "22.1")
120 (defcustom next-error-recenter nil
121 "Display the line in the visited source file recentered as specified.
122 If non-nil, the value is passed directly to `recenter'."
123 :type '(choice (integer :tag "Line to recenter to")
124 (const :tag "Center of window" (4))
125 (const :tag "No recentering" nil))
126 :group 'next-error
127 :version "23.1")
129 (defcustom next-error-hook nil
130 "List of hook functions run by `next-error' after visiting source file."
131 :type 'hook
132 :group 'next-error)
134 (defvar next-error-highlight-timer nil)
136 (defvar next-error-overlay-arrow-position nil)
137 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
138 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
140 (defvar next-error-last-buffer nil
141 "The most recent `next-error' buffer.
142 A buffer becomes most recent when its compilation, grep, or
143 similar mode is started, or when it is used with \\[next-error]
144 or \\[compile-goto-error].")
146 (defvar next-error-function nil
147 "Function to use to find the next error in the current buffer.
148 The function is called with 2 parameters:
149 ARG is an integer specifying by how many errors to move.
150 RESET is a boolean which, if non-nil, says to go back to the beginning
151 of the errors before moving.
152 Major modes providing compile-like functionality should set this variable
153 to indicate to `next-error' that this is a candidate buffer and how
154 to navigate in it.")
155 (make-variable-buffer-local 'next-error-function)
157 (defvar next-error-move-function nil
158 "Function to use to move to an error locus.
159 It takes two arguments, a buffer position in the error buffer
160 and a buffer position in the error locus buffer.
161 The buffer for the error locus should already be current.
162 nil means use goto-char using the second argument position.")
163 (make-variable-buffer-local 'next-error-move-function)
165 (defsubst next-error-buffer-p (buffer
166 &optional avoid-current
167 extra-test-inclusive
168 extra-test-exclusive)
169 "Return non-nil if BUFFER is a `next-error' capable buffer.
170 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
171 return nil.
173 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
174 BUFFER would not normally qualify. If it returns non-nil, BUFFER
175 is considered `next-error' capable, anyway, and the function
176 returns non-nil.
178 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
179 buffer would normally qualify. If it returns nil, BUFFER is
180 rejected, and the function returns nil."
181 (and (buffer-name buffer) ;First make sure it's live.
182 (not (and avoid-current (eq buffer (current-buffer))))
183 (with-current-buffer buffer
184 (if next-error-function ; This is the normal test.
185 ;; Optionally reject some buffers.
186 (if extra-test-exclusive
187 (funcall extra-test-exclusive)
189 ;; Optionally accept some other buffers.
190 (and extra-test-inclusive
191 (funcall extra-test-inclusive))))))
193 (defun next-error-find-buffer (&optional avoid-current
194 extra-test-inclusive
195 extra-test-exclusive)
196 "Return a `next-error' capable buffer.
198 If AVOID-CURRENT is non-nil, treat the current buffer
199 as an absolute last resort only.
201 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
202 that normally would not qualify. If it returns t, the buffer
203 in question is treated as usable.
205 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
206 that would normally be considered usable. If it returns nil,
207 that buffer is rejected."
209 ;; 1. If one window on the selected frame displays such buffer, return it.
210 (let ((window-buffers
211 (delete-dups
212 (delq nil (mapcar (lambda (w)
213 (if (next-error-buffer-p
214 (window-buffer w)
215 avoid-current
216 extra-test-inclusive extra-test-exclusive)
217 (window-buffer w)))
218 (window-list))))))
219 (if (eq (length window-buffers) 1)
220 (car window-buffers)))
221 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
222 (if (and next-error-last-buffer
223 (next-error-buffer-p next-error-last-buffer avoid-current
224 extra-test-inclusive extra-test-exclusive))
225 next-error-last-buffer)
226 ;; 3. If the current buffer is acceptable, choose it.
227 (if (next-error-buffer-p (current-buffer) avoid-current
228 extra-test-inclusive extra-test-exclusive)
229 (current-buffer))
230 ;; 4. Look for any acceptable buffer.
231 (let ((buffers (buffer-list)))
232 (while (and buffers
233 (not (next-error-buffer-p
234 (car buffers) avoid-current
235 extra-test-inclusive extra-test-exclusive)))
236 (setq buffers (cdr buffers)))
237 (car buffers))
238 ;; 5. Use the current buffer as a last resort if it qualifies,
239 ;; even despite AVOID-CURRENT.
240 (and avoid-current
241 (next-error-buffer-p (current-buffer) nil
242 extra-test-inclusive extra-test-exclusive)
243 (progn
244 (message "This is the only buffer with error message locations")
245 (current-buffer)))
246 ;; 6. Give up.
247 (error "No buffers contain error message locations")))
249 (defun next-error (&optional arg reset)
250 "Visit next `next-error' message and corresponding source code.
252 If all the error messages parsed so far have been processed already,
253 the message buffer is checked for new ones.
255 A prefix ARG specifies how many error messages to move;
256 negative means move back to previous error messages.
257 Just \\[universal-argument] as a prefix means reparse the error message buffer
258 and start at the first error.
260 The RESET argument specifies that we should restart from the beginning.
262 \\[next-error] normally uses the most recently started
263 compilation, grep, or occur buffer. It can also operate on any
264 buffer with output from the \\[compile], \\[grep] commands, or,
265 more generally, on any buffer in Compilation mode or with
266 Compilation Minor mode enabled, or any buffer in which
267 `next-error-function' is bound to an appropriate function.
268 To specify use of a particular buffer for error messages, type
269 \\[next-error] in that buffer when it is the only one displayed
270 in the current frame.
272 Once \\[next-error] has chosen the buffer for error messages, it
273 runs `next-error-hook' with `run-hooks', and stays with that buffer
274 until you use it in some other buffer which uses Compilation mode
275 or Compilation Minor mode.
277 To control which errors are matched, customize the variable
278 `compilation-error-regexp-alist'."
279 (interactive "P")
280 (if (consp arg) (setq reset t arg nil))
281 (when (setq next-error-last-buffer (next-error-find-buffer))
282 ;; we know here that next-error-function is a valid symbol we can funcall
283 (with-current-buffer next-error-last-buffer
284 (funcall next-error-function (prefix-numeric-value arg) reset)
285 (when next-error-recenter
286 (recenter next-error-recenter))
287 (run-hooks 'next-error-hook))))
289 (defun next-error-internal ()
290 "Visit the source code corresponding to the `next-error' message at point."
291 (setq next-error-last-buffer (current-buffer))
292 ;; we know here that next-error-function is a valid symbol we can funcall
293 (with-current-buffer next-error-last-buffer
294 (funcall next-error-function 0 nil)
295 (when next-error-recenter
296 (recenter next-error-recenter))
297 (run-hooks 'next-error-hook)))
299 (defalias 'goto-next-locus 'next-error)
300 (defalias 'next-match 'next-error)
302 (defun previous-error (&optional n)
303 "Visit previous `next-error' message and corresponding source code.
305 Prefix arg N says how many error messages to move backwards (or
306 forwards, if negative).
308 This operates on the output from the \\[compile] and \\[grep] commands."
309 (interactive "p")
310 (next-error (- (or n 1))))
312 (defun first-error (&optional n)
313 "Restart at the first error.
314 Visit corresponding source code.
315 With prefix arg N, visit the source code of the Nth error.
316 This operates on the output from the \\[compile] command, for instance."
317 (interactive "p")
318 (next-error n t))
320 (defun next-error-no-select (&optional n)
321 "Move point to the next error in the `next-error' buffer and highlight match.
322 Prefix arg N says how many error messages to move forwards (or
323 backwards, if negative).
324 Finds and highlights the source line like \\[next-error], but does not
325 select the source buffer."
326 (interactive "p")
327 (let ((next-error-highlight next-error-highlight-no-select))
328 (next-error n))
329 (pop-to-buffer next-error-last-buffer))
331 (defun previous-error-no-select (&optional n)
332 "Move point to the previous error in the `next-error' buffer and highlight match.
333 Prefix arg N says how many error messages to move backwards (or
334 forwards, if negative).
335 Finds and highlights the source line like \\[previous-error], but does not
336 select the source buffer."
337 (interactive "p")
338 (next-error-no-select (- (or n 1))))
340 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
341 (defvar next-error-follow-last-line nil)
343 (define-minor-mode next-error-follow-minor-mode
344 "Minor mode for compilation, occur and diff modes.
345 With a prefix argument ARG, enable mode if ARG is positive, and
346 disable it otherwise. If called from Lisp, enable mode if ARG is
347 omitted or nil.
348 When turned on, cursor motion in the compilation, grep, occur or diff
349 buffer causes automatic display of the corresponding source code location."
350 :group 'next-error :init-value nil :lighter " Fol"
351 (if (not next-error-follow-minor-mode)
352 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
353 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
354 (make-local-variable 'next-error-follow-last-line)))
356 ;; Used as a `post-command-hook' by `next-error-follow-mode'
357 ;; for the *Compilation* *grep* and *Occur* buffers.
358 (defun next-error-follow-mode-post-command-hook ()
359 (unless (equal next-error-follow-last-line (line-number-at-pos))
360 (setq next-error-follow-last-line (line-number-at-pos))
361 (condition-case nil
362 (let ((compilation-context-lines nil))
363 (setq compilation-current-error (point))
364 (next-error-no-select 0))
365 (error t))))
370 (defun fundamental-mode ()
371 "Major mode not specialized for anything in particular.
372 Other major modes are defined by comparison with this one."
373 (interactive)
374 (kill-all-local-variables)
375 (run-mode-hooks))
377 ;; Special major modes to view specially formatted data rather than files.
379 (defvar special-mode-map
380 (let ((map (make-sparse-keymap)))
381 (suppress-keymap map)
382 (define-key map "q" 'quit-window)
383 (define-key map " " 'scroll-up-command)
384 (define-key map [?\S-\ ] 'scroll-down-command)
385 (define-key map "\C-?" 'scroll-down-command)
386 (define-key map "?" 'describe-mode)
387 (define-key map "h" 'describe-mode)
388 (define-key map ">" 'end-of-buffer)
389 (define-key map "<" 'beginning-of-buffer)
390 (define-key map "g" 'revert-buffer)
391 map))
393 (put 'special-mode 'mode-class 'special)
394 (define-derived-mode special-mode nil "Special"
395 "Parent major mode from which special major modes should inherit."
396 (setq buffer-read-only t))
398 ;; Making and deleting lines.
400 (defvar self-insert-uses-region-functions nil
401 "Special hook to tell if `self-insert-command' will use the region.
402 It must be called via `run-hook-with-args-until-success' with no arguments.
403 Any `post-self-insert-command' which consumes the region should
404 register a function on this hook so that things like `delete-selection-mode'
405 can refrain from consuming the region.")
407 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
408 "Propertized string representing a hard newline character.")
410 (defun newline (&optional arg interactive)
411 "Insert a newline, and move to left margin of the new line if it's blank.
412 If option `use-hard-newlines' is non-nil, the newline is marked with the
413 text-property `hard'.
414 With ARG, insert that many newlines.
416 If `electric-indent-mode' is enabled, this indents the final new line
417 that it adds, and reindents the preceding line. To just insert
418 a newline, use \\[electric-indent-just-newline].
420 Calls `auto-fill-function' if the current column number is greater
421 than the value of `fill-column' and ARG is nil.
422 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
423 (interactive "*P\np")
424 (barf-if-buffer-read-only)
425 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
426 ;; Set last-command-event to tell self-insert what to insert.
427 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
428 (beforepos (point))
429 (last-command-event ?\n)
430 ;; Don't auto-fill if we have a numeric argument.
431 (auto-fill-function (if arg nil auto-fill-function))
432 (arg (prefix-numeric-value arg))
433 (postproc
434 ;; Do the rest in post-self-insert-hook, because we want to do it
435 ;; *before* other functions on that hook.
436 (lambda ()
437 ;; Mark the newline(s) `hard'.
438 (if use-hard-newlines
439 (set-hard-newline-properties
440 (- (point) arg) (point)))
441 ;; If the newline leaves the previous line blank, and we
442 ;; have a left margin, delete that from the blank line.
443 (save-excursion
444 (goto-char beforepos)
445 (beginning-of-line)
446 (and (looking-at "[ \t]$")
447 (> (current-left-margin) 0)
448 (delete-region (point)
449 (line-end-position))))
450 ;; Indent the line after the newline, except in one case:
451 ;; when we added the newline at the beginning of a line which
452 ;; starts a page.
453 (or was-page-start
454 (move-to-left-margin nil t)))))
455 (if (not interactive)
456 ;; FIXME: For non-interactive uses, many calls actually
457 ;; just want (insert "\n"), so maybe we should do just
458 ;; that, so as to avoid the risk of filling or running
459 ;; abbrevs unexpectedly.
460 (let ((post-self-insert-hook (list postproc)))
461 (self-insert-command arg))
462 (unwind-protect
463 (progn
464 (add-hook 'post-self-insert-hook postproc nil t)
465 (self-insert-command arg))
466 ;; We first used let-binding to protect the hook, but that
467 ;; was naive since add-hook affects the symbol-default
468 ;; value of the variable, whereas the let-binding might
469 ;; only protect the buffer-local value.
470 (remove-hook 'post-self-insert-hook postproc t))))
471 nil)
473 (defun set-hard-newline-properties (from to)
474 (let ((sticky (get-text-property from 'rear-nonsticky)))
475 (put-text-property from to 'hard 't)
476 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
477 (if (and (listp sticky) (not (memq 'hard sticky)))
478 (put-text-property from (point) 'rear-nonsticky
479 (cons 'hard sticky)))))
481 (defun open-line (n)
482 "Insert a newline and leave point before it.
483 If there is a fill prefix and/or a `left-margin', insert them on
484 the new line if the line would have been blank.
485 With arg N, insert N newlines."
486 (interactive "*p")
487 (let* ((do-fill-prefix (and fill-prefix (bolp)))
488 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
489 (loc (point-marker))
490 ;; Don't expand an abbrev before point.
491 (abbrev-mode nil))
492 (newline n)
493 (goto-char loc)
494 (while (> n 0)
495 (cond ((bolp)
496 (if do-left-margin (indent-to (current-left-margin)))
497 (if do-fill-prefix (insert-and-inherit fill-prefix))))
498 (forward-line 1)
499 (setq n (1- n)))
500 (goto-char loc)
501 ;; Necessary in case a margin or prefix was inserted.
502 (end-of-line)))
504 (defun split-line (&optional arg)
505 "Split current line, moving portion beyond point vertically down.
506 If the current line starts with `fill-prefix', insert it on the new
507 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
509 When called from Lisp code, ARG may be a prefix string to copy."
510 (interactive "*P")
511 (skip-chars-forward " \t")
512 (let* ((col (current-column))
513 (pos (point))
514 ;; What prefix should we check for (nil means don't).
515 (prefix (cond ((stringp arg) arg)
516 (arg nil)
517 (t fill-prefix)))
518 ;; Does this line start with it?
519 (have-prfx (and prefix
520 (save-excursion
521 (beginning-of-line)
522 (looking-at (regexp-quote prefix))))))
523 (newline 1)
524 (if have-prfx (insert-and-inherit prefix))
525 (indent-to col 0)
526 (goto-char pos)))
528 (defun delete-indentation (&optional arg)
529 "Join this line to previous and fix up whitespace at join.
530 If there is a fill prefix, delete it from the beginning of this line.
531 With argument, join this line to following line."
532 (interactive "*P")
533 (beginning-of-line)
534 (if arg (forward-line 1))
535 (if (eq (preceding-char) ?\n)
536 (progn
537 (delete-region (point) (1- (point)))
538 ;; If the second line started with the fill prefix,
539 ;; delete the prefix.
540 (if (and fill-prefix
541 (<= (+ (point) (length fill-prefix)) (point-max))
542 (string= fill-prefix
543 (buffer-substring (point)
544 (+ (point) (length fill-prefix)))))
545 (delete-region (point) (+ (point) (length fill-prefix))))
546 (fixup-whitespace))))
548 (defalias 'join-line #'delete-indentation) ; easier to find
550 (defun delete-blank-lines ()
551 "On blank line, delete all surrounding blank lines, leaving just one.
552 On isolated blank line, delete that one.
553 On nonblank line, delete any immediately following blank lines."
554 (interactive "*")
555 (let (thisblank singleblank)
556 (save-excursion
557 (beginning-of-line)
558 (setq thisblank (looking-at "[ \t]*$"))
559 ;; Set singleblank if there is just one blank line here.
560 (setq singleblank
561 (and thisblank
562 (not (looking-at "[ \t]*\n[ \t]*$"))
563 (or (bobp)
564 (progn (forward-line -1)
565 (not (looking-at "[ \t]*$")))))))
566 ;; Delete preceding blank lines, and this one too if it's the only one.
567 (if thisblank
568 (progn
569 (beginning-of-line)
570 (if singleblank (forward-line 1))
571 (delete-region (point)
572 (if (re-search-backward "[^ \t\n]" nil t)
573 (progn (forward-line 1) (point))
574 (point-min)))))
575 ;; Delete following blank lines, unless the current line is blank
576 ;; and there are no following blank lines.
577 (if (not (and thisblank singleblank))
578 (save-excursion
579 (end-of-line)
580 (forward-line 1)
581 (delete-region (point)
582 (if (re-search-forward "[^ \t\n]" nil t)
583 (progn (beginning-of-line) (point))
584 (point-max)))))
585 ;; Handle the special case where point is followed by newline and eob.
586 ;; Delete the line, leaving point at eob.
587 (if (looking-at "^[ \t]*\n\\'")
588 (delete-region (point) (point-max)))))
590 (defcustom delete-trailing-lines t
591 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
592 Trailing lines are deleted only if `delete-trailing-whitespace'
593 is called on the entire buffer (rather than an active region)."
594 :type 'boolean
595 :group 'editing
596 :version "24.3")
598 (defun region-modifiable-p (start end)
599 "Return non-nil if the region contains no read-only text."
600 (and (not (get-text-property start 'read-only))
601 (eq end (next-single-property-change start 'read-only nil end))))
603 (defun delete-trailing-whitespace (&optional start end)
604 "Delete trailing whitespace between START and END.
605 If called interactively, START and END are the start/end of the
606 region if the mark is active, or of the buffer's accessible
607 portion if the mark is inactive.
609 This command deletes whitespace characters after the last
610 non-whitespace character in each line between START and END. It
611 does not consider formfeed characters to be whitespace.
613 If this command acts on the entire buffer (i.e. if called
614 interactively with the mark inactive, or called from Lisp with
615 END nil), it also deletes all trailing lines at the end of the
616 buffer if the variable `delete-trailing-lines' is non-nil."
617 (interactive (progn
618 (barf-if-buffer-read-only)
619 (if (use-region-p)
620 (list (region-beginning) (region-end))
621 (list nil nil))))
622 (save-match-data
623 (save-excursion
624 (let ((end-marker (and end (copy-marker end))))
625 (goto-char (or start (point-min)))
626 (with-syntax-table (make-syntax-table (syntax-table))
627 ;; Don't delete formfeeds, even if they are considered whitespace.
628 (modify-syntax-entry ?\f "_")
629 (while (re-search-forward "\\s-$" end-marker t)
630 (skip-syntax-backward "-" (line-beginning-position))
631 (let ((b (point)) (e (match-end 0)))
632 (when (region-modifiable-p b e)
633 (delete-region b e)))))
634 (if end
635 (set-marker end-marker nil)
636 ;; Delete trailing empty lines.
637 (and delete-trailing-lines
638 ;; Really the end of buffer.
639 (= (goto-char (point-max)) (1+ (buffer-size)))
640 (<= (skip-chars-backward "\n") -2)
641 (region-modifiable-p (1+ (point)) (point-max))
642 (delete-region (1+ (point)) (point-max)))))))
643 ;; Return nil for the benefit of `write-file-functions'.
644 nil)
646 (defun newline-and-indent ()
647 "Insert a newline, then indent according to major mode.
648 Indentation is done using the value of `indent-line-function'.
649 In programming language modes, this is the same as TAB.
650 In some text modes, where TAB inserts a tab, this command indents to the
651 column specified by the function `current-left-margin'."
652 (interactive "*")
653 (delete-horizontal-space t)
654 (newline nil t)
655 (indent-according-to-mode))
657 (defun reindent-then-newline-and-indent ()
658 "Reindent current line, insert newline, then indent the new line.
659 Indentation of both lines is done according to the current major mode,
660 which means calling the current value of `indent-line-function'.
661 In programming language modes, this is the same as TAB.
662 In some text modes, where TAB inserts a tab, this indents to the
663 column specified by the function `current-left-margin'."
664 (interactive "*")
665 (let ((pos (point)))
666 ;; Be careful to insert the newline before indenting the line.
667 ;; Otherwise, the indentation might be wrong.
668 (newline)
669 (save-excursion
670 (goto-char pos)
671 ;; We are at EOL before the call to indent-according-to-mode, and
672 ;; after it we usually are as well, but not always. We tried to
673 ;; address it with `save-excursion' but that uses a normal marker
674 ;; whereas we need `move after insertion', so we do the save/restore
675 ;; by hand.
676 (setq pos (copy-marker pos t))
677 (indent-according-to-mode)
678 (goto-char pos)
679 ;; Remove the trailing white-space after indentation because
680 ;; indentation may introduce the whitespace.
681 (delete-horizontal-space t))
682 (indent-according-to-mode)))
684 (defcustom read-quoted-char-radix 8
685 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
686 Legitimate radix values are 8, 10 and 16."
687 :type '(choice (const 8) (const 10) (const 16))
688 :group 'editing-basics)
690 (defun read-quoted-char (&optional prompt)
691 "Like `read-char', but do not allow quitting.
692 Also, if the first character read is an octal digit,
693 we read any number of octal digits and return the
694 specified character code. Any nondigit terminates the sequence.
695 If the terminator is RET, it is discarded;
696 any other terminator is used itself as input.
698 The optional argument PROMPT specifies a string to use to prompt the user.
699 The variable `read-quoted-char-radix' controls which radix to use
700 for numeric input."
701 (let ((message-log-max nil)
702 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
703 help-event-list)))
704 done (first t) (code 0) char translated)
705 (while (not done)
706 (let ((inhibit-quit first)
707 ;; Don't let C-h or other help chars get the help
708 ;; message--only help function keys. See bug#16617.
709 (help-char nil)
710 (help-event-list help-events)
711 (help-form
712 "Type the special character you want to use,
713 or the octal character code.
714 RET terminates the character code and is discarded;
715 any other non-digit terminates the character code and is then used as input."))
716 (setq char (read-event (and prompt (format "%s-" prompt)) t))
717 (if inhibit-quit (setq quit-flag nil)))
718 ;; Translate TAB key into control-I ASCII character, and so on.
719 ;; Note: `read-char' does it using the `ascii-character' property.
720 ;; We tried using read-key instead, but that disables the keystroke
721 ;; echo produced by 'C-q', see bug#24635.
722 (let ((translation (lookup-key local-function-key-map (vector char))))
723 (setq translated (if (arrayp translation)
724 (aref translation 0)
725 char)))
726 (if (integerp translated)
727 (setq translated (char-resolve-modifiers translated)))
728 (cond ((null translated))
729 ((not (integerp translated))
730 (setq unread-command-events (list char)
731 done t))
732 ((/= (logand translated ?\M-\^@) 0)
733 ;; Turn a meta-character into a character with the 0200 bit set.
734 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
735 done t))
736 ((and (<= ?0 translated)
737 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
738 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
739 (and prompt (setq prompt (message "%s %c" prompt translated))))
740 ((and (<= ?a (downcase translated))
741 (< (downcase translated)
742 (+ ?a -10 (min 36 read-quoted-char-radix))))
743 (setq code (+ (* code read-quoted-char-radix)
744 (+ 10 (- (downcase translated) ?a))))
745 (and prompt (setq prompt (message "%s %c" prompt translated))))
746 ((and (not first) (eq translated ?\C-m))
747 (setq done t))
748 ((not first)
749 (setq unread-command-events (list char)
750 done t))
751 (t (setq code translated
752 done t)))
753 (setq first nil))
754 code))
756 (defun quoted-insert (arg)
757 "Read next input character and insert it.
758 This is useful for inserting control characters.
759 With argument, insert ARG copies of the character.
761 If the first character you type after this command is an octal digit,
762 you should type a sequence of octal digits which specify a character code.
763 Any nondigit terminates the sequence. If the terminator is a RET,
764 it is discarded; any other terminator is used itself as input.
765 The variable `read-quoted-char-radix' specifies the radix for this feature;
766 set it to 10 or 16 to use decimal or hex instead of octal.
768 In overwrite mode, this function inserts the character anyway, and
769 does not handle octal digits specially. This means that if you use
770 overwrite as your normal editing mode, you can use this function to
771 insert characters when necessary.
773 In binary overwrite mode, this function does overwrite, and octal
774 digits are interpreted as a character code. This is intended to be
775 useful for editing binary files."
776 (interactive "*p")
777 (let* ((char
778 ;; Avoid "obsolete" warnings for translation-table-for-input.
779 (with-no-warnings
780 (let (translation-table-for-input input-method-function)
781 (if (or (not overwrite-mode)
782 (eq overwrite-mode 'overwrite-mode-binary))
783 (read-quoted-char)
784 (read-char))))))
785 ;; This used to assume character codes 0240 - 0377 stand for
786 ;; characters in some single-byte character set, and converted them
787 ;; to Emacs characters. But in 23.1 this feature is deprecated
788 ;; in favor of inserting the corresponding Unicode characters.
789 ;; (if (and enable-multibyte-characters
790 ;; (>= char ?\240)
791 ;; (<= char ?\377))
792 ;; (setq char (unibyte-char-to-multibyte char)))
793 (unless (characterp char)
794 (user-error "%s is not a valid character"
795 (key-description (vector char))))
796 (if (> arg 0)
797 (if (eq overwrite-mode 'overwrite-mode-binary)
798 (delete-char arg)))
799 (while (> arg 0)
800 (insert-and-inherit char)
801 (setq arg (1- arg)))))
803 (defun forward-to-indentation (&optional arg)
804 "Move forward ARG lines and position at first nonblank character."
805 (interactive "^p")
806 (forward-line (or arg 1))
807 (skip-chars-forward " \t"))
809 (defun backward-to-indentation (&optional arg)
810 "Move backward ARG lines and position at first nonblank character."
811 (interactive "^p")
812 (forward-line (- (or arg 1)))
813 (skip-chars-forward " \t"))
815 (defun back-to-indentation ()
816 "Move point to the first non-whitespace character on this line."
817 (interactive "^")
818 (beginning-of-line 1)
819 (skip-syntax-forward " " (line-end-position))
820 ;; Move back over chars that have whitespace syntax but have the p flag.
821 (backward-prefix-chars))
823 (defun fixup-whitespace ()
824 "Fixup white space between objects around point.
825 Leave one space or none, according to the context."
826 (interactive "*")
827 (save-excursion
828 (delete-horizontal-space)
829 (if (or (looking-at "^\\|$\\|\\s)")
830 (save-excursion (forward-char -1)
831 (looking-at "$\\|\\s(\\|\\s'")))
833 (insert ?\s))))
835 (defun delete-horizontal-space (&optional backward-only)
836 "Delete all spaces and tabs around point.
837 If BACKWARD-ONLY is non-nil, only delete them before point."
838 (interactive "*P")
839 (let ((orig-pos (point)))
840 (delete-region
841 (if backward-only
842 orig-pos
843 (progn
844 (skip-chars-forward " \t")
845 (constrain-to-field nil orig-pos t)))
846 (progn
847 (skip-chars-backward " \t")
848 (constrain-to-field nil orig-pos)))))
850 (defun just-one-space (&optional n)
851 "Delete all spaces and tabs around point, leaving one space (or N spaces).
852 If N is negative, delete newlines as well, leaving -N spaces.
853 See also `cycle-spacing'."
854 (interactive "*p")
855 (cycle-spacing n nil 'single-shot))
857 (defvar cycle-spacing--context nil
858 "Store context used in consecutive calls to `cycle-spacing' command.
859 The first time `cycle-spacing' runs, it saves in this variable:
860 its N argument, the original point position, and the original spacing
861 around point.")
863 (defun cycle-spacing (&optional n preserve-nl-back mode)
864 "Manipulate whitespace around point in a smart way.
865 In interactive use, this function behaves differently in successive
866 consecutive calls.
868 The first call in a sequence acts like `just-one-space'.
869 It deletes all spaces and tabs around point, leaving one space
870 \(or N spaces). N is the prefix argument. If N is negative,
871 it deletes newlines as well, leaving -N spaces.
872 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
874 The second call in a sequence deletes all spaces.
876 The third call in a sequence restores the original whitespace (and point).
878 If MODE is `single-shot', it only performs the first step in the sequence.
879 If MODE is `fast' and the first step would not result in any change
880 \(i.e., there are exactly (abs N) spaces around point),
881 the function goes straight to the second step.
883 Repeatedly calling the function with different values of N starts a
884 new sequence each time."
885 (interactive "*p")
886 (let ((orig-pos (point))
887 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
888 (num (abs (or n 1))))
889 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
890 (constrain-to-field nil orig-pos)
891 (cond
892 ;; Command run for the first time, single-shot mode or different argument
893 ((or (eq 'single-shot mode)
894 (not (equal last-command this-command))
895 (not cycle-spacing--context)
896 (not (eq (car cycle-spacing--context) n)))
897 (let* ((start (point))
898 (num (- num (skip-chars-forward " " (+ num (point)))))
899 (mid (point))
900 (end (progn
901 (skip-chars-forward skip-characters)
902 (constrain-to-field nil orig-pos t))))
903 (setq cycle-spacing--context ;; Save for later.
904 ;; Special handling for case where there was no space at all.
905 (unless (= start end)
906 (cons n (cons orig-pos (buffer-substring start (point))))))
907 ;; If this run causes no change in buffer content, delete all spaces,
908 ;; otherwise delete all excess spaces.
909 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
910 start mid) end)
911 (insert (make-string num ?\s))))
913 ;; Command run for the second time.
914 ((not (equal orig-pos (point)))
915 (delete-region (point) orig-pos))
917 ;; Command run for the third time.
919 (insert (cddr cycle-spacing--context))
920 (goto-char (cadr cycle-spacing--context))
921 (setq cycle-spacing--context nil)))))
923 (defun beginning-of-buffer (&optional arg)
924 "Move point to the beginning of the buffer.
925 With numeric arg N, put point N/10 of the way from the beginning.
926 If the buffer is narrowed, this command uses the beginning of the
927 accessible part of the buffer.
929 Push mark at previous position, unless either a \\[universal-argument] prefix
930 is supplied, or Transient Mark mode is enabled and the mark is active."
931 (declare (interactive-only "use `(goto-char (point-min))' instead."))
932 (interactive "^P")
933 (or (consp arg)
934 (region-active-p)
935 (push-mark))
936 (let ((size (- (point-max) (point-min))))
937 (goto-char (if (and arg (not (consp arg)))
938 (+ (point-min)
939 (if (> size 10000)
940 ;; Avoid overflow for large buffer sizes!
941 (* (prefix-numeric-value arg)
942 (/ size 10))
943 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
944 (point-min))))
945 (if (and arg (not (consp arg))) (forward-line 1)))
947 (defun end-of-buffer (&optional arg)
948 "Move point to the end of the buffer.
949 With numeric arg N, put point N/10 of the way from the end.
950 If the buffer is narrowed, this command uses the end of the
951 accessible part of the buffer.
953 Push mark at previous position, unless either a \\[universal-argument] prefix
954 is supplied, or Transient Mark mode is enabled and the mark is active."
955 (declare (interactive-only "use `(goto-char (point-max))' instead."))
956 (interactive "^P")
957 (or (consp arg) (region-active-p) (push-mark))
958 (let ((size (- (point-max) (point-min))))
959 (goto-char (if (and arg (not (consp arg)))
960 (- (point-max)
961 (if (> size 10000)
962 ;; Avoid overflow for large buffer sizes!
963 (* (prefix-numeric-value arg)
964 (/ size 10))
965 (/ (* size (prefix-numeric-value arg)) 10)))
966 (point-max))))
967 ;; If we went to a place in the middle of the buffer,
968 ;; adjust it to the beginning of a line.
969 (cond ((and arg (not (consp arg))) (forward-line 1))
970 ((and (eq (current-buffer) (window-buffer))
971 (> (point) (window-end nil t)))
972 ;; If the end of the buffer is not already on the screen,
973 ;; then scroll specially to put it near, but not at, the bottom.
974 (overlay-recenter (point))
975 (recenter -3))))
977 (defcustom delete-active-region t
978 "Whether single-char deletion commands delete an active region.
979 This has an effect only if Transient Mark mode is enabled, and
980 affects `delete-forward-char' and `delete-backward-char', though
981 not `delete-char'.
983 If the value is the symbol `kill', the active region is killed
984 instead of deleted."
985 :type '(choice (const :tag "Delete active region" t)
986 (const :tag "Kill active region" kill)
987 (const :tag "Do ordinary deletion" nil))
988 :group 'killing
989 :version "24.1")
991 (defvar region-extract-function
992 (lambda (method)
993 (when (region-beginning)
994 (cond
995 ((eq method 'bounds)
996 (list (cons (region-beginning) (region-end))))
997 ((eq method 'delete-only)
998 (delete-region (region-beginning) (region-end)))
1000 (filter-buffer-substring (region-beginning) (region-end) method)))))
1001 "Function to get the region's content.
1002 Called with one argument METHOD.
1003 If METHOD is `delete-only', then delete the region; the return value
1004 is undefined. If METHOD is nil, then return the content as a string.
1005 If METHOD is `bounds', then return the boundaries of the region
1006 as a cons cell of the form (START . END).
1007 If METHOD is anything else, delete the region and return its content
1008 as a string, after filtering it with `filter-buffer-substring', which
1009 is called with METHOD as its 3rd argument.")
1011 (defvar region-insert-function
1012 (lambda (lines)
1013 (let ((first t))
1014 (while lines
1015 (or first
1016 (insert ?\n))
1017 (insert-for-yank (car lines))
1018 (setq lines (cdr lines)
1019 first nil))))
1020 "Function to insert the region's content.
1021 Called with one argument LINES.
1022 Insert the region as a list of lines.")
1024 (defun delete-backward-char (n &optional killflag)
1025 "Delete the previous N characters (following if N is negative).
1026 If Transient Mark mode is enabled, the mark is active, and N is 1,
1027 delete the text in the region and deactivate the mark instead.
1028 To disable this, set option `delete-active-region' to nil.
1030 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1031 kill ring) instead of delete. Interactively, N is the prefix
1032 arg, and KILLFLAG is set if N is explicitly specified.
1034 When killing, the killed text is filtered by
1035 `filter-buffer-substring' before it is saved in the kill ring, so
1036 the actual saved text might be different from what was killed.
1038 In Overwrite mode, single character backward deletion may replace
1039 tabs with spaces so as to back over columns, unless point is at
1040 the end of the line."
1041 (declare (interactive-only delete-char))
1042 (interactive "p\nP")
1043 (unless (integerp n)
1044 (signal 'wrong-type-argument (list 'integerp n)))
1045 (cond ((and (use-region-p)
1046 delete-active-region
1047 (= n 1))
1048 ;; If a region is active, kill or delete it.
1049 (if (eq delete-active-region 'kill)
1050 (kill-region (region-beginning) (region-end) 'region)
1051 (funcall region-extract-function 'delete-only)))
1052 ;; In Overwrite mode, maybe untabify while deleting
1053 ((null (or (null overwrite-mode)
1054 (<= n 0)
1055 (memq (char-before) '(?\t ?\n))
1056 (eobp)
1057 (eq (char-after) ?\n)))
1058 (let ((ocol (current-column)))
1059 (delete-char (- n) killflag)
1060 (save-excursion
1061 (insert-char ?\s (- ocol (current-column)) nil))))
1062 ;; Otherwise, do simple deletion.
1063 (t (delete-char (- n) killflag))))
1065 (defun delete-forward-char (n &optional killflag)
1066 "Delete the following N characters (previous if N is negative).
1067 If Transient Mark mode is enabled, the mark is active, and N is 1,
1068 delete the text in the region and deactivate the mark instead.
1069 To disable this, set variable `delete-active-region' to nil.
1071 Optional second arg KILLFLAG non-nil means to kill (save in kill
1072 ring) instead of delete. Interactively, N is the prefix arg, and
1073 KILLFLAG is set if N was explicitly specified.
1075 When killing, the killed text is filtered by
1076 `filter-buffer-substring' before it is saved in the kill ring, so
1077 the actual saved text might be different from what was killed."
1078 (declare (interactive-only delete-char))
1079 (interactive "p\nP")
1080 (unless (integerp n)
1081 (signal 'wrong-type-argument (list 'integerp n)))
1082 (cond ((and (use-region-p)
1083 delete-active-region
1084 (= n 1))
1085 ;; If a region is active, kill or delete it.
1086 (if (eq delete-active-region 'kill)
1087 (kill-region (region-beginning) (region-end) 'region)
1088 (funcall region-extract-function 'delete-only)))
1090 ;; Otherwise, do simple deletion.
1091 (t (delete-char n killflag))))
1093 (defun mark-whole-buffer ()
1094 "Put point at beginning and mark at end of buffer.
1095 If narrowing is in effect, only uses the accessible part of the buffer.
1096 You probably should not use this function in Lisp programs;
1097 it is usually a mistake for a Lisp function to use any subroutine
1098 that uses or sets the mark."
1099 (declare (interactive-only t))
1100 (interactive)
1101 (push-mark)
1102 (push-mark (point-max) nil t)
1103 ;; This is really `point-min' in most cases, but if we're in the
1104 ;; minibuffer, this is at the end of the prompt.
1105 (goto-char (minibuffer-prompt-end)))
1108 ;; Counting lines, one way or another.
1110 (defun goto-line (line &optional buffer)
1111 "Go to LINE, counting from line 1 at beginning of buffer.
1112 If called interactively, a numeric prefix argument specifies
1113 LINE; without a numeric prefix argument, read LINE from the
1114 minibuffer.
1116 If optional argument BUFFER is non-nil, switch to that buffer and
1117 move to line LINE there. If called interactively with \\[universal-argument]
1118 as argument, BUFFER is the most recently selected other buffer.
1120 Prior to moving point, this function sets the mark (without
1121 activating it), unless Transient Mark mode is enabled and the
1122 mark is already active.
1124 This function is usually the wrong thing to use in a Lisp program.
1125 What you probably want instead is something like:
1126 (goto-char (point-min))
1127 (forward-line (1- N))
1128 If at all possible, an even better solution is to use char counts
1129 rather than line counts."
1130 (declare (interactive-only forward-line))
1131 (interactive
1132 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1133 (list (prefix-numeric-value current-prefix-arg))
1134 ;; Look for a default, a number in the buffer at point.
1135 (let* ((default
1136 (save-excursion
1137 (skip-chars-backward "0-9")
1138 (if (looking-at "[0-9]")
1139 (string-to-number
1140 (buffer-substring-no-properties
1141 (point)
1142 (progn (skip-chars-forward "0-9")
1143 (point)))))))
1144 ;; Decide if we're switching buffers.
1145 (buffer
1146 (if (consp current-prefix-arg)
1147 (other-buffer (current-buffer) t)))
1148 (buffer-prompt
1149 (if buffer
1150 (concat " in " (buffer-name buffer))
1151 "")))
1152 ;; Read the argument, offering that number (if any) as default.
1153 (list (read-number (format "Goto line%s: " buffer-prompt)
1154 (list default (line-number-at-pos)))
1155 buffer))))
1156 ;; Switch to the desired buffer, one way or another.
1157 (if buffer
1158 (let ((window (get-buffer-window buffer)))
1159 (if window (select-window window)
1160 (switch-to-buffer-other-window buffer))))
1161 ;; Leave mark at previous position
1162 (or (region-active-p) (push-mark))
1163 ;; Move to the specified line number in that buffer.
1164 (save-restriction
1165 (widen)
1166 (goto-char (point-min))
1167 (if (eq selective-display t)
1168 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1169 (forward-line (1- line)))))
1171 (defun count-words-region (start end &optional arg)
1172 "Count the number of words in the region.
1173 If called interactively, print a message reporting the number of
1174 lines, words, and characters in the region (whether or not the
1175 region is active); with prefix ARG, report for the entire buffer
1176 rather than the region.
1178 If called from Lisp, return the number of words between positions
1179 START and END."
1180 (interactive (if current-prefix-arg
1181 (list nil nil current-prefix-arg)
1182 (list (region-beginning) (region-end) nil)))
1183 (cond ((not (called-interactively-p 'any))
1184 (count-words start end))
1185 (arg
1186 (count-words--buffer-message))
1188 (count-words--message "Region" start end))))
1190 (defun count-words (start end)
1191 "Count words between START and END.
1192 If called interactively, START and END are normally the start and
1193 end of the buffer; but if the region is active, START and END are
1194 the start and end of the region. Print a message reporting the
1195 number of lines, words, and chars.
1197 If called from Lisp, return the number of words between START and
1198 END, without printing any message."
1199 (interactive (list nil nil))
1200 (cond ((not (called-interactively-p 'any))
1201 (let ((words 0))
1202 (save-excursion
1203 (save-restriction
1204 (narrow-to-region start end)
1205 (goto-char (point-min))
1206 (while (forward-word-strictly 1)
1207 (setq words (1+ words)))))
1208 words))
1209 ((use-region-p)
1210 (call-interactively 'count-words-region))
1212 (count-words--buffer-message))))
1214 (defun count-words--buffer-message ()
1215 (count-words--message
1216 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1217 (point-min) (point-max)))
1219 (defun count-words--message (str start end)
1220 (let ((lines (count-lines start end))
1221 (words (count-words start end))
1222 (chars (- end start)))
1223 (message "%s has %d line%s, %d word%s, and %d character%s."
1225 lines (if (= lines 1) "" "s")
1226 words (if (= words 1) "" "s")
1227 chars (if (= chars 1) "" "s"))))
1229 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1231 (defun what-line ()
1232 "Print the current buffer line number and narrowed line number of point."
1233 (interactive)
1234 (let ((start (point-min))
1235 (n (line-number-at-pos)))
1236 (if (= start 1)
1237 (message "Line %d" n)
1238 (save-excursion
1239 (save-restriction
1240 (widen)
1241 (message "line %d (narrowed line %d)"
1242 (+ n (line-number-at-pos start) -1) n))))))
1244 (defun count-lines (start end)
1245 "Return number of lines between START and END.
1246 This is usually the number of newlines between them,
1247 but can be one more if START is not equal to END
1248 and the greater of them is not at the start of a line."
1249 (save-excursion
1250 (save-restriction
1251 (narrow-to-region start end)
1252 (goto-char (point-min))
1253 (if (eq selective-display t)
1254 (save-match-data
1255 (let ((done 0))
1256 (while (re-search-forward "[\n\C-m]" nil t 40)
1257 (setq done (+ 40 done)))
1258 (while (re-search-forward "[\n\C-m]" nil t 1)
1259 (setq done (+ 1 done)))
1260 (goto-char (point-max))
1261 (if (and (/= start end)
1262 (not (bolp)))
1263 (1+ done)
1264 done)))
1265 (- (buffer-size) (forward-line (buffer-size)))))))
1267 (defun line-number-at-pos (&optional pos absolute)
1268 "Return buffer line number at position POS.
1269 If POS is nil, use current buffer location.
1271 If ABSOLUTE is nil, the default, counting starts
1272 at (point-min), so the value refers to the contents of the
1273 accessible portion of the (potentially narrowed) buffer. If
1274 ABSOLUTE is non-nil, ignore any narrowing and return the
1275 absolute line number."
1276 (save-restriction
1277 (when absolute
1278 (widen))
1279 (let ((opoint (or pos (point))) start)
1280 (save-excursion
1281 (goto-char (point-min))
1282 (setq start (point))
1283 (goto-char opoint)
1284 (forward-line 0)
1285 (1+ (count-lines start (point)))))))
1287 (defun what-cursor-position (&optional detail)
1288 "Print info on cursor position (on screen and within buffer).
1289 Also describe the character after point, and give its character code
1290 in octal, decimal and hex.
1292 For a non-ASCII multibyte character, also give its encoding in the
1293 buffer's selected coding system if the coding system encodes the
1294 character safely. If the character is encoded into one byte, that
1295 code is shown in hex. If the character is encoded into more than one
1296 byte, just \"...\" is shown.
1298 In addition, with prefix argument, show details about that character
1299 in *Help* buffer. See also the command `describe-char'."
1300 (interactive "P")
1301 (let* ((char (following-char))
1302 (bidi-fixer
1303 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1304 ;; start a directional embedding, which could completely
1305 ;; disrupt the rest of the line (e.g., RLO will display the
1306 ;; rest of the line right-to-left). So we put an invisible
1307 ;; PDF character after these characters, to end the
1308 ;; embedding, which eliminates any effects on the rest of
1309 ;; the line. For RLE and RLO we also append an invisible
1310 ;; LRM, to avoid reordering the following numerical
1311 ;; characters. For LRI/RLI/FSI we append a PDI.
1312 (cond ((memq char '(?\x202a ?\x202d))
1313 (propertize (string ?\x202c) 'invisible t))
1314 ((memq char '(?\x202b ?\x202e))
1315 (propertize (string ?\x202c ?\x200e) 'invisible t))
1316 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1317 (propertize (string ?\x2069) 'invisible t))
1318 ;; Strong right-to-left characters cause reordering of
1319 ;; the following numerical characters which show the
1320 ;; codepoint, so append LRM to countermand that.
1321 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1322 (propertize (string ?\x200e) 'invisible t))
1324 "")))
1325 (beg (point-min))
1326 (end (point-max))
1327 (pos (point))
1328 (total (buffer-size))
1329 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1330 (hscroll (if (= (window-hscroll) 0)
1332 (format " Hscroll=%d" (window-hscroll))))
1333 (col (current-column)))
1334 (if (= pos end)
1335 (if (or (/= beg 1) (/= end (1+ total)))
1336 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1337 pos total percent beg end col hscroll)
1338 (message "point=%d of %d (EOB) column=%d%s"
1339 pos total col hscroll))
1340 (let ((coding buffer-file-coding-system)
1341 encoded encoding-msg display-prop under-display)
1342 (if (or (not coding)
1343 (eq (coding-system-type coding) t))
1344 (setq coding (default-value 'buffer-file-coding-system)))
1345 (if (eq (char-charset char) 'eight-bit)
1346 (setq encoding-msg
1347 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1348 ;; Check if the character is displayed with some `display'
1349 ;; text property. In that case, set under-display to the
1350 ;; buffer substring covered by that property.
1351 (setq display-prop (get-char-property pos 'display))
1352 (if display-prop
1353 (let ((to (or (next-single-char-property-change pos 'display)
1354 (point-max))))
1355 (if (< to (+ pos 4))
1356 (setq under-display "")
1357 (setq under-display "..."
1358 to (+ pos 4)))
1359 (setq under-display
1360 (concat (buffer-substring-no-properties pos to)
1361 under-display)))
1362 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1363 (setq encoding-msg
1364 (if display-prop
1365 (if (not (stringp display-prop))
1366 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1367 char char char under-display)
1368 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1369 char char char under-display display-prop))
1370 (if encoded
1371 (format "(%d, #o%o, #x%x, file %s)"
1372 char char char
1373 (if (> (length encoded) 1)
1374 "..."
1375 (encoded-string-description encoded coding)))
1376 (format "(%d, #o%o, #x%x)" char char char)))))
1377 (if detail
1378 ;; We show the detailed information about CHAR.
1379 (describe-char (point)))
1380 (if (or (/= beg 1) (/= end (1+ total)))
1381 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1382 (if (< char 256)
1383 (single-key-description char)
1384 (buffer-substring-no-properties (point) (1+ (point))))
1385 bidi-fixer
1386 encoding-msg pos total percent beg end col hscroll)
1387 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1388 (if enable-multibyte-characters
1389 (if (< char 128)
1390 (single-key-description char)
1391 (buffer-substring-no-properties (point) (1+ (point))))
1392 (single-key-description char))
1393 bidi-fixer encoding-msg pos total percent col hscroll))))))
1395 ;; Initialize read-expression-map. It is defined at C level.
1396 (defvar read-expression-map
1397 (let ((m (make-sparse-keymap)))
1398 (define-key m "\M-\t" 'completion-at-point)
1399 ;; Might as well bind TAB to completion, since inserting a TAB char is
1400 ;; much too rarely useful.
1401 (define-key m "\t" 'completion-at-point)
1402 (set-keymap-parent m minibuffer-local-map)
1405 (defun read-minibuffer (prompt &optional initial-contents)
1406 "Return a Lisp object read using the minibuffer, unevaluated.
1407 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1408 is a string to insert in the minibuffer before reading.
1409 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1410 Such arguments are used as in `read-from-minibuffer'.)"
1411 ;; Used for interactive spec `x'.
1412 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1413 t 'minibuffer-history))
1415 (defun eval-minibuffer (prompt &optional initial-contents)
1416 "Return value of Lisp expression read using the minibuffer.
1417 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1418 is a string to insert in the minibuffer before reading.
1419 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1420 Such arguments are used as in `read-from-minibuffer'.)"
1421 ;; Used for interactive spec `X'.
1422 (eval (read--expression prompt initial-contents)))
1424 (defvar minibuffer-completing-symbol nil
1425 "Non-nil means completing a Lisp symbol in the minibuffer.")
1426 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1428 (defvar minibuffer-default nil
1429 "The current default value or list of default values in the minibuffer.
1430 The functions `read-from-minibuffer' and `completing-read' bind
1431 this variable locally.")
1433 (defcustom eval-expression-print-level 4
1434 "Value for `print-level' while printing value in `eval-expression'.
1435 A value of nil means no limit."
1436 :group 'lisp
1437 :type '(choice (const :tag "No Limit" nil) integer)
1438 :version "21.1")
1440 (defcustom eval-expression-print-length 12
1441 "Value for `print-length' while printing value in `eval-expression'.
1442 A value of nil means no limit."
1443 :group 'lisp
1444 :type '(choice (const :tag "No Limit" nil) integer)
1445 :version "21.1")
1447 (defcustom eval-expression-debug-on-error t
1448 "If non-nil set `debug-on-error' to t in `eval-expression'.
1449 If nil, don't change the value of `debug-on-error'."
1450 :group 'lisp
1451 :type 'boolean
1452 :version "21.1")
1454 (defcustom eval-expression-print-maximum-character 127
1455 "The largest integer that will be displayed as a character.
1456 This affects printing by `eval-expression' (via
1457 `eval-expression-print-format')."
1458 :group 'lisp
1459 :type 'integer
1460 :version "26.1")
1462 (defun eval-expression-print-format (value)
1463 "If VALUE in an integer, return a specially formatted string.
1464 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1465 If VALUE is not an integer, nil is returned.
1466 This function is used by commands like `eval-expression' that
1467 display the result of expression evaluation."
1468 (when (integerp value)
1469 (let ((char-string
1470 (and (characterp value)
1471 (<= value eval-expression-print-maximum-character)
1472 (char-displayable-p value)
1473 (prin1-char value))))
1474 (if char-string
1475 (format " (#o%o, #x%x, %s)" value value char-string)
1476 (format " (#o%o, #x%x)" value value)))))
1478 (defvar eval-expression-minibuffer-setup-hook nil
1479 "Hook run by `eval-expression' when entering the minibuffer.")
1481 (defun read--expression (prompt &optional initial-contents)
1482 (let ((minibuffer-completing-symbol t))
1483 (minibuffer-with-setup-hook
1484 (lambda ()
1485 ;; FIXME: call emacs-lisp-mode?
1486 (add-function :before-until (local 'eldoc-documentation-function)
1487 #'elisp-eldoc-documentation-function)
1488 (eldoc-mode 1)
1489 (add-hook 'completion-at-point-functions
1490 #'elisp-completion-at-point nil t)
1491 (run-hooks 'eval-expression-minibuffer-setup-hook))
1492 (read-from-minibuffer prompt initial-contents
1493 read-expression-map t
1494 'read-expression-history))))
1496 (defun eval-expression-get-print-arguments (prefix-argument)
1497 "Get arguments for commands that print an expression result.
1498 Returns a list (INSERT-VALUE NO-TRUNCATE CHAR-PRINT-LIMIT)
1499 based on PREFIX-ARG. This function determines the interpretation
1500 of the prefix argument for `eval-expression' and
1501 `eval-last-sexp'."
1502 (let ((num (prefix-numeric-value prefix-argument)))
1503 (list (not (memq prefix-argument '(- nil)))
1504 (= num 0)
1505 (cond ((not (memq prefix-argument '(0 -1 - nil))) nil)
1506 ((= num -1) most-positive-fixnum)
1507 (t eval-expression-print-maximum-character)))))
1509 ;; We define this, rather than making `eval' interactive,
1510 ;; for the sake of completion of names like eval-region, eval-buffer.
1511 (defun eval-expression (exp &optional insert-value no-truncate char-print-limit)
1512 "Evaluate EXP and print value in the echo area.
1513 When called interactively, read an Emacs Lisp expression and
1514 evaluate it. Value is also consed on to front of the variable
1515 `values'. Optional argument INSERT-VALUE non-nil (interactively,
1516 with a non `-' prefix argument) means insert the result into the
1517 current buffer instead of printing it in the echo area.
1519 Normally, this function truncates long output according to the
1520 value of the variables `eval-expression-print-length' and
1521 `eval-expression-print-level'. When NO-TRUNCATE is
1522 non-nil (interactively, with a prefix argument of zero), however,
1523 there is no such truncation.
1525 If the resulting value is an integer, and CHAR-PRINT-LIMIT is
1526 non-nil (interactively, unless given a positive prefix argument)
1527 it will be printed in several additional formats (octal,
1528 hexadecimal, and character). The character format is only used
1529 if the value is below CHAR-PRINT-LIMIT (interactively, if the
1530 prefix argument is -1 or the value is below
1531 `eval-expression-print-maximum-character').
1533 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1534 minibuffer.
1536 If `eval-expression-debug-on-error' is non-nil, which is the default,
1537 this command arranges for all errors to enter the debugger."
1538 (interactive
1539 (cons (read--expression "Eval: ")
1540 (eval-expression-get-print-arguments current-prefix-arg)))
1542 (if (null eval-expression-debug-on-error)
1543 (push (eval exp lexical-binding) values)
1544 (let ((old-value (make-symbol "t")) new-value)
1545 ;; Bind debug-on-error to something unique so that we can
1546 ;; detect when evalled code changes it.
1547 (let ((debug-on-error old-value))
1548 (push (eval (macroexpand-all exp) lexical-binding) values)
1549 (setq new-value debug-on-error))
1550 ;; If evalled code has changed the value of debug-on-error,
1551 ;; propagate that change to the global binding.
1552 (unless (eq old-value new-value)
1553 (setq debug-on-error new-value))))
1555 (let ((print-length (unless no-truncate eval-expression-print-length))
1556 (print-level (unless no-truncate eval-expression-print-level))
1557 (eval-expression-print-maximum-character char-print-limit)
1558 (deactivate-mark))
1559 (let ((out (if insert-value (current-buffer) t)))
1560 (prog1
1561 (prin1 (car values) out)
1562 (let ((str (and char-print-limit
1563 (eval-expression-print-format (car values)))))
1564 (when str (princ str out)))))))
1566 (defun edit-and-eval-command (prompt command)
1567 "Prompting with PROMPT, let user edit COMMAND and eval result.
1568 COMMAND is a Lisp expression. Let user edit that expression in
1569 the minibuffer, then read and evaluate the result."
1570 (let ((command
1571 (let ((print-level nil)
1572 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1573 (unwind-protect
1574 (read-from-minibuffer prompt
1575 (prin1-to-string command)
1576 read-expression-map t
1577 'command-history)
1578 ;; If command was added to command-history as a string,
1579 ;; get rid of that. We want only evaluable expressions there.
1580 (if (stringp (car command-history))
1581 (setq command-history (cdr command-history)))))))
1583 ;; If command to be redone does not match front of history,
1584 ;; add it to the history.
1585 (or (equal command (car command-history))
1586 (setq command-history (cons command command-history)))
1587 (eval command)))
1589 (defun repeat-complex-command (arg)
1590 "Edit and re-evaluate last complex command, or ARGth from last.
1591 A complex command is one which used the minibuffer.
1592 The command is placed in the minibuffer as a Lisp form for editing.
1593 The result is executed, repeating the command as changed.
1594 If the command has been changed or is not the most recent previous
1595 command it is added to the front of the command history.
1596 You can use the minibuffer history commands \
1597 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1598 to get different commands to edit and resubmit."
1599 (interactive "p")
1600 (let ((elt (nth (1- arg) command-history))
1601 newcmd)
1602 (if elt
1603 (progn
1604 (setq newcmd
1605 (let ((print-level nil)
1606 (minibuffer-history-position arg)
1607 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1608 (unwind-protect
1609 (read-from-minibuffer
1610 "Redo: " (prin1-to-string elt) read-expression-map t
1611 (cons 'command-history arg))
1613 ;; If command was added to command-history as a
1614 ;; string, get rid of that. We want only
1615 ;; evaluable expressions there.
1616 (if (stringp (car command-history))
1617 (setq command-history (cdr command-history))))))
1619 ;; If command to be redone does not match front of history,
1620 ;; add it to the history.
1621 (or (equal newcmd (car command-history))
1622 (setq command-history (cons newcmd command-history)))
1623 (apply #'funcall-interactively
1624 (car newcmd)
1625 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1626 (if command-history
1627 (error "Argument %d is beyond length of command history" arg)
1628 (error "There are no previous complex commands to repeat")))))
1631 (defvar extended-command-history nil)
1632 (defvar execute-extended-command--last-typed nil)
1634 (defun read-extended-command ()
1635 "Read command name to invoke in `execute-extended-command'."
1636 (minibuffer-with-setup-hook
1637 (lambda ()
1638 (add-hook 'post-self-insert-hook
1639 (lambda ()
1640 (setq execute-extended-command--last-typed
1641 (minibuffer-contents)))
1642 nil 'local)
1643 (set (make-local-variable 'minibuffer-default-add-function)
1644 (lambda ()
1645 ;; Get a command name at point in the original buffer
1646 ;; to propose it after M-n.
1647 (with-current-buffer (window-buffer (minibuffer-selected-window))
1648 (and (commandp (function-called-at-point))
1649 (format "%S" (function-called-at-point)))))))
1650 ;; Read a string, completing from and restricting to the set of
1651 ;; all defined commands. Don't provide any initial input.
1652 ;; Save the command read on the extended-command history list.
1653 (completing-read
1654 (concat (cond
1655 ((eq current-prefix-arg '-) "- ")
1656 ((and (consp current-prefix-arg)
1657 (eq (car current-prefix-arg) 4)) "C-u ")
1658 ((and (consp current-prefix-arg)
1659 (integerp (car current-prefix-arg)))
1660 (format "%d " (car current-prefix-arg)))
1661 ((integerp current-prefix-arg)
1662 (format "%d " current-prefix-arg)))
1663 ;; This isn't strictly correct if `execute-extended-command'
1664 ;; is bound to anything else (e.g. [menu]).
1665 ;; It could use (key-description (this-single-command-keys)),
1666 ;; but actually a prompt other than "M-x" would be confusing,
1667 ;; because "M-x" is a well-known prompt to read a command
1668 ;; and it serves as a shorthand for "Extended command: ".
1669 "M-x ")
1670 (lambda (string pred action)
1671 (let ((pred
1672 (if (memq action '(nil t))
1673 ;; Exclude obsolete commands from completions.
1674 (lambda (sym)
1675 (and (funcall pred sym)
1676 (or (equal string (symbol-name sym))
1677 (not (get sym 'byte-obsolete-info)))))
1678 pred)))
1679 (complete-with-action action obarray string pred)))
1680 #'commandp t nil 'extended-command-history)))
1682 (defcustom suggest-key-bindings t
1683 "Non-nil means show the equivalent key-binding when M-x command has one.
1684 The value can be a length of time to show the message for.
1685 If the value is non-nil and not a number, we wait 2 seconds."
1686 :group 'keyboard
1687 :type '(choice (const :tag "off" nil)
1688 (integer :tag "time" 2)
1689 (other :tag "on")))
1691 (defcustom extended-command-suggest-shorter t
1692 "If non-nil, show a shorter M-x invocation when there is one."
1693 :group 'keyboard
1694 :type 'boolean
1695 :version "26.1")
1697 (defun execute-extended-command--shorter-1 (name length)
1698 (cond
1699 ((zerop length) (list ""))
1700 ((equal name "") nil)
1702 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1703 (execute-extended-command--shorter-1
1704 (substring name 1) (1- length)))
1705 (when (string-match "\\`\\(-\\)?[^-]*" name)
1706 (execute-extended-command--shorter-1
1707 (substring name (match-end 0)) length))))))
1709 (defun execute-extended-command--shorter (name typed)
1710 (let ((candidates '())
1711 (max (length typed))
1712 (len 1)
1713 binding)
1714 (while (and (not binding)
1715 (progn
1716 (unless candidates
1717 (setq len (1+ len))
1718 (setq candidates (execute-extended-command--shorter-1
1719 name len)))
1720 ;; Don't show the help message if the binding isn't
1721 ;; significantly shorter than the M-x command the user typed.
1722 (< len (- max 5))))
1723 (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
1724 (let ((candidate (pop candidates)))
1725 (when (equal name
1726 (car-safe (completion-try-completion
1727 candidate obarray 'commandp len)))
1728 (setq binding candidate))))
1729 binding))
1731 (defun execute-extended-command (prefixarg &optional command-name typed)
1732 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1733 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1734 "Read a command name, then read the arguments and call the command.
1735 To pass a prefix argument to the command you are
1736 invoking, give a prefix argument to `execute-extended-command'."
1737 (declare (interactive-only command-execute))
1738 ;; FIXME: Remember the actual text typed by the user before completion,
1739 ;; so that we don't later on suggest the same shortening.
1740 (interactive
1741 (let ((execute-extended-command--last-typed nil))
1742 (list current-prefix-arg
1743 (read-extended-command)
1744 execute-extended-command--last-typed)))
1745 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1746 (unless command-name
1747 (let ((current-prefix-arg prefixarg) ; for prompt
1748 (execute-extended-command--last-typed nil))
1749 (setq command-name (read-extended-command))
1750 (setq typed execute-extended-command--last-typed)))
1751 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1752 (binding (and suggest-key-bindings
1753 (not executing-kbd-macro)
1754 (where-is-internal function overriding-local-map t))))
1755 (unless (commandp function)
1756 (error "`%s' is not a valid command name" command-name))
1757 ;; Some features, such as novice.el, rely on this-command-keys
1758 ;; including M-x COMMAND-NAME RET.
1759 (set--this-command-keys (concat "\M-x" (symbol-name function) "\r"))
1760 (setq this-command function)
1761 ;; Normally `real-this-command' should never be changed, but here we really
1762 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1763 ;; binding" for <cmd>, so the command the user really wanted to run is
1764 ;; `function' and not `execute-extended-command'. The difference is
1765 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1766 (setq real-this-command function)
1767 (let ((prefix-arg prefixarg))
1768 (command-execute function 'record))
1769 ;; If enabled, show which key runs this command.
1770 ;; But first wait, and skip the message if there is input.
1771 (let* ((waited
1772 ;; If this command displayed something in the echo area;
1773 ;; wait a few seconds, then display our suggestion message.
1774 ;; FIXME: Wait *after* running post-command-hook!
1775 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1776 ;; find a better answer anyway!
1777 (when suggest-key-bindings
1778 (sit-for (cond
1779 ((zerop (length (current-message))) 0)
1780 ((numberp suggest-key-bindings) suggest-key-bindings)
1781 (t 2))))))
1782 (when (and waited (not (consp unread-command-events)))
1783 (unless (or (not extended-command-suggest-shorter)
1784 binding executing-kbd-macro (not (symbolp function))
1785 (<= (length (symbol-name function)) 2))
1786 ;; There's no binding for CMD. Let's try and find the shortest
1787 ;; string to use in M-x.
1788 ;; FIXME: Can be slow. Cache it maybe?
1789 (while-no-input
1790 (setq binding (execute-extended-command--shorter
1791 (symbol-name function) typed))))
1792 (when binding
1793 (with-temp-message
1794 (format-message "You can run the command `%s' with %s"
1795 function
1796 (if (stringp binding)
1797 (concat "M-x " binding " RET")
1798 (key-description binding)))
1799 (sit-for (if (numberp suggest-key-bindings)
1800 suggest-key-bindings
1801 2))))))))
1803 (defun command-execute (cmd &optional record-flag keys special)
1804 ;; BEWARE: Called directly from the C code.
1805 "Execute CMD as an editor command.
1806 CMD must be a symbol that satisfies the `commandp' predicate.
1807 Optional second arg RECORD-FLAG non-nil
1808 means unconditionally put this command in the variable `command-history'.
1809 Otherwise, that is done only if an arg is read using the minibuffer.
1810 The argument KEYS specifies the value to use instead of (this-command-keys)
1811 when reading the arguments; if it is nil, (this-command-keys) is used.
1812 The argument SPECIAL, if non-nil, means that this command is executing
1813 a special event, so ignore the prefix argument and don't clear it."
1814 (setq debug-on-next-call nil)
1815 (let ((prefixarg (unless special
1816 ;; FIXME: This should probably be done around
1817 ;; pre-command-hook rather than here!
1818 (prog1 prefix-arg
1819 (setq current-prefix-arg prefix-arg)
1820 (setq prefix-arg nil)
1821 (when current-prefix-arg
1822 (prefix-command-update))))))
1823 (if (and (symbolp cmd)
1824 (get cmd 'disabled)
1825 disabled-command-function)
1826 ;; FIXME: Weird calling convention!
1827 (run-hooks 'disabled-command-function)
1828 (let ((final cmd))
1829 (while
1830 (progn
1831 (setq final (indirect-function final))
1832 (if (autoloadp final)
1833 (setq final (autoload-do-load final cmd)))))
1834 (cond
1835 ((arrayp final)
1836 ;; If requested, place the macro in the command history. For
1837 ;; other sorts of commands, call-interactively takes care of this.
1838 (when record-flag
1839 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1840 ;; Don't keep command history around forever.
1841 (when (and (numberp history-length) (> history-length 0))
1842 (let ((cell (nthcdr history-length command-history)))
1843 (if (consp cell) (setcdr cell nil)))))
1844 (execute-kbd-macro final prefixarg))
1846 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1847 (prog1 (call-interactively cmd record-flag keys)
1848 (when (and (symbolp cmd)
1849 (get cmd 'byte-obsolete-info)
1850 (not (get cmd 'command-execute-obsolete-warned)))
1851 (put cmd 'command-execute-obsolete-warned t)
1852 (message "%s" (macroexp--obsolete-warning
1853 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1855 (defvar minibuffer-history nil
1856 "Default minibuffer history list.
1857 This is used for all minibuffer input
1858 except when an alternate history list is specified.
1860 Maximum length of the history list is determined by the value
1861 of `history-length', which see.")
1862 (defvar minibuffer-history-sexp-flag nil
1863 "Control whether history list elements are expressions or strings.
1864 If the value of this variable equals current minibuffer depth,
1865 they are expressions; otherwise they are strings.
1866 \(That convention is designed to do the right thing for
1867 recursive uses of the minibuffer.)")
1868 (setq minibuffer-history-variable 'minibuffer-history)
1869 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1870 (defvar minibuffer-history-search-history nil)
1872 (defvar minibuffer-text-before-history nil
1873 "Text that was in this minibuffer before any history commands.
1874 This is nil if there have not yet been any history commands
1875 in this use of the minibuffer.")
1877 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1879 (defun minibuffer-history-initialize ()
1880 (setq minibuffer-text-before-history nil))
1882 (defun minibuffer-avoid-prompt (_new _old)
1883 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1884 (declare (obsolete cursor-intangible-mode "25.1"))
1885 (constrain-to-field nil (point-max)))
1887 (defcustom minibuffer-history-case-insensitive-variables nil
1888 "Minibuffer history variables for which matching should ignore case.
1889 If a history variable is a member of this list, then the
1890 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1891 commands ignore case when searching it, regardless of `case-fold-search'."
1892 :type '(repeat variable)
1893 :group 'minibuffer)
1895 (defun previous-matching-history-element (regexp n)
1896 "Find the previous history element that matches REGEXP.
1897 \(Previous history elements refer to earlier actions.)
1898 With prefix argument N, search for Nth previous match.
1899 If N is negative, find the next or Nth next match.
1900 Normally, history elements are matched case-insensitively if
1901 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1902 makes the search case-sensitive.
1903 See also `minibuffer-history-case-insensitive-variables'."
1904 (interactive
1905 (let* ((enable-recursive-minibuffers t)
1906 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1908 minibuffer-local-map
1910 'minibuffer-history-search-history
1911 (car minibuffer-history-search-history))))
1912 ;; Use the last regexp specified, by default, if input is empty.
1913 (list (if (string= regexp "")
1914 (if minibuffer-history-search-history
1915 (car minibuffer-history-search-history)
1916 (user-error "No previous history search regexp"))
1917 regexp)
1918 (prefix-numeric-value current-prefix-arg))))
1919 (unless (zerop n)
1920 (if (and (zerop minibuffer-history-position)
1921 (null minibuffer-text-before-history))
1922 (setq minibuffer-text-before-history
1923 (minibuffer-contents-no-properties)))
1924 (let ((history (symbol-value minibuffer-history-variable))
1925 (case-fold-search
1926 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1927 ;; On some systems, ignore case for file names.
1928 (if (memq minibuffer-history-variable
1929 minibuffer-history-case-insensitive-variables)
1931 ;; Respect the user's setting for case-fold-search:
1932 case-fold-search)
1933 nil))
1934 prevpos
1935 match-string
1936 match-offset
1937 (pos minibuffer-history-position))
1938 (while (/= n 0)
1939 (setq prevpos pos)
1940 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1941 (when (= pos prevpos)
1942 (user-error (if (= pos 1)
1943 "No later matching history item"
1944 "No earlier matching history item")))
1945 (setq match-string
1946 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1947 (let ((print-level nil))
1948 (prin1-to-string (nth (1- pos) history)))
1949 (nth (1- pos) history)))
1950 (setq match-offset
1951 (if (< n 0)
1952 (and (string-match regexp match-string)
1953 (match-end 0))
1954 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1955 (match-beginning 1))))
1956 (when match-offset
1957 (setq n (+ n (if (< n 0) 1 -1)))))
1958 (setq minibuffer-history-position pos)
1959 (goto-char (point-max))
1960 (delete-minibuffer-contents)
1961 (insert match-string)
1962 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1963 (if (memq (car (car command-history)) '(previous-matching-history-element
1964 next-matching-history-element))
1965 (setq command-history (cdr command-history))))
1967 (defun next-matching-history-element (regexp n)
1968 "Find the next history element that matches REGEXP.
1969 \(The next history element refers to a more recent action.)
1970 With prefix argument N, search for Nth next match.
1971 If N is negative, find the previous or Nth previous match.
1972 Normally, history elements are matched case-insensitively if
1973 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1974 makes the search case-sensitive."
1975 (interactive
1976 (let* ((enable-recursive-minibuffers t)
1977 (regexp (read-from-minibuffer "Next element matching (regexp): "
1979 minibuffer-local-map
1981 'minibuffer-history-search-history
1982 (car minibuffer-history-search-history))))
1983 ;; Use the last regexp specified, by default, if input is empty.
1984 (list (if (string= regexp "")
1985 (if minibuffer-history-search-history
1986 (car minibuffer-history-search-history)
1987 (user-error "No previous history search regexp"))
1988 regexp)
1989 (prefix-numeric-value current-prefix-arg))))
1990 (previous-matching-history-element regexp (- n)))
1992 (defvar minibuffer-temporary-goal-position nil)
1994 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1995 "Function run by `goto-history-element' before consuming default values.
1996 This is useful to dynamically add more elements to the list of default values
1997 when `goto-history-element' reaches the end of this list.
1998 Before calling this function `goto-history-element' sets the variable
1999 `minibuffer-default-add-done' to t, so it will call this function only
2000 once. In special cases, when this function needs to be called more
2001 than once, it can set `minibuffer-default-add-done' to nil explicitly,
2002 overriding the setting of this variable to t in `goto-history-element'.")
2004 (defvar minibuffer-default-add-done nil
2005 "When nil, add more elements to the end of the list of default values.
2006 The value nil causes `goto-history-element' to add more elements to
2007 the list of defaults when it reaches the end of this list. It does
2008 this by calling a function defined by `minibuffer-default-add-function'.")
2010 (make-variable-buffer-local 'minibuffer-default-add-done)
2012 (defun minibuffer-default-add-completions ()
2013 "Return a list of all completions without the default value.
2014 This function is used to add all elements of the completion table to
2015 the end of the list of defaults just after the default value."
2016 (let ((def minibuffer-default)
2017 (all (all-completions ""
2018 minibuffer-completion-table
2019 minibuffer-completion-predicate)))
2020 (if (listp def)
2021 (append def all)
2022 (cons def (delete def all)))))
2024 (defun goto-history-element (nabs)
2025 "Puts element of the minibuffer history in the minibuffer.
2026 The argument NABS specifies the absolute history position."
2027 (interactive "p")
2028 (when (and (not minibuffer-default-add-done)
2029 (functionp minibuffer-default-add-function)
2030 (< nabs (- (if (listp minibuffer-default)
2031 (length minibuffer-default)
2032 1))))
2033 (setq minibuffer-default-add-done t
2034 minibuffer-default (funcall minibuffer-default-add-function)))
2035 (let ((minimum (if minibuffer-default
2036 (- (if (listp minibuffer-default)
2037 (length minibuffer-default)
2040 elt minibuffer-returned-to-present)
2041 (if (and (zerop minibuffer-history-position)
2042 (null minibuffer-text-before-history))
2043 (setq minibuffer-text-before-history
2044 (minibuffer-contents-no-properties)))
2045 (if (< nabs minimum)
2046 (user-error (if minibuffer-default
2047 "End of defaults; no next item"
2048 "End of history; no default available")))
2049 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
2050 (length (symbol-value minibuffer-history-variable))
2052 (user-error "Beginning of history; no preceding item"))
2053 (unless (memq last-command '(next-history-element
2054 previous-history-element))
2055 (let ((prompt-end (minibuffer-prompt-end)))
2056 (set (make-local-variable 'minibuffer-temporary-goal-position)
2057 (cond ((<= (point) prompt-end) prompt-end)
2058 ((eobp) nil)
2059 (t (point))))))
2060 (goto-char (point-max))
2061 (delete-minibuffer-contents)
2062 (setq minibuffer-history-position nabs)
2063 (cond ((< nabs 0)
2064 (setq elt (if (listp minibuffer-default)
2065 (nth (1- (abs nabs)) minibuffer-default)
2066 minibuffer-default)))
2067 ((= nabs 0)
2068 (setq elt (or minibuffer-text-before-history ""))
2069 (setq minibuffer-returned-to-present t)
2070 (setq minibuffer-text-before-history nil))
2071 (t (setq elt (nth (1- minibuffer-history-position)
2072 (symbol-value minibuffer-history-variable)))))
2073 (insert
2074 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2075 (not minibuffer-returned-to-present))
2076 (let ((print-level nil))
2077 (prin1-to-string elt))
2078 elt))
2079 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2081 (defun next-history-element (n)
2082 "Puts next element of the minibuffer history in the minibuffer.
2083 With argument N, it uses the Nth following element."
2084 (interactive "p")
2085 (or (zerop n)
2086 (goto-history-element (- minibuffer-history-position n))))
2088 (defun previous-history-element (n)
2089 "Puts previous element of the minibuffer history in the minibuffer.
2090 With argument N, it uses the Nth previous element."
2091 (interactive "p")
2092 (or (zerop n)
2093 (goto-history-element (+ minibuffer-history-position n))))
2095 (defun next-line-or-history-element (&optional arg)
2096 "Move cursor vertically down ARG lines, or to the next history element.
2097 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2098 next element of the minibuffer history in the minibuffer."
2099 (interactive "^p")
2100 (or arg (setq arg 1))
2101 (let* ((old-point (point))
2102 ;; Remember the original goal column of possibly multi-line input
2103 ;; excluding the length of the prompt on the first line.
2104 (prompt-end (minibuffer-prompt-end))
2105 (old-column (unless (and (eolp) (> (point) prompt-end))
2106 (if (= (line-number-at-pos) 1)
2107 (max (- (current-column) (1- prompt-end)) 0)
2108 (current-column)))))
2109 (condition-case nil
2110 (with-no-warnings
2111 (next-line arg))
2112 (end-of-buffer
2113 ;; Restore old position since `line-move-visual' moves point to
2114 ;; the end of the line when it fails to go to the next line.
2115 (goto-char old-point)
2116 (next-history-element arg)
2117 ;; Reset `temporary-goal-column' because a correct value is not
2118 ;; calculated when `next-line' above fails by bumping against
2119 ;; the bottom of the minibuffer (bug#22544).
2120 (setq temporary-goal-column 0)
2121 ;; Restore the original goal column on the last line
2122 ;; of possibly multi-line input.
2123 (goto-char (point-max))
2124 (when old-column
2125 (if (= (line-number-at-pos) 1)
2126 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2127 (move-to-column old-column)))))))
2129 (defun previous-line-or-history-element (&optional arg)
2130 "Move cursor vertically up ARG lines, or to the previous history element.
2131 When point moves over the top line of multi-line minibuffer, puts ARGth
2132 previous element of the minibuffer history in the minibuffer."
2133 (interactive "^p")
2134 (or arg (setq arg 1))
2135 (let* ((old-point (point))
2136 ;; Remember the original goal column of possibly multi-line input
2137 ;; excluding the length of the prompt on the first line.
2138 (prompt-end (minibuffer-prompt-end))
2139 (old-column (unless (and (eolp) (> (point) prompt-end))
2140 (if (= (line-number-at-pos) 1)
2141 (max (- (current-column) (1- prompt-end)) 0)
2142 (current-column)))))
2143 (condition-case nil
2144 (with-no-warnings
2145 (previous-line arg))
2146 (beginning-of-buffer
2147 ;; Restore old position since `line-move-visual' moves point to
2148 ;; the beginning of the line when it fails to go to the previous line.
2149 (goto-char old-point)
2150 (previous-history-element arg)
2151 ;; Reset `temporary-goal-column' because a correct value is not
2152 ;; calculated when `previous-line' above fails by bumping against
2153 ;; the top of the minibuffer (bug#22544).
2154 (setq temporary-goal-column 0)
2155 ;; Restore the original goal column on the first line
2156 ;; of possibly multi-line input.
2157 (goto-char (minibuffer-prompt-end))
2158 (if old-column
2159 (if (= (line-number-at-pos) 1)
2160 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2161 (move-to-column old-column))
2162 ;; Put the cursor at the end of the visual line instead of the
2163 ;; logical line, so the next `previous-line-or-history-element'
2164 ;; would move to the previous history element, not to a possible upper
2165 ;; visual line from the end of logical line in `line-move-visual' mode.
2166 (end-of-visual-line)
2167 ;; Since `end-of-visual-line' puts the cursor at the beginning
2168 ;; of the next visual line, move it one char back to the end
2169 ;; of the first visual line (bug#22544).
2170 (unless (eolp) (backward-char 1)))))))
2172 (defun next-complete-history-element (n)
2173 "Get next history element which completes the minibuffer before the point.
2174 The contents of the minibuffer after the point are deleted, and replaced
2175 by the new completion."
2176 (interactive "p")
2177 (let ((point-at-start (point)))
2178 (next-matching-history-element
2179 (concat
2180 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2182 ;; next-matching-history-element always puts us at (point-min).
2183 ;; Move to the position we were at before changing the buffer contents.
2184 ;; This is still sensible, because the text before point has not changed.
2185 (goto-char point-at-start)))
2187 (defun previous-complete-history-element (n)
2189 Get previous history element which completes the minibuffer before the point.
2190 The contents of the minibuffer after the point are deleted, and replaced
2191 by the new completion."
2192 (interactive "p")
2193 (next-complete-history-element (- n)))
2195 ;; For compatibility with the old subr of the same name.
2196 (defun minibuffer-prompt-width ()
2197 "Return the display width of the minibuffer prompt.
2198 Return 0 if current buffer is not a minibuffer."
2199 ;; Return the width of everything before the field at the end of
2200 ;; the buffer; this should be 0 for normal buffers.
2201 (1- (minibuffer-prompt-end)))
2203 ;; isearch minibuffer history
2204 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2206 (defvar minibuffer-history-isearch-message-overlay)
2207 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2209 (defun minibuffer-history-isearch-setup ()
2210 "Set up a minibuffer for using isearch to search the minibuffer history.
2211 Intended to be added to `minibuffer-setup-hook'."
2212 (set (make-local-variable 'isearch-search-fun-function)
2213 'minibuffer-history-isearch-search)
2214 (set (make-local-variable 'isearch-message-function)
2215 'minibuffer-history-isearch-message)
2216 (set (make-local-variable 'isearch-wrap-function)
2217 'minibuffer-history-isearch-wrap)
2218 (set (make-local-variable 'isearch-push-state-function)
2219 'minibuffer-history-isearch-push-state)
2220 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2222 (defun minibuffer-history-isearch-end ()
2223 "Clean up the minibuffer after terminating isearch in the minibuffer."
2224 (if minibuffer-history-isearch-message-overlay
2225 (delete-overlay minibuffer-history-isearch-message-overlay)))
2227 (defun minibuffer-history-isearch-search ()
2228 "Return the proper search function, for isearch in minibuffer history."
2229 (lambda (string bound noerror)
2230 (let ((search-fun
2231 ;; Use standard functions to search within minibuffer text
2232 (isearch-search-fun-default))
2233 found)
2234 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2235 ;; searching forward. Lazy-highlight calls this lambda with the
2236 ;; bound arg, so skip the minibuffer prompt.
2237 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2238 (goto-char (minibuffer-prompt-end)))
2240 ;; 1. First try searching in the initial minibuffer text
2241 (funcall search-fun string
2242 (if isearch-forward bound (minibuffer-prompt-end))
2243 noerror)
2244 ;; 2. If the above search fails, start putting next/prev history
2245 ;; elements in the minibuffer successively, and search the string
2246 ;; in them. Do this only when bound is nil (i.e. not while
2247 ;; lazy-highlighting search strings in the current minibuffer text).
2248 (unless bound
2249 (condition-case nil
2250 (progn
2251 (while (not found)
2252 (cond (isearch-forward
2253 (next-history-element 1)
2254 (goto-char (minibuffer-prompt-end)))
2256 (previous-history-element 1)
2257 (goto-char (point-max))))
2258 (setq isearch-barrier (point) isearch-opoint (point))
2259 ;; After putting the next/prev history element, search
2260 ;; the string in them again, until next-history-element
2261 ;; or previous-history-element raises an error at the
2262 ;; beginning/end of history.
2263 (setq found (funcall search-fun string
2264 (unless isearch-forward
2265 ;; For backward search, don't search
2266 ;; in the minibuffer prompt
2267 (minibuffer-prompt-end))
2268 noerror)))
2269 ;; Return point of the new search result
2270 (point))
2271 ;; Return nil when next(prev)-history-element fails
2272 (error nil)))))))
2274 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2275 "Display the minibuffer history search prompt.
2276 If there are no search errors, this function displays an overlay with
2277 the isearch prompt which replaces the original minibuffer prompt.
2278 Otherwise, it displays the standard isearch message returned from
2279 the function `isearch-message'."
2280 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2281 ;; Use standard function `isearch-message' when not in the minibuffer,
2282 ;; or search fails, or has an error (like incomplete regexp).
2283 ;; This function overwrites minibuffer text with isearch message,
2284 ;; so it's possible to see what is wrong in the search string.
2285 (isearch-message c-q-hack ellipsis)
2286 ;; Otherwise, put the overlay with the standard isearch prompt over
2287 ;; the initial minibuffer prompt.
2288 (if (overlayp minibuffer-history-isearch-message-overlay)
2289 (move-overlay minibuffer-history-isearch-message-overlay
2290 (point-min) (minibuffer-prompt-end))
2291 (setq minibuffer-history-isearch-message-overlay
2292 (make-overlay (point-min) (minibuffer-prompt-end)))
2293 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2294 (overlay-put minibuffer-history-isearch-message-overlay
2295 'display (isearch-message-prefix c-q-hack ellipsis))
2296 ;; And clear any previous isearch message.
2297 (message "")))
2299 (defun minibuffer-history-isearch-wrap ()
2300 "Wrap the minibuffer history search when search fails.
2301 Move point to the first history element for a forward search,
2302 or to the last history element for a backward search."
2303 ;; When `minibuffer-history-isearch-search' fails on reaching the
2304 ;; beginning/end of the history, wrap the search to the first/last
2305 ;; minibuffer history element.
2306 (if isearch-forward
2307 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2308 (goto-history-element 0))
2309 (setq isearch-success t)
2310 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2312 (defun minibuffer-history-isearch-push-state ()
2313 "Save a function restoring the state of minibuffer history search.
2314 Save `minibuffer-history-position' to the additional state parameter
2315 in the search status stack."
2316 (let ((pos minibuffer-history-position))
2317 (lambda (cmd)
2318 (minibuffer-history-isearch-pop-state cmd pos))))
2320 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2321 "Restore the minibuffer history search state.
2322 Go to the history element by the absolute history position HIST-POS."
2323 (goto-history-element hist-pos))
2326 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2327 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2329 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2330 "Table mapping redo records to the corresponding undo one.
2331 A redo record for undo-in-region maps to t.
2332 A redo record for ordinary undo maps to the following (earlier) undo.")
2334 (defvar undo-in-region nil
2335 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2337 (defvar undo-no-redo nil
2338 "If t, `undo' doesn't go through redo entries.")
2340 (defvar pending-undo-list nil
2341 "Within a run of consecutive undo commands, list remaining to be undone.
2342 If t, we undid all the way to the end of it.")
2344 (defun undo (&optional arg)
2345 "Undo some previous changes.
2346 Repeat this command to undo more changes.
2347 A numeric ARG serves as a repeat count.
2349 In Transient Mark mode when the mark is active, only undo changes within
2350 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2351 as an argument limits undo to changes within the current region."
2352 (interactive "*P")
2353 ;; Make last-command indicate for the next command that this was an undo.
2354 ;; That way, another undo will undo more.
2355 ;; If we get to the end of the undo history and get an error,
2356 ;; another undo command will find the undo history empty
2357 ;; and will get another error. To begin undoing the undos,
2358 ;; you must type some other command.
2359 (let* ((modified (buffer-modified-p))
2360 ;; For an indirect buffer, look in the base buffer for the
2361 ;; auto-save data.
2362 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2363 (recent-save (with-current-buffer base-buffer
2364 (recent-auto-save-p)))
2365 message)
2366 ;; If we get an error in undo-start,
2367 ;; the next command should not be a "consecutive undo".
2368 ;; So set `this-command' to something other than `undo'.
2369 (setq this-command 'undo-start)
2371 (unless (and (eq last-command 'undo)
2372 (or (eq pending-undo-list t)
2373 ;; If something (a timer or filter?) changed the buffer
2374 ;; since the previous command, don't continue the undo seq.
2375 (let ((list buffer-undo-list))
2376 (while (eq (car list) nil)
2377 (setq list (cdr list)))
2378 ;; If the last undo record made was made by undo
2379 ;; it shows nothing else happened in between.
2380 (gethash list undo-equiv-table))))
2381 (setq undo-in-region
2382 (or (region-active-p) (and arg (not (numberp arg)))))
2383 (if undo-in-region
2384 (undo-start (region-beginning) (region-end))
2385 (undo-start))
2386 ;; get rid of initial undo boundary
2387 (undo-more 1))
2388 ;; If we got this far, the next command should be a consecutive undo.
2389 (setq this-command 'undo)
2390 ;; Check to see whether we're hitting a redo record, and if
2391 ;; so, ask the user whether she wants to skip the redo/undo pair.
2392 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2393 (or (eq (selected-window) (minibuffer-window))
2394 (setq message (format "%s%s!"
2395 (if (or undo-no-redo (not equiv))
2396 "Undo" "Redo")
2397 (if undo-in-region " in region" ""))))
2398 (when (and (consp equiv) undo-no-redo)
2399 ;; The equiv entry might point to another redo record if we have done
2400 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2401 (while (let ((next (gethash equiv undo-equiv-table)))
2402 (if next (setq equiv next))))
2403 (setq pending-undo-list equiv)))
2404 (undo-more
2405 (if (numberp arg)
2406 (prefix-numeric-value arg)
2408 ;; Record the fact that the just-generated undo records come from an
2409 ;; undo operation--that is, they are redo records.
2410 ;; In the ordinary case (not within a region), map the redo
2411 ;; record to the following undos.
2412 ;; I don't know how to do that in the undo-in-region case.
2413 (let ((list buffer-undo-list))
2414 ;; Strip any leading undo boundaries there might be, like we do
2415 ;; above when checking.
2416 (while (eq (car list) nil)
2417 (setq list (cdr list)))
2418 (puthash list
2419 ;; Prevent identity mapping. This can happen if
2420 ;; consecutive nils are erroneously in undo list.
2421 (if (or undo-in-region (eq list pending-undo-list))
2423 pending-undo-list)
2424 undo-equiv-table))
2425 ;; Don't specify a position in the undo record for the undo command.
2426 ;; Instead, undoing this should move point to where the change is.
2427 (let ((tail buffer-undo-list)
2428 (prev nil))
2429 (while (car tail)
2430 (when (integerp (car tail))
2431 (let ((pos (car tail)))
2432 (if prev
2433 (setcdr prev (cdr tail))
2434 (setq buffer-undo-list (cdr tail)))
2435 (setq tail (cdr tail))
2436 (while (car tail)
2437 (if (eq pos (car tail))
2438 (if prev
2439 (setcdr prev (cdr tail))
2440 (setq buffer-undo-list (cdr tail)))
2441 (setq prev tail))
2442 (setq tail (cdr tail)))
2443 (setq tail nil)))
2444 (setq prev tail tail (cdr tail))))
2445 ;; Record what the current undo list says,
2446 ;; so the next command can tell if the buffer was modified in between.
2447 (and modified (not (buffer-modified-p))
2448 (with-current-buffer base-buffer
2449 (delete-auto-save-file-if-necessary recent-save)))
2450 ;; Display a message announcing success.
2451 (if message
2452 (message "%s" message))))
2454 (defun buffer-disable-undo (&optional buffer)
2455 "Make BUFFER stop keeping undo information.
2456 No argument or nil as argument means do this for the current buffer."
2457 (interactive)
2458 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2459 (setq buffer-undo-list t)))
2461 (defun undo-only (&optional arg)
2462 "Undo some previous changes.
2463 Repeat this command to undo more changes.
2464 A numeric ARG serves as a repeat count.
2465 Contrary to `undo', this will not redo a previous undo."
2466 (interactive "*p")
2467 (let ((undo-no-redo t)) (undo arg)))
2469 (defvar undo-in-progress nil
2470 "Non-nil while performing an undo.
2471 Some change-hooks test this variable to do something different.")
2473 (defun undo-more (n)
2474 "Undo back N undo-boundaries beyond what was already undone recently.
2475 Call `undo-start' to get ready to undo recent changes,
2476 then call `undo-more' one or more times to undo them."
2477 (or (listp pending-undo-list)
2478 (user-error (concat "No further undo information"
2479 (and undo-in-region " for region"))))
2480 (let ((undo-in-progress t))
2481 ;; Note: The following, while pulling elements off
2482 ;; `pending-undo-list' will call primitive change functions which
2483 ;; will push more elements onto `buffer-undo-list'.
2484 (setq pending-undo-list (primitive-undo n pending-undo-list))
2485 (if (null pending-undo-list)
2486 (setq pending-undo-list t))))
2488 (defun primitive-undo (n list)
2489 "Undo N records from the front of the list LIST.
2490 Return what remains of the list."
2492 ;; This is a good feature, but would make undo-start
2493 ;; unable to do what is expected.
2494 ;;(when (null (car (list)))
2495 ;; ;; If the head of the list is a boundary, it is the boundary
2496 ;; ;; preceding this command. Get rid of it and don't count it.
2497 ;; (setq list (cdr list))))
2499 (let ((arg n)
2500 ;; In a writable buffer, enable undoing read-only text that is
2501 ;; so because of text properties.
2502 (inhibit-read-only t)
2503 ;; Don't let `intangible' properties interfere with undo.
2504 (inhibit-point-motion-hooks t)
2505 ;; We use oldlist only to check for EQ. ++kfs
2506 (oldlist buffer-undo-list)
2507 (did-apply nil)
2508 (next nil))
2509 (while (> arg 0)
2510 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2511 ;; Handle an integer by setting point to that value.
2512 (pcase next
2513 ((pred integerp) (goto-char next))
2514 ;; Element (t . TIME) records previous modtime.
2515 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2516 ;; UNKNOWN_MODTIME_NSECS.
2517 (`(t . ,time)
2518 ;; If this records an obsolete save
2519 ;; (not matching the actual disk file)
2520 ;; then don't mark unmodified.
2521 (when (or (equal time (visited-file-modtime))
2522 (and (consp time)
2523 (equal (list (car time) (cdr time))
2524 (visited-file-modtime))))
2525 (when (fboundp 'unlock-buffer)
2526 (unlock-buffer))
2527 (set-buffer-modified-p nil)))
2528 ;; Element (nil PROP VAL BEG . END) is property change.
2529 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2530 (when (or (> (point-min) beg) (< (point-max) end))
2531 (error "Changes to be undone are outside visible portion of buffer"))
2532 (put-text-property beg end prop val))
2533 ;; Element (BEG . END) means range was inserted.
2534 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2535 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2536 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2537 (when (or (> (point-min) beg) (< (point-max) end))
2538 (error "Changes to be undone are outside visible portion of buffer"))
2539 ;; Set point first thing, so that undoing this undo
2540 ;; does not send point back to where it is now.
2541 (goto-char beg)
2542 (delete-region beg end))
2543 ;; Element (apply FUN . ARGS) means call FUN to undo.
2544 (`(apply . ,fun-args)
2545 (let ((currbuff (current-buffer)))
2546 (if (integerp (car fun-args))
2547 ;; Long format: (apply DELTA START END FUN . ARGS).
2548 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2549 (start-mark (copy-marker start nil))
2550 (end-mark (copy-marker end t)))
2551 (when (or (> (point-min) start) (< (point-max) end))
2552 (error "Changes to be undone are outside visible portion of buffer"))
2553 (apply fun args) ;; Use `save-current-buffer'?
2554 ;; Check that the function did what the entry
2555 ;; said it would do.
2556 (unless (and (= start start-mark)
2557 (= (+ delta end) end-mark))
2558 (error "Changes to be undone by function different than announced"))
2559 (set-marker start-mark nil)
2560 (set-marker end-mark nil))
2561 (apply fun-args))
2562 (unless (eq currbuff (current-buffer))
2563 (error "Undo function switched buffer"))
2564 (setq did-apply t)))
2565 ;; Element (STRING . POS) means STRING was deleted.
2566 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2567 (when (let ((apos (abs pos)))
2568 (or (< apos (point-min)) (> apos (point-max))))
2569 (error "Changes to be undone are outside visible portion of buffer"))
2570 (let (valid-marker-adjustments)
2571 ;; Check that marker adjustments which were recorded
2572 ;; with the (STRING . POS) record are still valid, ie
2573 ;; the markers haven't moved. We check their validity
2574 ;; before reinserting the string so as we don't need to
2575 ;; mind marker insertion-type.
2576 (while (and (markerp (car-safe (car list)))
2577 (integerp (cdr-safe (car list))))
2578 (let* ((marker-adj (pop list))
2579 (m (car marker-adj)))
2580 (and (eq (marker-buffer m) (current-buffer))
2581 (= pos m)
2582 (push marker-adj valid-marker-adjustments))))
2583 ;; Insert string and adjust point
2584 (if (< pos 0)
2585 (progn
2586 (goto-char (- pos))
2587 (insert string))
2588 (goto-char pos)
2589 (insert string)
2590 (goto-char pos))
2591 ;; Adjust the valid marker adjustments
2592 (dolist (adj valid-marker-adjustments)
2593 ;; Insert might have invalidated some of the markers
2594 ;; via modification hooks. Update only the currently
2595 ;; valid ones (bug#25599).
2596 (if (marker-buffer (car adj))
2597 (set-marker (car adj)
2598 (- (car adj) (cdr adj)))))))
2599 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2600 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2601 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2602 next)
2603 ;; Even though these elements are not expected in the undo
2604 ;; list, adjust them to be conservative for the 24.4
2605 ;; release. (Bug#16818)
2606 (when (marker-buffer marker)
2607 (set-marker marker
2608 (- marker offset)
2609 (marker-buffer marker))))
2610 (_ (error "Unrecognized entry in undo list %S" next))))
2611 (setq arg (1- arg)))
2612 ;; Make sure an apply entry produces at least one undo entry,
2613 ;; so the test in `undo' for continuing an undo series
2614 ;; will work right.
2615 (if (and did-apply
2616 (eq oldlist buffer-undo-list))
2617 (setq buffer-undo-list
2618 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2619 list)
2621 ;; Deep copy of a list
2622 (defun undo-copy-list (list)
2623 "Make a copy of undo list LIST."
2624 (mapcar 'undo-copy-list-1 list))
2626 (defun undo-copy-list-1 (elt)
2627 (if (consp elt)
2628 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2629 elt))
2631 (defun undo-start (&optional beg end)
2632 "Set `pending-undo-list' to the front of the undo list.
2633 The next call to `undo-more' will undo the most recently made change.
2634 If BEG and END are specified, then only undo elements
2635 that apply to text between BEG and END are used; other undo elements
2636 are ignored. If BEG and END are nil, all undo elements are used."
2637 (if (eq buffer-undo-list t)
2638 (user-error "No undo information in this buffer"))
2639 (setq pending-undo-list
2640 (if (and beg end (not (= beg end)))
2641 (undo-make-selective-list (min beg end) (max beg end))
2642 buffer-undo-list)))
2644 ;; The positions given in elements of the undo list are the positions
2645 ;; as of the time that element was recorded to undo history. In
2646 ;; general, subsequent buffer edits render those positions invalid in
2647 ;; the current buffer, unless adjusted according to the intervening
2648 ;; undo elements.
2650 ;; Undo in region is a use case that requires adjustments to undo
2651 ;; elements. It must adjust positions of elements in the region based
2652 ;; on newer elements not in the region so as they may be correctly
2653 ;; applied in the current buffer. undo-make-selective-list
2654 ;; accomplishes this with its undo-deltas list of adjustments. An
2655 ;; example undo history from oldest to newest:
2657 ;; buf pos:
2658 ;; 123456789 buffer-undo-list undo-deltas
2659 ;; --------- ---------------- -----------
2660 ;; aaa (1 . 4) (1 . -3)
2661 ;; aaba (3 . 4) N/A (in region)
2662 ;; ccaaba (1 . 3) (1 . -2)
2663 ;; ccaabaddd (7 . 10) (7 . -3)
2664 ;; ccaabdd ("ad" . 6) (6 . 2)
2665 ;; ccaabaddd (6 . 8) (6 . -2)
2666 ;; | |<-- region: "caab", from 2 to 6
2668 ;; When the user starts a run of undos in region,
2669 ;; undo-make-selective-list is called to create the full list of in
2670 ;; region elements. Each element is adjusted forward chronologically
2671 ;; through undo-deltas to determine if it is in the region.
2673 ;; In the above example, the insertion of "b" is (3 . 4) in the
2674 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2675 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2676 ;; . 6) is assessed as in the region and placed in the selective list.
2677 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2678 ;; due to the selected element. The "b" insertion is the only element
2679 ;; fully in the region, so in this example undo-make-selective-list
2680 ;; returns (nil (5 . 6)).
2682 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2683 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2684 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2685 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2686 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2688 ;; More interesting is how to adjust the "ddd" insertion due to the
2689 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2690 ;; If the reinsertion was a manual retyping of "ad", then the total
2691 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2692 ;; the reinsertion was due to undo, one might expect the first "d"
2693 ;; character would again be a part of the "ddd" text, meaning its
2694 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2696 ;; undo-make-selective-list assumes in this situation that "ad" was a
2697 ;; new edit, even if it was inserted because of an undo.
2698 ;; Consequently, if the user undos in region "8 to 10" of the
2699 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2700 ;; "ccaabad", as though the first "d" became detached from the
2701 ;; original "ddd" insertion. This quirk is a FIXME.
2703 (defun undo-make-selective-list (start end)
2704 "Return a list of undo elements for the region START to END.
2705 The elements come from `buffer-undo-list', but we keep only the
2706 elements inside this region, and discard those outside this
2707 region. The elements' positions are adjusted so as the returned
2708 list can be applied to the current buffer."
2709 (let ((ulist buffer-undo-list)
2710 ;; A list of position adjusted undo elements in the region.
2711 (selective-list (list nil))
2712 ;; A list of undo-deltas for out of region undo elements.
2713 undo-deltas
2714 undo-elt)
2715 (while ulist
2716 (when undo-no-redo
2717 (while (gethash ulist undo-equiv-table)
2718 (setq ulist (gethash ulist undo-equiv-table))))
2719 (setq undo-elt (car ulist))
2720 (cond
2721 ((null undo-elt)
2722 ;; Don't put two nils together in the list
2723 (when (car selective-list)
2724 (push nil selective-list)))
2725 ((and (consp undo-elt) (eq (car undo-elt) t))
2726 ;; This is a "was unmodified" element. Keep it
2727 ;; if we have kept everything thus far.
2728 (when (not undo-deltas)
2729 (push undo-elt selective-list)))
2730 ;; Skip over marker adjustments, instead relying
2731 ;; on finding them after (TEXT . POS) elements
2732 ((markerp (car-safe undo-elt))
2733 nil)
2735 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2736 undo-deltas)))
2737 (if (undo-elt-in-region adjusted-undo-elt start end)
2738 (progn
2739 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2740 (push adjusted-undo-elt selective-list)
2741 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2742 ;; kept. primitive-undo may discard them later.
2743 (when (and (stringp (car-safe adjusted-undo-elt))
2744 (integerp (cdr-safe adjusted-undo-elt)))
2745 (let ((list-i (cdr ulist)))
2746 (while (markerp (car-safe (car list-i)))
2747 (push (pop list-i) selective-list)))))
2748 (let ((delta (undo-delta undo-elt)))
2749 (when (/= 0 (cdr delta))
2750 (push delta undo-deltas)))))))
2751 (pop ulist))
2752 (nreverse selective-list)))
2754 (defun undo-elt-in-region (undo-elt start end)
2755 "Determine whether UNDO-ELT falls inside the region START ... END.
2756 If it crosses the edge, we return nil.
2758 Generally this function is not useful for determining
2759 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2760 because markers can be arbitrarily relocated. Instead, pass the
2761 marker adjustment's corresponding (TEXT . POS) element."
2762 (cond ((integerp undo-elt)
2763 (and (>= undo-elt start)
2764 (<= undo-elt end)))
2765 ((eq undo-elt nil)
2767 ((atom undo-elt)
2768 nil)
2769 ((stringp (car undo-elt))
2770 ;; (TEXT . POSITION)
2771 (and (>= (abs (cdr undo-elt)) start)
2772 (<= (abs (cdr undo-elt)) end)))
2773 ((and (consp undo-elt) (markerp (car undo-elt)))
2774 ;; (MARKER . ADJUSTMENT)
2775 (<= start (car undo-elt) end))
2776 ((null (car undo-elt))
2777 ;; (nil PROPERTY VALUE BEG . END)
2778 (let ((tail (nthcdr 3 undo-elt)))
2779 (and (>= (car tail) start)
2780 (<= (cdr tail) end))))
2781 ((integerp (car undo-elt))
2782 ;; (BEGIN . END)
2783 (and (>= (car undo-elt) start)
2784 (<= (cdr undo-elt) end)))))
2786 (defun undo-elt-crosses-region (undo-elt start end)
2787 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2788 This assumes we have already decided that UNDO-ELT
2789 is not *inside* the region START...END."
2790 (declare (obsolete nil "25.1"))
2791 (cond ((atom undo-elt) nil)
2792 ((null (car undo-elt))
2793 ;; (nil PROPERTY VALUE BEG . END)
2794 (let ((tail (nthcdr 3 undo-elt)))
2795 (and (< (car tail) end)
2796 (> (cdr tail) start))))
2797 ((integerp (car undo-elt))
2798 ;; (BEGIN . END)
2799 (and (< (car undo-elt) end)
2800 (> (cdr undo-elt) start)))))
2802 (defun undo-adjust-elt (elt deltas)
2803 "Return adjustment of undo element ELT by the undo DELTAS
2804 list."
2805 (pcase elt
2806 ;; POSITION
2807 ((pred integerp)
2808 (undo-adjust-pos elt deltas))
2809 ;; (BEG . END)
2810 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2811 (undo-adjust-beg-end beg end deltas))
2812 ;; (TEXT . POSITION)
2813 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2814 (cons text (* (if (< pos 0) -1 1)
2815 (undo-adjust-pos (abs pos) deltas))))
2816 ;; (nil PROPERTY VALUE BEG . END)
2817 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2818 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2819 ;; (apply DELTA START END FUN . ARGS)
2820 ;; FIXME
2821 ;; All others return same elt
2822 (_ elt)))
2824 ;; (BEG . END) can adjust to the same positions, commonly when an
2825 ;; insertion was undone and they are out of region, for example:
2827 ;; buf pos:
2828 ;; 123456789 buffer-undo-list undo-deltas
2829 ;; --------- ---------------- -----------
2830 ;; [...]
2831 ;; abbaa (2 . 4) (2 . -2)
2832 ;; aaa ("bb" . 2) (2 . 2)
2833 ;; [...]
2835 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2836 ;; undo. Further adjustments to such an element should be the same as
2837 ;; for (TEXT . POSITION) elements. The options are:
2839 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2840 ;; analogous to marker insertion-type t.
2842 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2843 ;; marker insertion-type nil.
2845 ;; There was no strong reason to prefer one or the other, except that
2846 ;; the first is more consistent with prior undo in region behavior.
2847 (defun undo-adjust-beg-end (beg end deltas)
2848 "Return cons of adjustments to BEG and END by the undo DELTAS
2849 list."
2850 (let ((adj-beg (undo-adjust-pos beg deltas)))
2851 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2852 (cons adj-beg
2853 (max adj-beg (undo-adjust-pos end deltas t)))))
2855 (defun undo-adjust-pos (pos deltas &optional use-<)
2856 "Return adjustment of POS by the undo DELTAS list, comparing
2857 with < or <= based on USE-<."
2858 (dolist (d deltas pos)
2859 (when (if use-<
2860 (< (car d) pos)
2861 (<= (car d) pos))
2862 (setq pos
2863 ;; Don't allow pos to become less than the undo-delta
2864 ;; position. This edge case is described in the overview
2865 ;; comments.
2866 (max (car d) (- pos (cdr d)))))))
2868 ;; Return the first affected buffer position and the delta for an undo element
2869 ;; delta is defined as the change in subsequent buffer positions if we *did*
2870 ;; the undo.
2871 (defun undo-delta (undo-elt)
2872 (if (consp undo-elt)
2873 (cond ((stringp (car undo-elt))
2874 ;; (TEXT . POSITION)
2875 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2876 ((integerp (car undo-elt))
2877 ;; (BEGIN . END)
2878 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2880 '(0 . 0)))
2881 '(0 . 0)))
2883 ;;; Default undo-boundary addition
2885 ;; This section adds a new undo-boundary at either after a command is
2886 ;; called or in some cases on a timer called after a change is made in
2887 ;; any buffer.
2888 (defvar-local undo-auto--last-boundary-cause nil
2889 "Describe the cause of the last undo-boundary.
2891 If `explicit', the last boundary was caused by an explicit call to
2892 `undo-boundary', that is one not called by the code in this
2893 section.
2895 If it is equal to `timer', then the last boundary was inserted
2896 by `undo-auto--boundary-timer'.
2898 If it is equal to `command', then the last boundary was inserted
2899 automatically after a command, that is by the code defined in
2900 this section.
2902 If it is equal to a list, then the last boundary was inserted by
2903 an amalgamating command. The car of the list is the number of
2904 times an amalgamating command has been called, and the cdr are the
2905 buffers that were changed during the last command.")
2907 (defvar undo-auto-current-boundary-timer nil
2908 "Current timer which will run `undo-auto--boundary-timer' or nil.
2910 If set to non-nil, this will effectively disable the timer.")
2912 (defvar undo-auto--this-command-amalgamating nil
2913 "Non-nil if `this-command' should be amalgamated.
2914 This variable is set to nil by `undo-auto--boundaries' and is set
2915 by `undo-auto-amalgamate'." )
2917 (defun undo-auto--needs-boundary-p ()
2918 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2919 (car-safe buffer-undo-list))
2921 (defun undo-auto--last-boundary-amalgamating-number ()
2922 "Return the number of amalgamating last commands or nil.
2923 Amalgamating commands are, by default, either
2924 `self-insert-command' and `delete-char', but can be any command
2925 that calls `undo-auto-amalgamate'."
2926 (car-safe undo-auto--last-boundary-cause))
2928 (defun undo-auto--ensure-boundary (cause)
2929 "Add an `undo-boundary' to the current buffer if needed.
2930 REASON describes the reason that the boundary is being added; see
2931 `undo-auto--last-boundary' for more information."
2932 (when (and
2933 (undo-auto--needs-boundary-p))
2934 (let ((last-amalgamating
2935 (undo-auto--last-boundary-amalgamating-number)))
2936 (undo-boundary)
2937 (setq undo-auto--last-boundary-cause
2938 (if (eq 'amalgamate cause)
2939 (cons
2940 (if last-amalgamating (1+ last-amalgamating) 0)
2941 undo-auto--undoably-changed-buffers)
2942 cause)))))
2944 (defun undo-auto--boundaries (cause)
2945 "Check recently changed buffers and add a boundary if necessary.
2946 REASON describes the reason that the boundary is being added; see
2947 `undo-last-boundary' for more information."
2948 ;; (Bug #23785) All commands should ensure that there is an undo
2949 ;; boundary whether they have changed the current buffer or not.
2950 (when (eq cause 'command)
2951 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2952 (dolist (b undo-auto--undoably-changed-buffers)
2953 (when (buffer-live-p b)
2954 (with-current-buffer b
2955 (undo-auto--ensure-boundary cause))))
2956 (setq undo-auto--undoably-changed-buffers nil))
2958 (defun undo-auto--boundary-timer ()
2959 "Timer which will run `undo--auto-boundary-timer'."
2960 (setq undo-auto-current-boundary-timer nil)
2961 (undo-auto--boundaries 'timer))
2963 (defun undo-auto--boundary-ensure-timer ()
2964 "Ensure that the `undo-auto-boundary-timer' is set."
2965 (unless undo-auto-current-boundary-timer
2966 (setq undo-auto-current-boundary-timer
2967 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2969 (defvar undo-auto--undoably-changed-buffers nil
2970 "List of buffers that have changed recently.
2972 This list is maintained by `undo-auto--undoable-change' and
2973 `undo-auto--boundaries' and can be affected by changes to their
2974 default values.")
2976 (defun undo-auto--add-boundary ()
2977 "Add an `undo-boundary' in appropriate buffers."
2978 (undo-auto--boundaries
2979 (let ((amal undo-auto--this-command-amalgamating))
2980 (setq undo-auto--this-command-amalgamating nil)
2981 (if amal
2982 'amalgamate
2983 'command))))
2985 (defun undo-auto-amalgamate ()
2986 "Amalgamate undo if necessary.
2987 This function can be called before an amalgamating command. It
2988 removes the previous `undo-boundary' if a series of such calls
2989 have been made. By default `self-insert-command' and
2990 `delete-char' are the only amalgamating commands, although this
2991 function could be called by any command wishing to have this
2992 behavior."
2993 (let ((last-amalgamating-count
2994 (undo-auto--last-boundary-amalgamating-number)))
2995 (setq undo-auto--this-command-amalgamating t)
2996 (when
2997 last-amalgamating-count
2999 (and
3000 (< last-amalgamating-count 20)
3001 (eq this-command last-command))
3002 ;; Amalgamate all buffers that have changed.
3003 (dolist (b (cdr undo-auto--last-boundary-cause))
3004 (when (buffer-live-p b)
3005 (with-current-buffer
3007 (when
3008 ;; The head of `buffer-undo-list' is nil.
3009 ;; `car-safe' doesn't work because
3010 ;; `buffer-undo-list' need not be a list!
3011 (and (listp buffer-undo-list)
3012 (not (car buffer-undo-list)))
3013 (setq buffer-undo-list
3014 (cdr buffer-undo-list))))))
3015 (setq undo-auto--last-boundary-cause 0)))))
3017 (defun undo-auto--undoable-change ()
3018 "Called after every undoable buffer change."
3019 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
3020 (undo-auto--boundary-ensure-timer))
3021 ;; End auto-boundary section
3023 (defun undo-amalgamate-change-group (handle)
3024 "Amalgamate changes in change-group since HANDLE.
3025 Remove all undo boundaries between the state of HANDLE and now.
3026 HANDLE is as returned by `prepare-change-group'."
3027 (dolist (elt handle)
3028 (with-current-buffer (car elt)
3029 (setq elt (cdr elt))
3030 (when (consp buffer-undo-list)
3031 (let ((old-car (car-safe elt))
3032 (old-cdr (cdr-safe elt)))
3033 (unwind-protect
3034 (progn
3035 ;; Temporarily truncate the undo log at ELT.
3036 (when (consp elt)
3037 (setcar elt t) (setcdr elt nil))
3038 (when
3039 (or (null elt) ;The undo-log was empty.
3040 ;; `elt' is still in the log: normal case.
3041 (eq elt (last buffer-undo-list))
3042 ;; `elt' is not in the log any more, but that's because
3043 ;; the log is "all new", so we should remove all
3044 ;; boundaries from it.
3045 (not (eq (last buffer-undo-list) (last old-cdr))))
3046 (cl-callf (lambda (x) (delq nil x))
3047 (if (car buffer-undo-list)
3048 buffer-undo-list
3049 ;; Preserve the undo-boundaries at either ends of the
3050 ;; change-groups.
3051 (cdr buffer-undo-list)))))
3052 ;; Reset the modified cons cell ELT to its original content.
3053 (when (consp elt)
3054 (setcar elt old-car)
3055 (setcdr elt old-cdr))))))))
3058 (defcustom undo-ask-before-discard nil
3059 "If non-nil ask about discarding undo info for the current command.
3060 Normally, Emacs discards the undo info for the current command if
3061 it exceeds `undo-outer-limit'. But if you set this option
3062 non-nil, it asks in the echo area whether to discard the info.
3063 If you answer no, there is a slight risk that Emacs might crash, so
3064 only do it if you really want to undo the command.
3066 This option is mainly intended for debugging. You have to be
3067 careful if you use it for other purposes. Garbage collection is
3068 inhibited while the question is asked, meaning that Emacs might
3069 leak memory. So you should make sure that you do not wait
3070 excessively long before answering the question."
3071 :type 'boolean
3072 :group 'undo
3073 :version "22.1")
3075 (defvar undo-extra-outer-limit nil
3076 "If non-nil, an extra level of size that's ok in an undo item.
3077 We don't ask the user about truncating the undo list until the
3078 current item gets bigger than this amount.
3080 This variable only matters if `undo-ask-before-discard' is non-nil.")
3081 (make-variable-buffer-local 'undo-extra-outer-limit)
3083 ;; When the first undo batch in an undo list is longer than
3084 ;; undo-outer-limit, this function gets called to warn the user that
3085 ;; the undo info for the current command was discarded. Garbage
3086 ;; collection is inhibited around the call, so it had better not do a
3087 ;; lot of consing.
3088 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3089 (defun undo-outer-limit-truncate (size)
3090 (if undo-ask-before-discard
3091 (when (or (null undo-extra-outer-limit)
3092 (> size undo-extra-outer-limit))
3093 ;; Don't ask the question again unless it gets even bigger.
3094 ;; This applies, in particular, if the user quits from the question.
3095 ;; Such a quit quits out of GC, but something else will call GC
3096 ;; again momentarily. It will call this function again,
3097 ;; but we don't want to ask the question again.
3098 (setq undo-extra-outer-limit (+ size 50000))
3099 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3100 (yes-or-no-p (format-message
3101 "Buffer `%s' undo info is %d bytes long; discard it? "
3102 (buffer-name) size)))
3103 (progn (setq buffer-undo-list nil)
3104 (setq undo-extra-outer-limit nil)
3106 nil))
3107 (display-warning '(undo discard-info)
3108 (concat
3109 (format-message
3110 "Buffer `%s' undo info was %d bytes long.\n"
3111 (buffer-name) size)
3112 "The undo info was discarded because it exceeded \
3113 `undo-outer-limit'.
3115 This is normal if you executed a command that made a huge change
3116 to the buffer. In that case, to prevent similar problems in the
3117 future, set `undo-outer-limit' to a value that is large enough to
3118 cover the maximum size of normal changes you expect a single
3119 command to make, but not so large that it might exceed the
3120 maximum memory allotted to Emacs.
3122 If you did not execute any such command, the situation is
3123 probably due to a bug and you should report it.
3125 You can disable the popping up of this buffer by adding the entry
3126 \(undo discard-info) to the user option `warning-suppress-types',
3127 which is defined in the `warnings' library.\n")
3128 :warning)
3129 (setq buffer-undo-list nil)
3132 (defcustom password-word-equivalents
3133 '("password" "passcode" "passphrase" "pass phrase"
3134 ; These are sorted according to the GNU en_US locale.
3135 "암호" ; ko
3136 "パスワード" ; ja
3137 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3138 "ពាក្យសម្ងាត់" ; km
3139 "adgangskode" ; da
3140 "contraseña" ; es
3141 "contrasenya" ; ca
3142 "geslo" ; sl
3143 "hasło" ; pl
3144 "heslo" ; cs, sk
3145 "iphasiwedi" ; zu
3146 "jelszó" ; hu
3147 "lösenord" ; sv
3148 "lozinka" ; hr, sr
3149 "mật khẩu" ; vi
3150 "mot de passe" ; fr
3151 "parola" ; tr
3152 "pasahitza" ; eu
3153 "passord" ; nb
3154 "passwort" ; de
3155 "pasvorto" ; eo
3156 "salasana" ; fi
3157 "senha" ; pt
3158 "slaptažodis" ; lt
3159 "wachtwoord" ; nl
3160 "كلمة السر" ; ar
3161 "ססמה" ; he
3162 "лозинка" ; sr
3163 "пароль" ; kk, ru, uk
3164 "गुप्तशब्द" ; mr
3165 "शब्दकूट" ; hi
3166 "પાસવર્ડ" ; gu
3167 "సంకేతపదము" ; te
3168 "ਪਾਸਵਰਡ" ; pa
3169 "ಗುಪ್ತಪದ" ; kn
3170 "கடவுச்சொல்" ; ta
3171 "അടയാളവാക്ക്" ; ml
3172 "গুপ্তশব্দ" ; as
3173 "পাসওয়ার্ড" ; bn_IN
3174 "රහස්පදය" ; si
3175 "密码" ; zh_CN
3176 "密碼" ; zh_TW
3178 "List of words equivalent to \"password\".
3179 This is used by Shell mode and other parts of Emacs to recognize
3180 password prompts, including prompts in languages other than
3181 English. Different case choices should not be assumed to be
3182 included; callers should bind `case-fold-search' to t."
3183 :type '(repeat string)
3184 :version "24.4"
3185 :group 'processes)
3187 (defvar shell-command-history nil
3188 "History list for some commands that read shell commands.
3190 Maximum length of the history list is determined by the value
3191 of `history-length', which see.")
3193 (defvar shell-command-switch (purecopy "-c")
3194 "Switch used to have the shell execute its command line argument.")
3196 (defvar shell-command-default-error-buffer nil
3197 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3198 This buffer is used when `shell-command' or `shell-command-on-region'
3199 is run interactively. A value of nil means that output to stderr and
3200 stdout will be intermixed in the output stream.")
3202 (declare-function mailcap-file-default-commands "mailcap" (files))
3203 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3205 (defun minibuffer-default-add-shell-commands ()
3206 "Return a list of all commands associated with the current file.
3207 This function is used to add all related commands retrieved by `mailcap'
3208 to the end of the list of defaults just after the default value."
3209 (interactive)
3210 (let* ((filename (if (listp minibuffer-default)
3211 (car minibuffer-default)
3212 minibuffer-default))
3213 (commands (and filename (require 'mailcap nil t)
3214 (mailcap-file-default-commands (list filename)))))
3215 (setq commands (mapcar (lambda (command)
3216 (concat command " " filename))
3217 commands))
3218 (if (listp minibuffer-default)
3219 (append minibuffer-default commands)
3220 (cons minibuffer-default commands))))
3222 (declare-function shell-completion-vars "shell" ())
3224 (defvar minibuffer-local-shell-command-map
3225 (let ((map (make-sparse-keymap)))
3226 (set-keymap-parent map minibuffer-local-map)
3227 (define-key map "\t" 'completion-at-point)
3228 map)
3229 "Keymap used for completing shell commands in minibuffer.")
3231 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3232 "Read a shell command from the minibuffer.
3233 The arguments are the same as the ones of `read-from-minibuffer',
3234 except READ and KEYMAP are missing and HIST defaults
3235 to `shell-command-history'."
3236 (require 'shell)
3237 (minibuffer-with-setup-hook
3238 (lambda ()
3239 (shell-completion-vars)
3240 (set (make-local-variable 'minibuffer-default-add-function)
3241 'minibuffer-default-add-shell-commands))
3242 (apply 'read-from-minibuffer prompt initial-contents
3243 minibuffer-local-shell-command-map
3245 (or hist 'shell-command-history)
3246 args)))
3248 (defcustom async-shell-command-buffer 'confirm-new-buffer
3249 "What to do when the output buffer is used by another shell command.
3250 This option specifies how to resolve the conflict where a new command
3251 wants to direct its output to the buffer `*Async Shell Command*',
3252 but this buffer is already taken by another running shell command.
3254 The value `confirm-kill-process' is used to ask for confirmation before
3255 killing the already running process and running a new process
3256 in the same buffer, `confirm-new-buffer' for confirmation before running
3257 the command in a new buffer with a name other than the default buffer name,
3258 `new-buffer' for doing the same without confirmation,
3259 `confirm-rename-buffer' for confirmation before renaming the existing
3260 output buffer and running a new command in the default buffer,
3261 `rename-buffer' for doing the same without confirmation."
3262 :type '(choice (const :tag "Confirm killing of running command"
3263 confirm-kill-process)
3264 (const :tag "Confirm creation of a new buffer"
3265 confirm-new-buffer)
3266 (const :tag "Create a new buffer"
3267 new-buffer)
3268 (const :tag "Confirm renaming of existing buffer"
3269 confirm-rename-buffer)
3270 (const :tag "Rename the existing buffer"
3271 rename-buffer))
3272 :group 'shell
3273 :version "24.3")
3275 (defcustom async-shell-command-display-buffer t
3276 "Whether to display the command buffer immediately.
3277 If t, display the buffer immediately; if nil, wait until there
3278 is output."
3279 :type '(choice (const :tag "Display buffer immediately"
3281 (const :tag "Display buffer on output"
3282 nil))
3283 :group 'shell
3284 :version "26.1")
3286 (defun shell-command--save-pos-or-erase ()
3287 "Store a buffer position or erase the buffer.
3288 See `shell-command-dont-erase-buffer'."
3289 (let ((sym shell-command-dont-erase-buffer)
3290 pos)
3291 (setq buffer-read-only nil)
3292 ;; Setting buffer-read-only to nil doesn't suffice
3293 ;; if some text has a non-nil read-only property,
3294 ;; which comint sometimes adds for prompts.
3295 (setq pos
3296 (cond ((eq sym 'save-point) (point))
3297 ((eq sym 'beg-last-out) (point-max))
3298 ((not sym)
3299 (let ((inhibit-read-only t))
3300 (erase-buffer) nil))))
3301 (when pos
3302 (goto-char (point-max))
3303 (push (cons (current-buffer) pos)
3304 shell-command-saved-pos))))
3306 (defun shell-command--set-point-after-cmd (&optional buffer)
3307 "Set point in BUFFER after command complete.
3308 BUFFER is the output buffer of the command; if nil, then defaults
3309 to the current BUFFER.
3310 Set point to the `cdr' of the element in `shell-command-saved-pos'
3311 whose `car' is BUFFER."
3312 (when shell-command-dont-erase-buffer
3313 (let* ((sym shell-command-dont-erase-buffer)
3314 (buf (or buffer (current-buffer)))
3315 (pos (alist-get buf shell-command-saved-pos)))
3316 (setq shell-command-saved-pos
3317 (assq-delete-all buf shell-command-saved-pos))
3318 (when (buffer-live-p buf)
3319 (let ((win (car (get-buffer-window-list buf)))
3320 (pmax (with-current-buffer buf (point-max))))
3321 (unless (and pos (memq sym '(save-point beg-last-out)))
3322 (setq pos pmax))
3323 ;; Set point in the window displaying buf, if any; otherwise
3324 ;; display buf temporary in selected frame and set the point.
3325 (if win
3326 (set-window-point win pos)
3327 (save-window-excursion
3328 (let ((win (display-buffer
3330 '(nil (inhibit-switch-frame . t)))))
3331 (set-window-point win pos)))))))))
3333 (defun async-shell-command (command &optional output-buffer error-buffer)
3334 "Execute string COMMAND asynchronously in background.
3336 Like `shell-command', but adds `&' at the end of COMMAND
3337 to execute it asynchronously.
3339 The output appears in the buffer `*Async Shell Command*'.
3340 That buffer is in shell mode.
3342 You can configure `async-shell-command-buffer' to specify what to do in
3343 case when `*Async Shell Command*' buffer is already taken by another
3344 running shell command. To run COMMAND without displaying the output
3345 in a window you can configure `display-buffer-alist' to use the action
3346 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3348 In Elisp, you will often be better served by calling `start-process'
3349 directly, since it offers more control and does not impose the use of a
3350 shell (with its need to quote arguments)."
3351 (interactive
3352 (list
3353 (read-shell-command "Async shell command: " nil nil
3354 (let ((filename
3355 (cond
3356 (buffer-file-name)
3357 ((eq major-mode 'dired-mode)
3358 (dired-get-filename nil t)))))
3359 (and filename (file-relative-name filename))))
3360 current-prefix-arg
3361 shell-command-default-error-buffer))
3362 (unless (string-match "&[ \t]*\\'" command)
3363 (setq command (concat command " &")))
3364 (shell-command command output-buffer error-buffer))
3366 (defun shell-command (command &optional output-buffer error-buffer)
3367 "Execute string COMMAND in inferior shell; display output, if any.
3368 With prefix argument, insert the COMMAND's output at point.
3370 Interactively, prompt for COMMAND in the minibuffer.
3372 If COMMAND ends in `&', execute it asynchronously.
3373 The output appears in the buffer `*Async Shell Command*'.
3374 That buffer is in shell mode. You can also use
3375 `async-shell-command' that automatically adds `&'.
3377 Otherwise, COMMAND is executed synchronously. The output appears in
3378 the buffer `*Shell Command Output*'. If the output is short enough to
3379 display in the echo area (which is determined by the variables
3380 `resize-mini-windows' and `max-mini-window-height'), it is shown
3381 there, but it is nonetheless available in buffer `*Shell Command
3382 Output*' even though that buffer is not automatically displayed.
3384 To specify a coding system for converting non-ASCII characters
3385 in the shell command output, use \\[universal-coding-system-argument] \
3386 before this command.
3388 Noninteractive callers can specify coding systems by binding
3389 `coding-system-for-read' and `coding-system-for-write'.
3391 The optional second argument OUTPUT-BUFFER, if non-nil,
3392 says to put the output in some other buffer.
3393 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3394 and insert the output there; a non-nil value of
3395 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3396 If OUTPUT-BUFFER is not a buffer and not nil, insert the output
3397 in current buffer after point leaving mark after it.
3398 This cannot be done asynchronously.
3400 If the command terminates without error, but generates output,
3401 and you did not specify \"insert it in the current buffer\",
3402 the output can be displayed in the echo area or in its buffer.
3403 If the output is short enough to display in the echo area
3404 \(determined by the variable `max-mini-window-height' if
3405 `resize-mini-windows' is non-nil), it is shown there.
3406 Otherwise,the buffer containing the output is displayed.
3408 If there is output and an error, and you did not specify \"insert it
3409 in the current buffer\", a message about the error goes at the end
3410 of the output.
3412 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3413 or buffer name to which to direct the command's standard error output.
3414 If it is nil, error output is mingled with regular output.
3415 In an interactive call, the variable `shell-command-default-error-buffer'
3416 specifies the value of ERROR-BUFFER.
3418 In Elisp, you will often be better served by calling `call-process' or
3419 `start-process' directly, since it offers more control and does not impose
3420 the use of a shell (with its need to quote arguments)."
3422 (interactive
3423 (list
3424 (read-shell-command "Shell command: " nil nil
3425 (let ((filename
3426 (cond
3427 (buffer-file-name)
3428 ((eq major-mode 'dired-mode)
3429 (dired-get-filename nil t)))))
3430 (and filename (file-relative-name filename))))
3431 current-prefix-arg
3432 shell-command-default-error-buffer))
3433 ;; Look for a handler in case default-directory is a remote file name.
3434 (let ((handler
3435 (find-file-name-handler (directory-file-name default-directory)
3436 'shell-command)))
3437 (if handler
3438 (funcall handler 'shell-command command output-buffer error-buffer)
3439 (if (and output-buffer
3440 (not (or (bufferp output-buffer) (stringp output-buffer))))
3441 ;; Output goes in current buffer.
3442 (let ((error-file
3443 (if error-buffer
3444 (make-temp-file
3445 (expand-file-name "scor"
3446 (or small-temporary-file-directory
3447 temporary-file-directory)))
3448 nil)))
3449 (barf-if-buffer-read-only)
3450 (push-mark nil t)
3451 ;; We do not use -f for csh; we will not support broken use of
3452 ;; .cshrcs. Even the BSD csh manual says to use
3453 ;; "if ($?prompt) exit" before things which are not useful
3454 ;; non-interactively. Besides, if someone wants their other
3455 ;; aliases for shell commands then they can still have them.
3456 (call-process shell-file-name nil
3457 (if error-file
3458 (list t error-file)
3460 nil shell-command-switch command)
3461 (when (and error-file (file-exists-p error-file))
3462 (if (< 0 (nth 7 (file-attributes error-file)))
3463 (with-current-buffer (get-buffer-create error-buffer)
3464 (let ((pos-from-end (- (point-max) (point))))
3465 (or (bobp)
3466 (insert "\f\n"))
3467 ;; Do no formatting while reading error file,
3468 ;; because that can run a shell command, and we
3469 ;; don't want that to cause an infinite recursion.
3470 (format-insert-file error-file nil)
3471 ;; Put point after the inserted errors.
3472 (goto-char (- (point-max) pos-from-end)))
3473 (display-buffer (current-buffer))))
3474 (delete-file error-file))
3475 ;; This is like exchange-point-and-mark, but doesn't
3476 ;; activate the mark. It is cleaner to avoid activation,
3477 ;; even though the command loop would deactivate the mark
3478 ;; because we inserted text.
3479 (goto-char (prog1 (mark t)
3480 (set-marker (mark-marker) (point)
3481 (current-buffer)))))
3482 ;; Output goes in a separate buffer.
3483 ;; Preserve the match data in case called from a program.
3484 ;; FIXME: It'd be ridiculous for an Elisp function to call
3485 ;; shell-command and assume that it won't mess the match-data!
3486 (save-match-data
3487 (if (string-match "[ \t]*&[ \t]*\\'" command)
3488 ;; Command ending with ampersand means asynchronous.
3489 (let ((buffer (get-buffer-create
3490 (or output-buffer "*Async Shell Command*")))
3491 (directory default-directory)
3492 proc)
3493 ;; Remove the ampersand.
3494 (setq command (substring command 0 (match-beginning 0)))
3495 ;; Ask the user what to do with already running process.
3496 (setq proc (get-buffer-process buffer))
3497 (when proc
3498 (cond
3499 ((eq async-shell-command-buffer 'confirm-kill-process)
3500 ;; If will kill a process, query first.
3501 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3502 (kill-process proc)
3503 (error "Shell command in progress")))
3504 ((eq async-shell-command-buffer 'confirm-new-buffer)
3505 ;; If will create a new buffer, query first.
3506 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3507 (setq buffer (generate-new-buffer
3508 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3509 output-buffer "*Async Shell Command*")))
3510 (error "Shell command in progress")))
3511 ((eq async-shell-command-buffer 'new-buffer)
3512 ;; It will create a new buffer.
3513 (setq buffer (generate-new-buffer
3514 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3515 output-buffer "*Async Shell Command*"))))
3516 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3517 ;; If will rename the buffer, query first.
3518 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3519 (progn
3520 (with-current-buffer buffer
3521 (rename-uniquely))
3522 (setq buffer (get-buffer-create
3523 (or output-buffer "*Async Shell Command*"))))
3524 (error "Shell command in progress")))
3525 ((eq async-shell-command-buffer 'rename-buffer)
3526 ;; It will rename the buffer.
3527 (with-current-buffer buffer
3528 (rename-uniquely))
3529 (setq buffer (get-buffer-create
3530 (or output-buffer "*Async Shell Command*"))))))
3531 (with-current-buffer buffer
3532 (shell-command--save-pos-or-erase)
3533 (setq default-directory directory)
3534 (setq proc (start-process "Shell" buffer shell-file-name
3535 shell-command-switch command))
3536 (setq mode-line-process '(":%s"))
3537 (require 'shell) (shell-mode)
3538 (set-process-sentinel proc 'shell-command-sentinel)
3539 ;; Use the comint filter for proper handling of carriage motion
3540 ;; (see `comint-inhibit-carriage-motion'),.
3541 (set-process-filter proc 'comint-output-filter)
3542 (if async-shell-command-display-buffer
3543 (display-buffer buffer '(nil (allow-no-window . t)))
3544 (add-function :before (process-filter proc)
3545 `(lambda (process string)
3546 (when (and (= 0 (buffer-size (process-buffer process)))
3547 (string= (buffer-name (process-buffer process))
3548 ,(or output-buffer "*Async Shell Command*")))
3549 (display-buffer (process-buffer process))))
3552 ;; Otherwise, command is executed synchronously.
3553 (shell-command-on-region (point) (point) command
3554 output-buffer nil error-buffer)))))))
3556 (defun display-message-or-buffer (message &optional buffer-name action frame)
3557 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3558 MESSAGE may be either a string or a buffer.
3560 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3561 for maximum height of the echo area, as defined by `max-mini-window-height'
3562 if `resize-mini-windows' is non-nil.
3564 Returns either the string shown in the echo area, or when a pop-up
3565 buffer is used, the window used to display it.
3567 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3568 name of the buffer used to display it in the case where a pop-up buffer
3569 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3570 string and it is displayed in the echo area, it is not specified whether
3571 the contents are inserted into the buffer anyway.
3573 Optional arguments ACTION and FRAME are as for `display-buffer',
3574 and are only used if a pop-up buffer is displayed."
3575 (cond ((and (stringp message) (not (string-match "\n" message)))
3576 ;; Trivial case where we can use the echo area
3577 (message "%s" message))
3578 ((and (stringp message)
3579 (= (string-match "\n" message) (1- (length message))))
3580 ;; Trivial case where we can just remove single trailing newline
3581 (message "%s" (substring message 0 (1- (length message)))))
3583 ;; General case
3584 (with-current-buffer
3585 (if (bufferp message)
3586 message
3587 (get-buffer-create (or buffer-name "*Message*")))
3589 (unless (bufferp message)
3590 (erase-buffer)
3591 (insert message))
3593 (let ((lines
3594 (if (= (buffer-size) 0)
3596 (count-screen-lines nil nil nil (minibuffer-window)))))
3597 (cond ((= lines 0))
3598 ((and (or (<= lines 1)
3599 (<= lines
3600 (if resize-mini-windows
3601 (cond ((floatp max-mini-window-height)
3602 (* (frame-height)
3603 max-mini-window-height))
3604 ((integerp max-mini-window-height)
3605 max-mini-window-height)
3608 1)))
3609 ;; Don't use the echo area if the output buffer is
3610 ;; already displayed in the selected frame.
3611 (not (get-buffer-window (current-buffer))))
3612 ;; Echo area
3613 (goto-char (point-max))
3614 (when (bolp)
3615 (backward-char 1))
3616 (message "%s" (buffer-substring (point-min) (point))))
3618 ;; Buffer
3619 (goto-char (point-min))
3620 (display-buffer (current-buffer) action frame))))))))
3623 ;; We have a sentinel to prevent insertion of a termination message
3624 ;; in the buffer itself, and to set the point in the buffer when
3625 ;; `shell-command-dont-erase-buffer' is non-nil.
3626 (defun shell-command-sentinel (process signal)
3627 (when (memq (process-status process) '(exit signal))
3628 (shell-command--set-point-after-cmd (process-buffer process))
3629 (message "%s: %s."
3630 (car (cdr (cdr (process-command process))))
3631 (substring signal 0 -1))))
3633 (defun shell-command-on-region (start end command
3634 &optional output-buffer replace
3635 error-buffer display-error-buffer
3636 region-noncontiguous-p)
3637 "Execute string COMMAND in inferior shell with region as input.
3638 Normally display output (if any) in temp buffer `*Shell Command Output*';
3639 Prefix arg means replace the region with it. Return the exit code of
3640 COMMAND.
3642 To specify a coding system for converting non-ASCII characters
3643 in the input and output to the shell command, use \\[universal-coding-system-argument]
3644 before this command. By default, the input (from the current buffer)
3645 is encoded using coding-system specified by `process-coding-system-alist',
3646 falling back to `default-process-coding-system' if no match for COMMAND
3647 is found in `process-coding-system-alist'.
3649 Noninteractive callers can specify coding systems by binding
3650 `coding-system-for-read' and `coding-system-for-write'.
3652 If the command generates output, the output may be displayed
3653 in the echo area or in a buffer.
3654 If the output is short enough to display in the echo area
3655 \(determined by the variable `max-mini-window-height' if
3656 `resize-mini-windows' is non-nil), it is shown there.
3657 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3658 The output is available in that buffer in both cases.
3660 If there is output and an error, a message about the error
3661 appears at the end of the output.
3663 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3664 command's output. If the value is a buffer or buffer name,
3665 erase that buffer and insert the output there; a non-nil value of
3666 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3667 If the value is nil, use the buffer `*Shell Command Output*'.
3668 Any other non-nil value means to insert the output in the
3669 current buffer after START.
3671 Optional fifth arg REPLACE, if non-nil, means to insert the
3672 output in place of text from START to END, putting point and mark
3673 around it.
3675 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3676 or buffer name to which to direct the command's standard error
3677 output. If nil, error output is mingled with regular output.
3678 When called interactively, `shell-command-default-error-buffer'
3679 is used for ERROR-BUFFER.
3681 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3682 display the error buffer if there were any errors. When called
3683 interactively, this is t."
3684 (interactive (let (string)
3685 (unless (mark)
3686 (user-error "The mark is not set now, so there is no region"))
3687 ;; Do this before calling region-beginning
3688 ;; and region-end, in case subprocess output
3689 ;; relocates them while we are in the minibuffer.
3690 (setq string (read-shell-command "Shell command on region: "))
3691 ;; call-interactively recognizes region-beginning and
3692 ;; region-end specially, leaving them in the history.
3693 (list (region-beginning) (region-end)
3694 string
3695 current-prefix-arg
3696 current-prefix-arg
3697 shell-command-default-error-buffer
3699 (region-noncontiguous-p))))
3700 (let ((error-file
3701 (if error-buffer
3702 (make-temp-file
3703 (expand-file-name "scor"
3704 (or small-temporary-file-directory
3705 temporary-file-directory)))
3706 nil))
3707 exit-status)
3708 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3709 (if region-noncontiguous-p
3710 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3711 output)
3712 (with-temp-buffer
3713 (insert input)
3714 (call-process-region (point-min) (point-max)
3715 shell-file-name t t
3716 nil shell-command-switch
3717 command)
3718 (setq output (split-string (buffer-string) "\n")))
3719 (goto-char start)
3720 (funcall region-insert-function output))
3721 (if (or replace
3722 (and output-buffer
3723 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3724 ;; Replace specified region with output from command.
3725 (let ((swap (and replace (< start end))))
3726 ;; Don't muck with mark unless REPLACE says we should.
3727 (goto-char start)
3728 (and replace (push-mark (point) 'nomsg))
3729 (setq exit-status
3730 (call-shell-region start end command replace
3731 (if error-file
3732 (list t error-file)
3733 t)))
3734 ;; It is rude to delete a buffer which the command is not using.
3735 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3736 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3737 ;; (kill-buffer shell-buffer)))
3738 ;; Don't muck with mark unless REPLACE says we should.
3739 (and replace swap (exchange-point-and-mark)))
3740 ;; No prefix argument: put the output in a temp buffer,
3741 ;; replacing its entire contents.
3742 (let ((buffer (get-buffer-create
3743 (or output-buffer "*Shell Command Output*"))))
3744 (unwind-protect
3745 (if (and (eq buffer (current-buffer))
3746 (or (not shell-command-dont-erase-buffer)
3747 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3748 (not (region-active-p)))))
3749 ;; If the input is the same buffer as the output,
3750 ;; delete everything but the specified region,
3751 ;; then replace that region with the output.
3752 (progn (setq buffer-read-only nil)
3753 (delete-region (max start end) (point-max))
3754 (delete-region (point-min) (min start end))
3755 (setq exit-status
3756 (call-process-region (point-min) (point-max)
3757 shell-file-name t
3758 (if error-file
3759 (list t error-file)
3761 nil shell-command-switch
3762 command)))
3763 ;; Clear the output buffer, then run the command with
3764 ;; output there.
3765 (let ((directory default-directory))
3766 (with-current-buffer buffer
3767 (if (not output-buffer)
3768 (setq default-directory directory))
3769 (shell-command--save-pos-or-erase)))
3770 (setq exit-status
3771 (call-shell-region start end command nil
3772 (if error-file
3773 (list buffer error-file)
3774 buffer))))
3775 ;; Report the output.
3776 (with-current-buffer buffer
3777 (setq mode-line-process
3778 (cond ((null exit-status)
3779 " - Error")
3780 ((stringp exit-status)
3781 (format " - Signal [%s]" exit-status))
3782 ((not (equal 0 exit-status))
3783 (format " - Exit [%d]" exit-status)))))
3784 (if (with-current-buffer buffer (> (point-max) (point-min)))
3785 ;; There's some output, display it
3786 (progn
3787 (display-message-or-buffer buffer)
3788 (shell-command--set-point-after-cmd buffer))
3789 ;; No output; error?
3790 (let ((output
3791 (if (and error-file
3792 (< 0 (nth 7 (file-attributes error-file))))
3793 (format "some error output%s"
3794 (if shell-command-default-error-buffer
3795 (format " to the \"%s\" buffer"
3796 shell-command-default-error-buffer)
3797 ""))
3798 "no output")))
3799 (cond ((null exit-status)
3800 (message "(Shell command failed with error)"))
3801 ((equal 0 exit-status)
3802 (message "(Shell command succeeded with %s)"
3803 output))
3804 ((stringp exit-status)
3805 (message "(Shell command killed by signal %s)"
3806 exit-status))
3808 (message "(Shell command failed with code %d and %s)"
3809 exit-status output))))
3810 ;; Don't kill: there might be useful info in the undo-log.
3811 ;; (kill-buffer buffer)
3812 )))))
3814 (when (and error-file (file-exists-p error-file))
3815 (if (< 0 (nth 7 (file-attributes error-file)))
3816 (with-current-buffer (get-buffer-create error-buffer)
3817 (let ((pos-from-end (- (point-max) (point))))
3818 (or (bobp)
3819 (insert "\f\n"))
3820 ;; Do no formatting while reading error file,
3821 ;; because that can run a shell command, and we
3822 ;; don't want that to cause an infinite recursion.
3823 (format-insert-file error-file nil)
3824 ;; Put point after the inserted errors.
3825 (goto-char (- (point-max) pos-from-end)))
3826 (and display-error-buffer
3827 (display-buffer (current-buffer)))))
3828 (delete-file error-file))
3829 exit-status))
3831 (defun shell-command-to-string (command)
3832 "Execute shell command COMMAND and return its output as a string."
3833 (with-output-to-string
3834 (with-current-buffer
3835 standard-output
3836 (process-file shell-file-name nil t nil shell-command-switch command))))
3838 (defun process-file (program &optional infile buffer display &rest args)
3839 "Process files synchronously in a separate process.
3840 Similar to `call-process', but may invoke a file handler based on
3841 `default-directory'. The current working directory of the
3842 subprocess is `default-directory'.
3844 File names in INFILE and BUFFER are handled normally, but file
3845 names in ARGS should be relative to `default-directory', as they
3846 are passed to the process verbatim. (This is a difference to
3847 `call-process' which does not support file handlers for INFILE
3848 and BUFFER.)
3850 Some file handlers might not support all variants, for example
3851 they might behave as if DISPLAY was nil, regardless of the actual
3852 value passed."
3853 (let ((fh (find-file-name-handler default-directory 'process-file))
3854 lc stderr-file)
3855 (unwind-protect
3856 (if fh (apply fh 'process-file program infile buffer display args)
3857 (when infile (setq lc (file-local-copy infile)))
3858 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3859 (make-temp-file "emacs")))
3860 (prog1
3861 (apply 'call-process program
3862 (or lc infile)
3863 (if stderr-file (list (car buffer) stderr-file) buffer)
3864 display args)
3865 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3866 (when stderr-file (delete-file stderr-file))
3867 (when lc (delete-file lc)))))
3869 (defvar process-file-side-effects t
3870 "Whether a call of `process-file' changes remote files.
3872 By default, this variable is always set to t, meaning that a
3873 call of `process-file' could potentially change any file on a
3874 remote host. When set to nil, a file handler could optimize
3875 its behavior with respect to remote file attribute caching.
3877 You should only ever change this variable with a let-binding;
3878 never with `setq'.")
3880 (defun start-file-process (name buffer program &rest program-args)
3881 "Start a program in a subprocess. Return the process object for it.
3883 Similar to `start-process', but may invoke a file handler based on
3884 `default-directory'. See Info node `(elisp)Magic File Names'.
3886 This handler ought to run PROGRAM, perhaps on the local host,
3887 perhaps on a remote host that corresponds to `default-directory'.
3888 In the latter case, the local part of `default-directory' becomes
3889 the working directory of the process.
3891 PROGRAM and PROGRAM-ARGS might be file names. They are not
3892 objects of file handler invocation. File handlers might not
3893 support pty association, if PROGRAM is nil."
3894 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3895 (if fh (apply fh 'start-file-process name buffer program program-args)
3896 (apply 'start-process name buffer program program-args))))
3898 ;;;; Process menu
3900 (defvar tabulated-list-format)
3901 (defvar tabulated-list-entries)
3902 (defvar tabulated-list-sort-key)
3903 (declare-function tabulated-list-init-header "tabulated-list" ())
3904 (declare-function tabulated-list-print "tabulated-list"
3905 (&optional remember-pos update))
3907 (defvar process-menu-query-only nil)
3909 (defvar process-menu-mode-map
3910 (let ((map (make-sparse-keymap)))
3911 (define-key map [?d] 'process-menu-delete-process)
3912 map))
3914 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3915 "Major mode for listing the processes called by Emacs."
3916 (setq tabulated-list-format [("Process" 15 t)
3917 ("PID" 7 t)
3918 ("Status" 7 t)
3919 ("Buffer" 15 t)
3920 ("TTY" 12 t)
3921 ("Command" 0 t)])
3922 (make-local-variable 'process-menu-query-only)
3923 (setq tabulated-list-sort-key (cons "Process" nil))
3924 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t))
3926 (defun process-menu-delete-process ()
3927 "Kill process at point in a `list-processes' buffer."
3928 (interactive)
3929 (let ((pos (point)))
3930 (delete-process (tabulated-list-get-id))
3931 (revert-buffer)
3932 (goto-char (min pos (point-max)))
3933 (if (eobp)
3934 (forward-line -1)
3935 (beginning-of-line))))
3937 (defun list-processes--refresh ()
3938 "Recompute the list of processes for the Process List buffer.
3939 Also, delete any process that is exited or signaled."
3940 (setq tabulated-list-entries nil)
3941 (dolist (p (process-list))
3942 (cond ((memq (process-status p) '(exit signal closed))
3943 (delete-process p))
3944 ((or (not process-menu-query-only)
3945 (process-query-on-exit-flag p))
3946 (let* ((buf (process-buffer p))
3947 (type (process-type p))
3948 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
3949 (name (process-name p))
3950 (status (symbol-name (process-status p)))
3951 (buf-label (if (buffer-live-p buf)
3952 `(,(buffer-name buf)
3953 face link
3954 help-echo ,(format-message
3955 "Visit buffer `%s'"
3956 (buffer-name buf))
3957 follow-link t
3958 process-buffer ,buf
3959 action process-menu-visit-buffer)
3960 "--"))
3961 (tty (or (process-tty-name p) "--"))
3962 (cmd
3963 (if (memq type '(network serial))
3964 (let ((contact (process-contact p t)))
3965 (if (eq type 'network)
3966 (format "(%s %s)"
3967 (if (plist-get contact :type)
3968 "datagram"
3969 "network")
3970 (if (plist-get contact :server)
3971 (format "server on %s"
3973 (plist-get contact :host)
3974 (plist-get contact :local)))
3975 (format "connection to %s"
3976 (plist-get contact :host))))
3977 (format "(serial port %s%s)"
3978 (or (plist-get contact :port) "?")
3979 (let ((speed (plist-get contact :speed)))
3980 (if speed
3981 (format " at %s b/s" speed)
3982 "")))))
3983 (mapconcat 'identity (process-command p) " "))))
3984 (push (list p (vector name pid status buf-label tty cmd))
3985 tabulated-list-entries)))))
3986 (tabulated-list-init-header))
3988 (defun process-menu-visit-buffer (button)
3989 (display-buffer (button-get button 'process-buffer)))
3991 (defun list-processes (&optional query-only buffer)
3992 "Display a list of all processes that are Emacs sub-processes.
3993 If optional argument QUERY-ONLY is non-nil, only processes with
3994 the query-on-exit flag set are listed.
3995 Any process listed as exited or signaled is actually eliminated
3996 after the listing is made.
3997 Optional argument BUFFER specifies a buffer to use, instead of
3998 \"*Process List*\".
3999 The return value is always nil.
4001 This function lists only processes that were launched by Emacs. To
4002 see other processes running on the system, use `list-system-processes'."
4003 (interactive)
4004 (or (fboundp 'process-list)
4005 (error "Asynchronous subprocesses are not supported on this system"))
4006 (unless (bufferp buffer)
4007 (setq buffer (get-buffer-create "*Process List*")))
4008 (with-current-buffer buffer
4009 (process-menu-mode)
4010 (setq process-menu-query-only query-only)
4011 (list-processes--refresh)
4012 (tabulated-list-print))
4013 (display-buffer buffer)
4014 nil)
4016 ;;;; Prefix commands
4018 (setq prefix-command--needs-update nil)
4019 (setq prefix-command--last-echo nil)
4021 (defun internal-echo-keystrokes-prefix ()
4022 ;; BEWARE: Called directly from C code.
4023 ;; If the return value is non-nil, it means we are in the middle of
4024 ;; a command with prefix, such as a command invoked with prefix-arg.
4025 (if (not prefix-command--needs-update)
4026 prefix-command--last-echo
4027 (setq prefix-command--last-echo
4028 (let ((strs nil))
4029 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
4030 (lambda (fun) (push (funcall fun) strs)))
4031 (setq strs (delq nil strs))
4032 (when strs (mapconcat #'identity strs " "))))))
4034 (defvar prefix-command-echo-keystrokes-functions nil
4035 "Abnormal hook which constructs the description of the current prefix state.
4036 Each function is called with no argument, should return a string or nil.")
4038 (defun prefix-command-update ()
4039 "Update state of prefix commands.
4040 Call it whenever you change the \"prefix command state\"."
4041 (setq prefix-command--needs-update t))
4043 (defvar prefix-command-preserve-state-hook nil
4044 "Normal hook run when a command needs to preserve the prefix.")
4046 (defun prefix-command-preserve-state ()
4047 "Pass the current prefix command state to the next command.
4048 Should be called by all prefix commands.
4049 Runs `prefix-command-preserve-state-hook'."
4050 (run-hooks 'prefix-command-preserve-state-hook)
4051 ;; If the current command is a prefix command, we don't want the next (real)
4052 ;; command to have `last-command' set to, say, `universal-argument'.
4053 (setq this-command last-command)
4054 (setq real-this-command real-last-command)
4055 (prefix-command-update))
4057 (defun reset-this-command-lengths ()
4058 (declare (obsolete prefix-command-preserve-state "25.1"))
4059 nil)
4061 ;;;;; The main prefix command.
4063 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4065 (add-hook 'prefix-command-echo-keystrokes-functions
4066 #'universal-argument--description)
4067 (defun universal-argument--description ()
4068 (when prefix-arg
4069 (concat "C-u"
4070 (pcase prefix-arg
4071 (`(-) " -")
4072 (`(,(and (pred integerp) n))
4073 (let ((str ""))
4074 (while (and (> n 4) (= (mod n 4) 0))
4075 (setq str (concat str " C-u"))
4076 (setq n (/ n 4)))
4077 (if (= n 4) str (format " %s" prefix-arg))))
4078 (_ (format " %s" prefix-arg))))))
4080 (add-hook 'prefix-command-preserve-state-hook
4081 #'universal-argument--preserve)
4082 (defun universal-argument--preserve ()
4083 (setq prefix-arg current-prefix-arg))
4085 (defvar universal-argument-map
4086 (let ((map (make-sparse-keymap))
4087 (universal-argument-minus
4088 ;; For backward compatibility, minus with no modifiers is an ordinary
4089 ;; command if digits have already been entered.
4090 `(menu-item "" negative-argument
4091 :filter ,(lambda (cmd)
4092 (if (integerp prefix-arg) nil cmd)))))
4093 (define-key map [switch-frame]
4094 (lambda (e) (interactive "e")
4095 (handle-switch-frame e) (universal-argument--mode)))
4096 (define-key map [?\C-u] 'universal-argument-more)
4097 (define-key map [?-] universal-argument-minus)
4098 (define-key map [?0] 'digit-argument)
4099 (define-key map [?1] 'digit-argument)
4100 (define-key map [?2] 'digit-argument)
4101 (define-key map [?3] 'digit-argument)
4102 (define-key map [?4] 'digit-argument)
4103 (define-key map [?5] 'digit-argument)
4104 (define-key map [?6] 'digit-argument)
4105 (define-key map [?7] 'digit-argument)
4106 (define-key map [?8] 'digit-argument)
4107 (define-key map [?9] 'digit-argument)
4108 (define-key map [kp-0] 'digit-argument)
4109 (define-key map [kp-1] 'digit-argument)
4110 (define-key map [kp-2] 'digit-argument)
4111 (define-key map [kp-3] 'digit-argument)
4112 (define-key map [kp-4] 'digit-argument)
4113 (define-key map [kp-5] 'digit-argument)
4114 (define-key map [kp-6] 'digit-argument)
4115 (define-key map [kp-7] 'digit-argument)
4116 (define-key map [kp-8] 'digit-argument)
4117 (define-key map [kp-9] 'digit-argument)
4118 (define-key map [kp-subtract] universal-argument-minus)
4119 map)
4120 "Keymap used while processing \\[universal-argument].")
4122 (defun universal-argument--mode ()
4123 (prefix-command-update)
4124 (set-transient-map universal-argument-map nil))
4126 (defun universal-argument ()
4127 "Begin a numeric argument for the following command.
4128 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4129 \\[universal-argument] following the digits or minus sign ends the argument.
4130 \\[universal-argument] without digits or minus sign provides 4 as argument.
4131 Repeating \\[universal-argument] without digits or minus sign
4132 multiplies the argument by 4 each time.
4133 For some commands, just \\[universal-argument] by itself serves as a flag
4134 which is different in effect from any particular numeric argument.
4135 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4136 (interactive)
4137 (prefix-command-preserve-state)
4138 (setq prefix-arg (list 4))
4139 (universal-argument--mode))
4141 (defun universal-argument-more (arg)
4142 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4143 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4144 (interactive "P")
4145 (prefix-command-preserve-state)
4146 (setq prefix-arg (if (consp arg)
4147 (list (* 4 (car arg)))
4148 (if (eq arg '-)
4149 (list -4)
4150 arg)))
4151 (when (consp prefix-arg) (universal-argument--mode)))
4153 (defun negative-argument (arg)
4154 "Begin a negative numeric argument for the next command.
4155 \\[universal-argument] following digits or minus sign ends the argument."
4156 (interactive "P")
4157 (prefix-command-preserve-state)
4158 (setq prefix-arg (cond ((integerp arg) (- arg))
4159 ((eq arg '-) nil)
4160 (t '-)))
4161 (universal-argument--mode))
4163 (defun digit-argument (arg)
4164 "Part of the numeric argument for the next command.
4165 \\[universal-argument] following digits or minus sign ends the argument."
4166 (interactive "P")
4167 (prefix-command-preserve-state)
4168 (let* ((char (if (integerp last-command-event)
4169 last-command-event
4170 (get last-command-event 'ascii-character)))
4171 (digit (- (logand char ?\177) ?0)))
4172 (setq prefix-arg (cond ((integerp arg)
4173 (+ (* arg 10)
4174 (if (< arg 0) (- digit) digit)))
4175 ((eq arg '-)
4176 ;; Treat -0 as just -, so that -01 will work.
4177 (if (zerop digit) '- (- digit)))
4179 digit))))
4180 (universal-argument--mode))
4183 (defvar filter-buffer-substring-functions nil
4184 "This variable is a wrapper hook around `buffer-substring--filter'.
4185 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4186 (make-obsolete-variable 'filter-buffer-substring-functions
4187 'filter-buffer-substring-function "24.4")
4189 (defvar filter-buffer-substring-function #'buffer-substring--filter
4190 "Function to perform the filtering in `filter-buffer-substring'.
4191 The function is called with the same 3 arguments (BEG END DELETE)
4192 that `filter-buffer-substring' received. It should return the
4193 buffer substring between BEG and END, after filtering. If DELETE is
4194 non-nil, it should delete the text between BEG and END from the buffer.")
4196 (defvar buffer-substring-filters nil
4197 "List of filter functions for `buffer-substring--filter'.
4198 Each function must accept a single argument, a string, and return a string.
4199 The buffer substring is passed to the first function in the list,
4200 and the return value of each function is passed to the next.
4201 As a special convention, point is set to the start of the buffer text
4202 being operated on (i.e., the first argument of `buffer-substring--filter')
4203 before these functions are called.")
4204 (make-obsolete-variable 'buffer-substring-filters
4205 'filter-buffer-substring-function "24.1")
4207 (defun filter-buffer-substring (beg end &optional delete)
4208 "Return the buffer substring between BEG and END, after filtering.
4209 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4211 This calls the function that `filter-buffer-substring-function' specifies
4212 \(passing the same three arguments that it received) to do the work,
4213 and returns whatever it does. The default function does no filtering,
4214 unless a hook has been set.
4216 Use `filter-buffer-substring' instead of `buffer-substring',
4217 `buffer-substring-no-properties', or `delete-and-extract-region' when
4218 you want to allow filtering to take place. For example, major or minor
4219 modes can use `filter-buffer-substring-function' to extract characters
4220 that are special to a buffer, and should not be copied into other buffers."
4221 (funcall filter-buffer-substring-function beg end delete))
4223 (defun buffer-substring--filter (beg end &optional delete)
4224 "Default function to use for `filter-buffer-substring-function'.
4225 Its arguments and return value are as specified for `filter-buffer-substring'.
4226 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4227 \(see `with-wrapper-hook' for details about wrapper hooks),
4228 and the abnormal hook `buffer-substring-filters'.
4229 No filtering is done unless a hook says to."
4230 (subr--with-wrapper-hook-no-warnings
4231 filter-buffer-substring-functions (beg end delete)
4232 (cond
4233 ((or delete buffer-substring-filters)
4234 (save-excursion
4235 (goto-char beg)
4236 (let ((string (if delete (delete-and-extract-region beg end)
4237 (buffer-substring beg end))))
4238 (dolist (filter buffer-substring-filters)
4239 (setq string (funcall filter string)))
4240 string)))
4242 (buffer-substring beg end)))))
4245 ;;;; Window system cut and paste hooks.
4247 (defvar interprogram-cut-function #'gui-select-text
4248 "Function to call to make a killed region available to other programs.
4249 Most window systems provide a facility for cutting and pasting
4250 text between different programs, such as the clipboard on X and
4251 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4253 This variable holds a function that Emacs calls whenever text is
4254 put in the kill ring, to make the new kill available to other
4255 programs. The function takes one argument, TEXT, which is a
4256 string containing the text which should be made available.")
4258 (defvar interprogram-paste-function #'gui-selection-value
4259 "Function to call to get text cut from 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 to obtain text
4265 that other programs have provided for pasting. The function is
4266 called with no arguments. If no other program has provided text
4267 to paste, the function should return nil (in which case the
4268 caller, usually `current-kill', should use the top of the Emacs
4269 kill ring). If another program has provided text to paste, the
4270 function should return that text as a string (in which case the
4271 caller should put this string in the kill ring as the latest
4272 kill).
4274 The function may also return a list of strings if the window
4275 system supports multiple selections. The first string will be
4276 used as the pasted text, but the other will be placed in the kill
4277 ring for easy access via `yank-pop'.
4279 Note that the function should return a string only if a program
4280 other than Emacs has provided a string for pasting; if Emacs
4281 provided the most recent string, the function should return nil.
4282 If it is difficult to tell whether Emacs or some other program
4283 provided the current string, it is probably good enough to return
4284 nil if the string is equal (according to `string=') to the last
4285 text Emacs provided.")
4289 ;;;; The kill ring data structure.
4291 (defvar kill-ring nil
4292 "List of killed text sequences.
4293 Since the kill ring is supposed to interact nicely with cut-and-paste
4294 facilities offered by window systems, use of this variable should
4295 interact nicely with `interprogram-cut-function' and
4296 `interprogram-paste-function'. The functions `kill-new',
4297 `kill-append', and `current-kill' are supposed to implement this
4298 interaction; you may want to use them instead of manipulating the kill
4299 ring directly.")
4301 (defcustom kill-ring-max 60
4302 "Maximum length of kill ring before oldest elements are thrown away."
4303 :type 'integer
4304 :group 'killing)
4306 (defvar kill-ring-yank-pointer nil
4307 "The tail of the kill ring whose car is the last thing yanked.")
4309 (defcustom save-interprogram-paste-before-kill nil
4310 "Save clipboard strings into kill ring before replacing them.
4311 When one selects something in another program to paste it into Emacs,
4312 but kills something in Emacs before actually pasting it,
4313 this selection is gone unless this variable is non-nil,
4314 in which case the other program's selection is saved in the `kill-ring'
4315 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4316 :type 'boolean
4317 :group 'killing
4318 :version "23.2")
4320 (defcustom kill-do-not-save-duplicates nil
4321 "Do not add a new string to `kill-ring' if it duplicates the last one.
4322 The comparison is done using `equal-including-properties'."
4323 :type 'boolean
4324 :group 'killing
4325 :version "23.2")
4327 (defun kill-new (string &optional replace)
4328 "Make STRING the latest kill in the kill ring.
4329 Set `kill-ring-yank-pointer' to point to it.
4330 If `interprogram-cut-function' is non-nil, apply it to STRING.
4331 Optional second argument REPLACE non-nil means that STRING will replace
4332 the front of the kill ring, rather than being added to the list.
4334 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4335 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4336 STRING.
4338 When the yank handler has a non-nil PARAM element, the original STRING
4339 argument is not used by `insert-for-yank'. However, since Lisp code
4340 may access and use elements from the kill ring directly, the STRING
4341 argument should still be a \"useful\" string for such uses."
4342 (unless (and kill-do-not-save-duplicates
4343 ;; Due to text properties such as 'yank-handler that
4344 ;; can alter the contents to yank, comparison using
4345 ;; `equal' is unsafe.
4346 (equal-including-properties string (car kill-ring)))
4347 (if (fboundp 'menu-bar-update-yank-menu)
4348 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4349 (when save-interprogram-paste-before-kill
4350 (let ((interprogram-paste (and interprogram-paste-function
4351 (funcall interprogram-paste-function))))
4352 (when interprogram-paste
4353 (dolist (s (if (listp interprogram-paste)
4354 (nreverse interprogram-paste)
4355 (list interprogram-paste)))
4356 (unless (and kill-do-not-save-duplicates
4357 (equal-including-properties s (car kill-ring)))
4358 (push s kill-ring))))))
4359 (unless (and kill-do-not-save-duplicates
4360 (equal-including-properties string (car kill-ring)))
4361 (if (and replace kill-ring)
4362 (setcar kill-ring string)
4363 (push string kill-ring)
4364 (if (> (length kill-ring) kill-ring-max)
4365 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4366 (setq kill-ring-yank-pointer kill-ring)
4367 (if interprogram-cut-function
4368 (funcall interprogram-cut-function string)))
4370 ;; It has been argued that this should work similar to `self-insert-command'
4371 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4372 (defcustom kill-append-merge-undo nil
4373 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4374 :type 'boolean
4375 :group 'killing
4376 :version "25.1")
4378 (defun kill-append (string before-p)
4379 "Append STRING to the end of the latest kill in the kill ring.
4380 If BEFORE-P is non-nil, prepend STRING to the kill.
4381 Also removes the last undo boundary in the current buffer,
4382 depending on `kill-append-merge-undo'.
4383 If `interprogram-cut-function' is set, pass the resulting kill to it."
4384 (let* ((cur (car kill-ring)))
4385 (kill-new (if before-p (concat string cur) (concat cur string))
4386 (or (= (length cur) 0)
4387 (equal nil (get-text-property 0 'yank-handler cur))))
4388 (when (and kill-append-merge-undo (not buffer-read-only))
4389 (let ((prev buffer-undo-list)
4390 (next (cdr buffer-undo-list)))
4391 ;; find the next undo boundary
4392 (while (car next)
4393 (pop next)
4394 (pop prev))
4395 ;; remove this undo boundary
4396 (when prev
4397 (setcdr prev (cdr next)))))))
4399 (defcustom yank-pop-change-selection nil
4400 "Whether rotating the kill ring changes the window system selection.
4401 If non-nil, whenever the kill ring is rotated (usually via the
4402 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4403 to copy the new kill to the window system selection."
4404 :type 'boolean
4405 :group 'killing
4406 :version "23.1")
4408 (defun current-kill (n &optional do-not-move)
4409 "Rotate the yanking point by N places, and then return that kill.
4410 If N is zero and `interprogram-paste-function' is set to a
4411 function that returns a string or a list of strings, and if that
4412 function doesn't return nil, then that string (or list) is added
4413 to the front of the kill ring and the string (or first string in
4414 the list) is returned as the latest kill.
4416 If N is not zero, and if `yank-pop-change-selection' is
4417 non-nil, use `interprogram-cut-function' to transfer the
4418 kill at the new yank point into the window system selection.
4420 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4421 move the yanking point; just return the Nth kill forward."
4423 (let ((interprogram-paste (and (= n 0)
4424 interprogram-paste-function
4425 (funcall interprogram-paste-function))))
4426 (if interprogram-paste
4427 (progn
4428 ;; Disable the interprogram cut function when we add the new
4429 ;; text to the kill ring, so Emacs doesn't try to own the
4430 ;; selection, with identical text.
4431 (let ((interprogram-cut-function nil))
4432 (if (listp interprogram-paste)
4433 (mapc 'kill-new (nreverse interprogram-paste))
4434 (kill-new interprogram-paste)))
4435 (car kill-ring))
4436 (or kill-ring (error "Kill ring is empty"))
4437 (let ((ARGth-kill-element
4438 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4439 (length kill-ring))
4440 kill-ring)))
4441 (unless do-not-move
4442 (setq kill-ring-yank-pointer ARGth-kill-element)
4443 (when (and yank-pop-change-selection
4444 (> n 0)
4445 interprogram-cut-function)
4446 (funcall interprogram-cut-function (car ARGth-kill-element))))
4447 (car ARGth-kill-element)))))
4451 ;;;; Commands for manipulating the kill ring.
4453 (defcustom kill-read-only-ok nil
4454 "Non-nil means don't signal an error for killing read-only text."
4455 :type 'boolean
4456 :group 'killing)
4458 (defun kill-region (beg end &optional region)
4459 "Kill (\"cut\") text between point and mark.
4460 This deletes the text from the buffer and saves it in the kill ring.
4461 The command \\[yank] can retrieve it from there.
4462 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4464 If you want to append the killed region to the last killed text,
4465 use \\[append-next-kill] before \\[kill-region].
4467 Any command that calls this function is a \"kill command\".
4468 If the previous command was also a kill command,
4469 the text killed this time appends to the text killed last time
4470 to make one entry in the kill ring.
4472 The killed text is filtered by `filter-buffer-substring' before it is
4473 saved in the kill ring, so the actual saved text might be different
4474 from what was killed.
4476 If the buffer is read-only, Emacs will beep and refrain from deleting
4477 the text, but put the text in the kill ring anyway. This means that
4478 you can use the killing commands to copy text from a read-only buffer.
4480 Lisp programs should use this function for killing text.
4481 (To delete text, use `delete-region'.)
4482 Supply two arguments, character positions BEG and END indicating the
4483 stretch of text to be killed. If the optional argument REGION is
4484 non-nil, the function ignores BEG and END, and kills the current
4485 region instead."
4486 ;; Pass mark first, then point, because the order matters when
4487 ;; calling `kill-append'.
4488 (interactive (list (mark) (point) 'region))
4489 (unless (and beg end)
4490 (user-error "The mark is not set now, so there is no region"))
4491 (condition-case nil
4492 (let ((string (if region
4493 (funcall region-extract-function 'delete)
4494 (filter-buffer-substring beg end 'delete))))
4495 (when string ;STRING is nil if BEG = END
4496 ;; Add that string to the kill ring, one way or another.
4497 (if (eq last-command 'kill-region)
4498 (kill-append string (< end beg))
4499 (kill-new string)))
4500 (when (or string (eq last-command 'kill-region))
4501 (setq this-command 'kill-region))
4502 (setq deactivate-mark t)
4503 nil)
4504 ((buffer-read-only text-read-only)
4505 ;; The code above failed because the buffer, or some of the characters
4506 ;; in the region, are read-only.
4507 ;; We should beep, in case the user just isn't aware of this.
4508 ;; However, there's no harm in putting
4509 ;; the region's text in the kill ring, anyway.
4510 (copy-region-as-kill beg end region)
4511 ;; Set this-command now, so it will be set even if we get an error.
4512 (setq this-command 'kill-region)
4513 ;; This should barf, if appropriate, and give us the correct error.
4514 (if kill-read-only-ok
4515 (progn (message "Read only text copied to kill ring") nil)
4516 ;; Signal an error if the buffer is read-only.
4517 (barf-if-buffer-read-only)
4518 ;; If the buffer isn't read-only, the text is.
4519 (signal 'text-read-only (list (current-buffer)))))))
4521 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4522 ;; to get two copies of the text when the user accidentally types M-w and
4523 ;; then corrects it with the intended C-w.
4524 (defun copy-region-as-kill (beg end &optional region)
4525 "Save the region as if killed, but don't kill it.
4526 In Transient Mark mode, deactivate the mark.
4527 If `interprogram-cut-function' is non-nil, also save the text for a window
4528 system cut and paste.
4530 The copied text is filtered by `filter-buffer-substring' before it is
4531 saved in the kill ring, so the actual saved text might be different
4532 from what was in the buffer.
4534 When called from Lisp, save in the kill ring the stretch of text
4535 between BEG and END, unless the optional argument REGION is
4536 non-nil, in which case ignore BEG and END, and save the current
4537 region instead.
4539 This command's old key binding has been given to `kill-ring-save'."
4540 ;; Pass mark first, then point, because the order matters when
4541 ;; calling `kill-append'.
4542 (interactive (list (mark) (point)
4543 (prefix-numeric-value current-prefix-arg)))
4544 (let ((str (if region
4545 (funcall region-extract-function nil)
4546 (filter-buffer-substring beg end))))
4547 (if (eq last-command 'kill-region)
4548 (kill-append str (< end beg))
4549 (kill-new str)))
4550 (setq deactivate-mark t)
4551 nil)
4553 (defun kill-ring-save (beg end &optional region)
4554 "Save the region as if killed, but don't kill it.
4555 In Transient Mark mode, deactivate the mark.
4556 If `interprogram-cut-function' is non-nil, also save the text for a window
4557 system cut and paste.
4559 If you want to append the killed line to the last killed text,
4560 use \\[append-next-kill] before \\[kill-ring-save].
4562 The copied text is filtered by `filter-buffer-substring' before it is
4563 saved in the kill ring, so the actual saved text might be different
4564 from what was in the buffer.
4566 When called from Lisp, save in the kill ring the stretch of text
4567 between BEG and END, unless the optional argument REGION is
4568 non-nil, in which case ignore BEG and END, and save the current
4569 region instead.
4571 This command is similar to `copy-region-as-kill', except that it gives
4572 visual feedback indicating the extent of the region being copied."
4573 ;; Pass mark first, then point, because the order matters when
4574 ;; calling `kill-append'.
4575 (interactive (list (mark) (point)
4576 (prefix-numeric-value current-prefix-arg)))
4577 (copy-region-as-kill beg end region)
4578 ;; This use of called-interactively-p is correct because the code it
4579 ;; controls just gives the user visual feedback.
4580 (if (called-interactively-p 'interactive)
4581 (indicate-copied-region)))
4583 (defun indicate-copied-region (&optional message-len)
4584 "Indicate that the region text has been copied interactively.
4585 If the mark is visible in the selected window, blink the cursor
4586 between point and mark if there is currently no active region
4587 highlighting.
4589 If the mark lies outside the selected window, display an
4590 informative message containing a sample of the copied text. The
4591 optional argument MESSAGE-LEN, if non-nil, specifies the length
4592 of this sample text; it defaults to 40."
4593 (let ((mark (mark t))
4594 (point (point))
4595 ;; Inhibit quitting so we can make a quit here
4596 ;; look like a C-g typed as a command.
4597 (inhibit-quit t))
4598 (if (pos-visible-in-window-p mark (selected-window))
4599 ;; Swap point-and-mark quickly so as to show the region that
4600 ;; was selected. Don't do it if the region is highlighted.
4601 (unless (and (region-active-p)
4602 (face-background 'region))
4603 ;; Swap point and mark.
4604 (set-marker (mark-marker) (point) (current-buffer))
4605 (goto-char mark)
4606 (sit-for blink-matching-delay)
4607 ;; Swap back.
4608 (set-marker (mark-marker) mark (current-buffer))
4609 (goto-char point)
4610 ;; If user quit, deactivate the mark
4611 ;; as C-g would as a command.
4612 (and quit-flag (region-active-p)
4613 (deactivate-mark)))
4614 (let ((len (min (abs (- mark point))
4615 (or message-len 40))))
4616 (if (< point mark)
4617 ;; Don't say "killed"; that is misleading.
4618 (message "Saved text until \"%s\""
4619 (buffer-substring-no-properties (- mark len) mark))
4620 (message "Saved text from \"%s\""
4621 (buffer-substring-no-properties mark (+ mark len))))))))
4623 (defun append-next-kill (&optional interactive)
4624 "Cause following command, if it kills, to add to previous kill.
4625 If the next command kills forward from point, the kill is
4626 appended to the previous killed text. If the command kills
4627 backward, the kill is prepended. Kill commands that act on the
4628 region, such as `kill-region', are regarded as killing forward if
4629 point is after mark, and killing backward if point is before
4630 mark.
4632 If the next command is not a kill command, `append-next-kill' has
4633 no effect.
4635 The argument is used for internal purposes; do not supply one."
4636 (interactive "p")
4637 ;; We don't use (interactive-p), since that breaks kbd macros.
4638 (if interactive
4639 (progn
4640 (setq this-command 'kill-region)
4641 (message "If the next command is a kill, it will append"))
4642 (setq last-command 'kill-region)))
4644 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4645 "Character set that matches bidirectional formatting control characters.")
4647 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4648 "Character set that matches any character except bidirectional controls.")
4650 (defun squeeze-bidi-context-1 (from to category replacement)
4651 "A subroutine of `squeeze-bidi-context'.
4652 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4653 (let ((pt (copy-marker from))
4654 (limit (copy-marker to))
4655 (old-pt 0)
4656 lim1)
4657 (setq lim1 limit)
4658 (goto-char pt)
4659 (while (< pt limit)
4660 (if (> pt old-pt)
4661 (move-marker lim1
4662 (save-excursion
4663 ;; L and R categories include embedding and
4664 ;; override controls, but we don't want to
4665 ;; replace them, because that might change
4666 ;; the visual order. Likewise with PDF and
4667 ;; isolate controls.
4668 (+ pt (skip-chars-forward
4669 bidi-directional-non-controls-chars
4670 limit)))))
4671 ;; Replace any run of non-RTL characters by a single LRM.
4672 (if (null (re-search-forward category lim1 t))
4673 ;; No more characters of CATEGORY, we are done.
4674 (setq pt limit)
4675 (replace-match replacement nil t)
4676 (move-marker pt (point)))
4677 (setq old-pt pt)
4678 ;; Skip directional controls, if any.
4679 (move-marker
4680 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4682 (defun squeeze-bidi-context (from to)
4683 "Replace characters between FROM and TO while keeping bidi context.
4685 This function replaces the region of text with as few characters
4686 as possible, while preserving the effect that region will have on
4687 bidirectional display before and after the region."
4688 (let ((start (set-marker (make-marker)
4689 (if (> from 0) from (+ (point-max) from))))
4690 (end (set-marker (make-marker) to))
4691 ;; This is for when they copy text with read-only text
4692 ;; properties.
4693 (inhibit-read-only t))
4694 (if (null (marker-position end))
4695 (setq end (point-max-marker)))
4696 ;; Replace each run of non-RTL characters with a single LRM.
4697 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4698 ;; Replace each run of non-LTR characters with a single RLM. Note
4699 ;; that the \cR category includes both the Arabic Letter (AL) and
4700 ;; R characters; here we ignore the distinction between them,
4701 ;; because that distinction only affects Arabic Number (AN)
4702 ;; characters, which are weak and don't affect the reordering.
4703 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4705 (defun line-substring-with-bidi-context (start end &optional no-properties)
4706 "Return buffer text between START and END with its bidi context.
4708 START and END are assumed to belong to the same physical line
4709 of buffer text. This function prepends and appends to the text
4710 between START and END bidi control characters that preserve the
4711 visual order of that text when it is inserted at some other place."
4712 (if (or (< start (point-min))
4713 (> end (point-max)))
4714 (signal 'args-out-of-range (list (current-buffer) start end)))
4715 (let ((buf (current-buffer))
4716 substr para-dir from to)
4717 (save-excursion
4718 (goto-char start)
4719 (setq para-dir (current-bidi-paragraph-direction))
4720 (setq from (line-beginning-position)
4721 to (line-end-position))
4722 (goto-char from)
4723 ;; If we don't have any mixed directional characters in the
4724 ;; entire line, we can just copy the substring without adding
4725 ;; any context.
4726 (if (or (looking-at-p "\\CR*$")
4727 (looking-at-p "\\CL*$"))
4728 (setq substr (if no-properties
4729 (buffer-substring-no-properties start end)
4730 (buffer-substring start end)))
4731 (setq substr
4732 (with-temp-buffer
4733 (if no-properties
4734 (insert-buffer-substring-no-properties buf from to)
4735 (insert-buffer-substring buf from to))
4736 (squeeze-bidi-context 1 (1+ (- start from)))
4737 (squeeze-bidi-context (- end to) nil)
4738 (buffer-substring 1 (point-max)))))
4740 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4741 ;; (1) force the string to have the same base embedding
4742 ;; direction as the paragraph direction at the source, no matter
4743 ;; what is the paragraph direction at destination; and (2) avoid
4744 ;; affecting the visual order of the surrounding text at
4745 ;; destination if there are characters of different
4746 ;; directionality there.
4747 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4748 substr "\x2069"))))
4750 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4751 "Return portion of current buffer between START and END with bidi context.
4753 This function works similar to `buffer-substring', but it prepends and
4754 appends to the text bidi directional control characters necessary to
4755 preserve the visual appearance of the text if it is inserted at another
4756 place. This is useful when the buffer substring includes bidirectional
4757 text and control characters that cause non-trivial reordering on display.
4758 If copied verbatim, such text can have a very different visual appearance,
4759 and can also change the visual appearance of the surrounding text at the
4760 destination of the copy.
4762 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4763 the text properties."
4764 (let (line-end substr)
4765 (if (or (< start (point-min))
4766 (> end (point-max)))
4767 (signal 'args-out-of-range (list (current-buffer) start end)))
4768 (save-excursion
4769 (goto-char start)
4770 (setq line-end (min end (line-end-position)))
4771 (while (< start end)
4772 (setq substr
4773 (concat substr
4774 (if substr "\n" "")
4775 (line-substring-with-bidi-context start line-end
4776 no-properties)))
4777 (forward-line 1)
4778 (setq start (point))
4779 (setq line-end (min end (line-end-position))))
4780 substr)))
4782 ;; Yanking.
4784 (defcustom yank-handled-properties
4785 '((font-lock-face . yank-handle-font-lock-face-property)
4786 (category . yank-handle-category-property))
4787 "List of special text property handling conditions for yanking.
4788 Each element should have the form (PROP . FUN), where PROP is a
4789 property symbol and FUN is a function. When the `yank' command
4790 inserts text into the buffer, it scans the inserted text for
4791 stretches of text that have `eq' values of the text property
4792 PROP; for each such stretch of text, FUN is called with three
4793 arguments: the property's value in that text, and the start and
4794 end positions of the text.
4796 This is done prior to removing the properties specified by
4797 `yank-excluded-properties'."
4798 :group 'killing
4799 :type '(repeat (cons (symbol :tag "property symbol")
4800 function))
4801 :version "24.3")
4803 ;; This is actually used in subr.el but defcustom does not work there.
4804 (defcustom yank-excluded-properties
4805 '(category field follow-link fontified font-lock-face help-echo
4806 intangible invisible keymap local-map mouse-face read-only
4807 yank-handler)
4808 "Text properties to discard when yanking.
4809 The value should be a list of text properties to discard or t,
4810 which means to discard all text properties.
4812 See also `yank-handled-properties'."
4813 :type '(choice (const :tag "All" t) (repeat symbol))
4814 :group 'killing
4815 :version "24.3")
4817 (defvar yank-window-start nil)
4818 (defvar yank-undo-function nil
4819 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4820 Function is called with two parameters, START and END corresponding to
4821 the value of the mark and point; it is guaranteed that START <= END.
4822 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4824 (defun yank-pop (&optional arg)
4825 "Replace just-yanked stretch of killed text with a different stretch.
4826 This command is allowed only immediately after a `yank' or a `yank-pop'.
4827 At such a time, the region contains a stretch of reinserted
4828 previously-killed text. `yank-pop' deletes that text and inserts in its
4829 place a different stretch of killed text.
4831 With no argument, the previous kill is inserted.
4832 With argument N, insert the Nth previous kill.
4833 If N is negative, this is a more recent kill.
4835 The sequence of kills wraps around, so that after the oldest one
4836 comes the newest one.
4838 This command honors the `yank-handled-properties' and
4839 `yank-excluded-properties' variables, and the `yank-handler' text
4840 property, in the way that `yank' does."
4841 (interactive "*p")
4842 (if (not (eq last-command 'yank))
4843 (user-error "Previous command was not a yank"))
4844 (setq this-command 'yank)
4845 (unless arg (setq arg 1))
4846 (let ((inhibit-read-only t)
4847 (before (< (point) (mark t))))
4848 (if before
4849 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4850 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4851 (setq yank-undo-function nil)
4852 (set-marker (mark-marker) (point) (current-buffer))
4853 (insert-for-yank (current-kill arg))
4854 ;; Set the window start back where it was in the yank command,
4855 ;; if possible.
4856 (set-window-start (selected-window) yank-window-start t)
4857 (if before
4858 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4859 ;; It is cleaner to avoid activation, even though the command
4860 ;; loop would deactivate the mark because we inserted text.
4861 (goto-char (prog1 (mark t)
4862 (set-marker (mark-marker) (point) (current-buffer))))))
4863 nil)
4865 (defun yank (&optional arg)
4866 "Reinsert (\"paste\") the last stretch of killed text.
4867 More precisely, reinsert the most recent kill, which is the
4868 stretch of killed text most recently killed OR yanked. Put point
4869 at the end, and set mark at the beginning without activating it.
4870 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4871 With argument N, reinsert the Nth most recent kill.
4873 This command honors the `yank-handled-properties' and
4874 `yank-excluded-properties' variables, and the `yank-handler' text
4875 property, as described below.
4877 Properties listed in `yank-handled-properties' are processed,
4878 then those listed in `yank-excluded-properties' are discarded.
4880 If STRING has a non-nil `yank-handler' property anywhere, the
4881 normal insert behavior is altered, and instead, for each contiguous
4882 segment of STRING that has a given value of the `yank-handler'
4883 property, that value is used as follows:
4885 The value of a `yank-handler' property must be a list of one to four
4886 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4887 FUNCTION, if non-nil, should be a function of one argument (the
4888 object to insert); FUNCTION is called instead of `insert'.
4889 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4890 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4891 PARAM may be a list of strings to insert as a rectangle). If PARAM
4892 is nil, then the current segment of STRING is used.
4893 If NOEXCLUDE is present and non-nil, the normal removal of
4894 `yank-excluded-properties' is not performed; instead FUNCTION is
4895 responsible for the removal. This may be necessary if FUNCTION
4896 adjusts point before or after inserting the object.
4897 UNDO, if present and non-nil, should be a function to be called
4898 by `yank-pop' to undo the insertion of the current PARAM. It is
4899 given two arguments, the start and end of the region. FUNCTION
4900 may set `yank-undo-function' to override UNDO.
4902 See also the command `yank-pop' (\\[yank-pop])."
4903 (interactive "*P")
4904 (setq yank-window-start (window-start))
4905 ;; If we don't get all the way thru, make last-command indicate that
4906 ;; for the following command.
4907 (setq this-command t)
4908 (push-mark)
4909 (insert-for-yank (current-kill (cond
4910 ((listp arg) 0)
4911 ((eq arg '-) -2)
4912 (t (1- arg)))))
4913 (if (consp arg)
4914 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4915 ;; It is cleaner to avoid activation, even though the command
4916 ;; loop would deactivate the mark because we inserted text.
4917 (goto-char (prog1 (mark t)
4918 (set-marker (mark-marker) (point) (current-buffer)))))
4919 ;; If we do get all the way thru, make this-command indicate that.
4920 (if (eq this-command t)
4921 (setq this-command 'yank))
4922 nil)
4924 (defun rotate-yank-pointer (arg)
4925 "Rotate the yanking point in the kill ring.
4926 With ARG, rotate that many kills forward (or backward, if negative)."
4927 (interactive "p")
4928 (current-kill arg))
4930 ;; Some kill commands.
4932 ;; Internal subroutine of delete-char
4933 (defun kill-forward-chars (arg)
4934 (if (listp arg) (setq arg (car arg)))
4935 (if (eq arg '-) (setq arg -1))
4936 (kill-region (point) (+ (point) arg)))
4938 ;; Internal subroutine of backward-delete-char
4939 (defun kill-backward-chars (arg)
4940 (if (listp arg) (setq arg (car arg)))
4941 (if (eq arg '-) (setq arg -1))
4942 (kill-region (point) (- (point) arg)))
4944 (defcustom backward-delete-char-untabify-method 'untabify
4945 "The method for untabifying when deleting backward.
4946 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4947 `hungry' -- delete all whitespace, both tabs and spaces;
4948 `all' -- delete all whitespace, including tabs, spaces and newlines;
4949 nil -- just delete one character."
4950 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4951 :version "20.3"
4952 :group 'killing)
4954 (defun backward-delete-char-untabify (arg &optional killp)
4955 "Delete characters backward, changing tabs into spaces.
4956 The exact behavior depends on `backward-delete-char-untabify-method'.
4957 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4958 Interactively, ARG is the prefix arg (default 1)
4959 and KILLP is t if a prefix arg was specified."
4960 (interactive "*p\nP")
4961 (when (eq backward-delete-char-untabify-method 'untabify)
4962 (let ((count arg))
4963 (save-excursion
4964 (while (and (> count 0) (not (bobp)))
4965 (if (= (preceding-char) ?\t)
4966 (let ((col (current-column)))
4967 (forward-char -1)
4968 (setq col (- col (current-column)))
4969 (insert-char ?\s col)
4970 (delete-char 1)))
4971 (forward-char -1)
4972 (setq count (1- count))))))
4973 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4974 ((eq backward-delete-char-untabify-method 'all)
4975 " \t\n\r")))
4976 (n (if skip
4977 (let* ((oldpt (point))
4978 (wh (- oldpt (save-excursion
4979 (skip-chars-backward skip)
4980 (constrain-to-field nil oldpt)))))
4981 (+ arg (if (zerop wh) 0 (1- wh))))
4982 arg)))
4983 ;; Avoid warning about delete-backward-char
4984 (with-no-warnings (delete-backward-char n killp))))
4986 (defun zap-to-char (arg char)
4987 "Kill up to and including ARGth occurrence of CHAR.
4988 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4989 Goes backward if ARG is negative; error if CHAR not found."
4990 (interactive (list (prefix-numeric-value current-prefix-arg)
4991 (read-char "Zap to char: " t)))
4992 ;; Avoid "obsolete" warnings for translation-table-for-input.
4993 (with-no-warnings
4994 (if (char-table-p translation-table-for-input)
4995 (setq char (or (aref translation-table-for-input char) char))))
4996 (kill-region (point) (progn
4997 (search-forward (char-to-string char) nil nil arg)
4998 (point))))
5000 ;; kill-line and its subroutines.
5002 (defcustom kill-whole-line nil
5003 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
5004 :type 'boolean
5005 :group 'killing)
5007 (defun kill-line (&optional arg)
5008 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
5009 With prefix argument ARG, kill that many lines from point.
5010 Negative arguments kill lines backward.
5011 With zero argument, kills the text before point on the current line.
5013 When calling from a program, nil means \"no arg\",
5014 a number counts as a prefix arg.
5016 To kill a whole line, when point is not at the beginning, type \
5017 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
5019 If `show-trailing-whitespace' is non-nil, this command will just
5020 kill the rest of the current line, even if there are no nonblanks
5021 there.
5023 If option `kill-whole-line' is non-nil, then this command kills the whole line
5024 including its terminating newline, when used at the beginning of a line
5025 with no argument. As a consequence, you can always kill a whole line
5026 by typing \\[move-beginning-of-line] \\[kill-line].
5028 If you want to append the killed line to the last killed text,
5029 use \\[append-next-kill] before \\[kill-line].
5031 If the buffer is read-only, Emacs will beep and refrain from deleting
5032 the line, but put the line in the kill ring anyway. This means that
5033 you can use this command to copy text from a read-only buffer.
5034 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5035 even beep.)"
5036 (interactive "P")
5037 (kill-region (point)
5038 ;; It is better to move point to the other end of the kill
5039 ;; before killing. That way, in a read-only buffer, point
5040 ;; moves across the text that is copied to the kill ring.
5041 ;; The choice has no effect on undo now that undo records
5042 ;; the value of point from before the command was run.
5043 (progn
5044 (if arg
5045 (forward-visible-line (prefix-numeric-value arg))
5046 (if (eobp)
5047 (signal 'end-of-buffer nil))
5048 (let ((end
5049 (save-excursion
5050 (end-of-visible-line) (point))))
5051 (if (or (save-excursion
5052 ;; If trailing whitespace is visible,
5053 ;; don't treat it as nothing.
5054 (unless show-trailing-whitespace
5055 (skip-chars-forward " \t" end))
5056 (= (point) end))
5057 (and kill-whole-line (bolp)))
5058 (forward-visible-line 1)
5059 (goto-char end))))
5060 (point))))
5062 (defun kill-whole-line (&optional arg)
5063 "Kill current line.
5064 With prefix ARG, kill that many lines starting from the current line.
5065 If ARG is negative, kill backward. Also kill the preceding newline.
5066 \(This is meant to make \\[repeat] work well with negative arguments.)
5067 If ARG is zero, kill current line but exclude the trailing newline."
5068 (interactive "p")
5069 (or arg (setq arg 1))
5070 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5071 (signal 'end-of-buffer nil))
5072 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5073 (signal 'beginning-of-buffer nil))
5074 (unless (eq last-command 'kill-region)
5075 (kill-new "")
5076 (setq last-command 'kill-region))
5077 (cond ((zerop arg)
5078 ;; We need to kill in two steps, because the previous command
5079 ;; could have been a kill command, in which case the text
5080 ;; before point needs to be prepended to the current kill
5081 ;; ring entry and the text after point appended. Also, we
5082 ;; need to use save-excursion to avoid copying the same text
5083 ;; twice to the kill ring in read-only buffers.
5084 (save-excursion
5085 (kill-region (point) (progn (forward-visible-line 0) (point))))
5086 (kill-region (point) (progn (end-of-visible-line) (point))))
5087 ((< arg 0)
5088 (save-excursion
5089 (kill-region (point) (progn (end-of-visible-line) (point))))
5090 (kill-region (point)
5091 (progn (forward-visible-line (1+ arg))
5092 (unless (bobp) (backward-char))
5093 (point))))
5095 (save-excursion
5096 (kill-region (point) (progn (forward-visible-line 0) (point))))
5097 (kill-region (point)
5098 (progn (forward-visible-line arg) (point))))))
5100 (defun forward-visible-line (arg)
5101 "Move forward by ARG lines, ignoring currently invisible newlines only.
5102 If ARG is negative, move backward -ARG lines.
5103 If ARG is zero, move to the beginning of the current line."
5104 (condition-case nil
5105 (if (> arg 0)
5106 (progn
5107 (while (> arg 0)
5108 (or (zerop (forward-line 1))
5109 (signal 'end-of-buffer nil))
5110 ;; If the newline we just skipped is invisible,
5111 ;; don't count it.
5112 (let ((prop
5113 (get-char-property (1- (point)) 'invisible)))
5114 (if (if (eq buffer-invisibility-spec t)
5115 prop
5116 (or (memq prop buffer-invisibility-spec)
5117 (assq prop buffer-invisibility-spec)))
5118 (setq arg (1+ arg))))
5119 (setq arg (1- arg)))
5120 ;; If invisible text follows, and it is a number of complete lines,
5121 ;; skip it.
5122 (let ((opoint (point)))
5123 (while (and (not (eobp))
5124 (let ((prop
5125 (get-char-property (point) 'invisible)))
5126 (if (eq buffer-invisibility-spec t)
5127 prop
5128 (or (memq prop buffer-invisibility-spec)
5129 (assq prop buffer-invisibility-spec)))))
5130 (goto-char
5131 (if (get-text-property (point) 'invisible)
5132 (or (next-single-property-change (point) 'invisible)
5133 (point-max))
5134 (next-overlay-change (point)))))
5135 (unless (bolp)
5136 (goto-char opoint))))
5137 (let ((first t))
5138 (while (or first (<= arg 0))
5139 (if first
5140 (beginning-of-line)
5141 (or (zerop (forward-line -1))
5142 (signal 'beginning-of-buffer nil)))
5143 ;; If the newline we just moved to is invisible,
5144 ;; don't count it.
5145 (unless (bobp)
5146 (let ((prop
5147 (get-char-property (1- (point)) 'invisible)))
5148 (unless (if (eq buffer-invisibility-spec t)
5149 prop
5150 (or (memq prop buffer-invisibility-spec)
5151 (assq prop buffer-invisibility-spec)))
5152 (setq arg (1+ arg)))))
5153 (setq first nil))
5154 ;; If invisible text follows, and it is a number of complete lines,
5155 ;; skip it.
5156 (let ((opoint (point)))
5157 (while (and (not (bobp))
5158 (let ((prop
5159 (get-char-property (1- (point)) 'invisible)))
5160 (if (eq buffer-invisibility-spec t)
5161 prop
5162 (or (memq prop buffer-invisibility-spec)
5163 (assq prop buffer-invisibility-spec)))))
5164 (goto-char
5165 (if (get-text-property (1- (point)) 'invisible)
5166 (or (previous-single-property-change (point) 'invisible)
5167 (point-min))
5168 (previous-overlay-change (point)))))
5169 (unless (bolp)
5170 (goto-char opoint)))))
5171 ((beginning-of-buffer end-of-buffer)
5172 nil)))
5174 (defun end-of-visible-line ()
5175 "Move to end of current visible line."
5176 (end-of-line)
5177 ;; If the following character is currently invisible,
5178 ;; skip all characters with that same `invisible' property value,
5179 ;; then find the next newline.
5180 (while (and (not (eobp))
5181 (save-excursion
5182 (skip-chars-forward "^\n")
5183 (let ((prop
5184 (get-char-property (point) 'invisible)))
5185 (if (eq buffer-invisibility-spec t)
5186 prop
5187 (or (memq prop buffer-invisibility-spec)
5188 (assq prop buffer-invisibility-spec))))))
5189 (skip-chars-forward "^\n")
5190 (if (get-text-property (point) 'invisible)
5191 (goto-char (or (next-single-property-change (point) 'invisible)
5192 (point-max)))
5193 (goto-char (next-overlay-change (point))))
5194 (end-of-line)))
5196 (defun kill-current-buffer ()
5197 "Kill the current buffer.
5198 When called in the minibuffer, get out of the minibuffer
5199 using `abort-recursive-edit'.
5201 This is like `kill-this-buffer', but it doesn't have to be invoked
5202 via the menu bar, and pays no attention to the menu-bar's frame."
5203 (interactive)
5204 (let ((frame (selected-frame)))
5205 (if (and (frame-live-p frame)
5206 (not (window-minibuffer-p (frame-selected-window frame))))
5207 (kill-buffer (current-buffer))
5208 (abort-recursive-edit))))
5211 (defun insert-buffer (buffer)
5212 "Insert after point the contents of BUFFER.
5213 Puts mark after the inserted text.
5214 BUFFER may be a buffer or a buffer name."
5215 (declare (interactive-only insert-buffer-substring))
5216 (interactive
5217 (list
5218 (progn
5219 (barf-if-buffer-read-only)
5220 (read-buffer "Insert buffer: "
5221 (if (eq (selected-window) (next-window))
5222 (other-buffer (current-buffer))
5223 (window-buffer (next-window)))
5224 t))))
5225 (push-mark
5226 (save-excursion
5227 (insert-buffer-substring (get-buffer buffer))
5228 (point)))
5229 nil)
5231 (defun append-to-buffer (buffer start end)
5232 "Append to specified buffer the text of the region.
5233 It is inserted into that buffer before its point.
5235 When calling from a program, give three arguments:
5236 BUFFER (or buffer name), START and END.
5237 START and END specify the portion of the current buffer to be copied."
5238 (interactive
5239 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5240 (region-beginning) (region-end)))
5241 (let* ((oldbuf (current-buffer))
5242 (append-to (get-buffer-create buffer))
5243 (windows (get-buffer-window-list append-to t t))
5244 point)
5245 (save-excursion
5246 (with-current-buffer append-to
5247 (setq point (point))
5248 (barf-if-buffer-read-only)
5249 (insert-buffer-substring oldbuf start end)
5250 (dolist (window windows)
5251 (when (= (window-point window) point)
5252 (set-window-point window (point))))))))
5254 (defun prepend-to-buffer (buffer start end)
5255 "Prepend to specified buffer the text of the region.
5256 It is inserted into that buffer after its point.
5258 When calling from a program, give three arguments:
5259 BUFFER (or buffer name), START and END.
5260 START and END specify the portion of the current buffer to be copied."
5261 (interactive "BPrepend to buffer: \nr")
5262 (let ((oldbuf (current-buffer)))
5263 (with-current-buffer (get-buffer-create buffer)
5264 (barf-if-buffer-read-only)
5265 (save-excursion
5266 (insert-buffer-substring oldbuf start end)))))
5268 (defun copy-to-buffer (buffer start end)
5269 "Copy to specified buffer the text of the region.
5270 It is inserted into that buffer, replacing existing text there.
5272 When calling from a program, give three arguments:
5273 BUFFER (or buffer name), START and END.
5274 START and END specify the portion of the current buffer to be copied."
5275 (interactive "BCopy to buffer: \nr")
5276 (let ((oldbuf (current-buffer)))
5277 (with-current-buffer (get-buffer-create buffer)
5278 (barf-if-buffer-read-only)
5279 (erase-buffer)
5280 (save-excursion
5281 (insert-buffer-substring oldbuf start end)))))
5283 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5285 (defvar activate-mark-hook nil
5286 "Hook run when the mark becomes active.
5287 It is also run at the end of a command, if the mark is active and
5288 it is possible that the region may have changed.")
5290 (defvar deactivate-mark-hook nil
5291 "Hook run when the mark becomes inactive.")
5293 (defun mark (&optional force)
5294 "Return this buffer's mark value as integer, or nil if never set.
5296 In Transient Mark mode, this function signals an error if
5297 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5298 or the argument FORCE is non-nil, it disregards whether the mark
5299 is active, and returns an integer or nil in the usual way.
5301 If you are using this in an editing command, you are most likely making
5302 a mistake; see the documentation of `set-mark'."
5303 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5304 (marker-position (mark-marker))
5305 (signal 'mark-inactive nil)))
5307 ;; Behind display-selections-p.
5309 (defun deactivate-mark (&optional force)
5310 "Deactivate the mark.
5311 If Transient Mark mode is disabled, this function normally does
5312 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5314 Deactivating the mark sets `mark-active' to nil, updates the
5315 primary selection according to `select-active-regions', and runs
5316 `deactivate-mark-hook'.
5318 If Transient Mark mode was temporarily enabled, reset the value
5319 of the variable `transient-mark-mode'; if this causes Transient
5320 Mark mode to be disabled, don't change `mark-active' to nil or
5321 run `deactivate-mark-hook'."
5322 (when (or (region-active-p) force)
5323 (when (and (if (eq select-active-regions 'only)
5324 (eq (car-safe transient-mark-mode) 'only)
5325 select-active-regions)
5326 (region-active-p)
5327 (display-selections-p))
5328 ;; The var `saved-region-selection', if non-nil, is the text in
5329 ;; the region prior to the last command modifying the buffer.
5330 ;; Set the selection to that, or to the current region.
5331 (cond (saved-region-selection
5332 (if (gui-backend-selection-owner-p 'PRIMARY)
5333 (gui-set-selection 'PRIMARY saved-region-selection))
5334 (setq saved-region-selection nil))
5335 ;; If another program has acquired the selection, region
5336 ;; deactivation should not clobber it (Bug#11772).
5337 ((and (/= (region-beginning) (region-end))
5338 (or (gui-backend-selection-owner-p 'PRIMARY)
5339 (null (gui-backend-selection-exists-p 'PRIMARY))))
5340 (gui-set-selection 'PRIMARY
5341 (funcall region-extract-function nil)))))
5342 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5343 (cond
5344 ((eq (car-safe transient-mark-mode) 'only)
5345 (setq transient-mark-mode (cdr transient-mark-mode))
5346 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5347 (kill-local-variable 'transient-mark-mode)))
5348 ((eq transient-mark-mode 'lambda)
5349 (kill-local-variable 'transient-mark-mode)))
5350 (setq mark-active nil)
5351 (run-hooks 'deactivate-mark-hook)
5352 (redisplay--update-region-highlight (selected-window))))
5354 (defun activate-mark (&optional no-tmm)
5355 "Activate the mark.
5356 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5357 (when (mark t)
5358 (unless (region-active-p)
5359 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5360 (setq mark-active t)
5361 (unless (or transient-mark-mode no-tmm)
5362 (setq-local transient-mark-mode 'lambda))
5363 (run-hooks 'activate-mark-hook))))
5365 (defun set-mark (pos)
5366 "Set this buffer's mark to POS. Don't use this function!
5367 That is to say, don't use this function unless you want
5368 the user to see that the mark has moved, and you want the previous
5369 mark position to be lost.
5371 Normally, when a new mark is set, the old one should go on the stack.
5372 This is why most applications should use `push-mark', not `set-mark'.
5374 Novice Emacs Lisp programmers often try to use the mark for the wrong
5375 purposes. The mark saves a location for the user's convenience.
5376 Most editing commands should not alter the mark.
5377 To remember a location for internal use in the Lisp program,
5378 store it in a Lisp variable. Example:
5380 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5381 (if pos
5382 (progn
5383 (set-marker (mark-marker) pos (current-buffer))
5384 (activate-mark 'no-tmm))
5385 ;; Normally we never clear mark-active except in Transient Mark mode.
5386 ;; But when we actually clear out the mark value too, we must
5387 ;; clear mark-active in any mode.
5388 (deactivate-mark t)
5389 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5390 ;; it should never be nil if the mark is nil.
5391 (setq mark-active nil)
5392 (set-marker (mark-marker) nil)))
5394 (defun save-mark-and-excursion--save ()
5395 (cons
5396 (let ((mark (mark-marker)))
5397 (and (marker-position mark) (copy-marker mark)))
5398 mark-active))
5400 (defun save-mark-and-excursion--restore (saved-mark-info)
5401 (let ((saved-mark (car saved-mark-info))
5402 (omark (marker-position (mark-marker)))
5403 (nmark nil)
5404 (saved-mark-active (cdr saved-mark-info)))
5405 ;; Mark marker
5406 (if (null saved-mark)
5407 (set-marker (mark-marker) nil)
5408 (setf nmark (marker-position saved-mark))
5409 (set-marker (mark-marker) nmark)
5410 (set-marker saved-mark nil))
5411 ;; Mark active
5412 (let ((cur-mark-active mark-active))
5413 (setq mark-active saved-mark-active)
5414 ;; If mark is active now, and either was not active or was at a
5415 ;; different place, run the activate hook.
5416 (if saved-mark-active
5417 (when (or (not cur-mark-active)
5418 (not (eq omark nmark)))
5419 (run-hooks 'activate-mark-hook))
5420 ;; If mark has ceased to be active, run deactivate hook.
5421 (when cur-mark-active
5422 (run-hooks 'deactivate-mark-hook))))))
5424 (defmacro save-mark-and-excursion (&rest body)
5425 "Like `save-excursion', but also save and restore the mark state.
5426 This macro does what `save-excursion' did before Emacs 25.1."
5427 (declare (indent 0) (debug t))
5428 (let ((saved-marker-sym (make-symbol "saved-marker")))
5429 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5430 (unwind-protect
5431 (save-excursion ,@body)
5432 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5434 (defcustom use-empty-active-region nil
5435 "Whether \"region-aware\" commands should act on empty regions.
5436 If nil, region-aware commands treat the empty region as inactive.
5437 If non-nil, region-aware commands treat the region as active as
5438 long as the mark is active, even if the region is empty.
5440 Region-aware commands are those that act on the region if it is
5441 active and Transient Mark mode is enabled, and on the text near
5442 point otherwise."
5443 :type 'boolean
5444 :version "23.1"
5445 :group 'editing-basics)
5447 (defun use-region-p ()
5448 "Return t if the region is active and it is appropriate to act on it.
5449 This is used by commands that act specially on the region under
5450 Transient Mark mode.
5452 The return value is t if Transient Mark mode is enabled and the
5453 mark is active; furthermore, if `use-empty-active-region' is nil,
5454 the region must not be empty. Otherwise, the return value is nil.
5456 For some commands, it may be appropriate to ignore the value of
5457 `use-empty-active-region'; in that case, use `region-active-p'."
5458 (and (region-active-p)
5459 (or use-empty-active-region (> (region-end) (region-beginning)))))
5461 (defun region-active-p ()
5462 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5464 Some commands act specially on the region when Transient Mark
5465 mode is enabled. Usually, such commands should use
5466 `use-region-p' instead of this function, because `use-region-p'
5467 also checks the value of `use-empty-active-region'."
5468 (and transient-mark-mode mark-active
5469 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5470 ;; without the mark being set (e.g. bug#17324). We really should fix
5471 ;; that problem, but in the mean time, let's make sure we don't say the
5472 ;; region is active when there's no mark.
5473 (progn (cl-assert (mark)) t)))
5475 (defun region-bounds ()
5476 "Return the boundaries of the region as a pair of positions.
5477 Value is a cons cell of the form (START . END)."
5478 (funcall region-extract-function 'bounds))
5480 (defun region-noncontiguous-p ()
5481 "Return non-nil if the region contains several pieces.
5482 An example is a rectangular region handled as a list of
5483 separate contiguous regions for each line."
5484 (> (length (region-bounds)) 1))
5486 (defvar redisplay-unhighlight-region-function
5487 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5489 (defvar redisplay-highlight-region-function
5490 (lambda (start end window rol)
5491 (if (not (overlayp rol))
5492 (let ((nrol (make-overlay start end)))
5493 (funcall redisplay-unhighlight-region-function rol)
5494 (overlay-put nrol 'window window)
5495 (overlay-put nrol 'face 'region)
5496 ;; Normal priority so that a large region doesn't hide all the
5497 ;; overlays within it, but high secondary priority so that if it
5498 ;; ends/starts in the middle of a small overlay, that small overlay
5499 ;; won't hide the region's boundaries.
5500 (overlay-put nrol 'priority '(nil . 100))
5501 nrol)
5502 (unless (and (eq (overlay-buffer rol) (current-buffer))
5503 (eq (overlay-start rol) start)
5504 (eq (overlay-end rol) end))
5505 (move-overlay rol start end (current-buffer)))
5506 rol)))
5508 (defun redisplay--update-region-highlight (window)
5509 (let ((rol (window-parameter window 'internal-region-overlay)))
5510 (if (not (and (region-active-p)
5511 (or highlight-nonselected-windows
5512 (eq window (selected-window))
5513 (and (window-minibuffer-p)
5514 (eq window (minibuffer-selected-window))))))
5515 (funcall redisplay-unhighlight-region-function rol)
5516 (let* ((pt (window-point window))
5517 (mark (mark))
5518 (start (min pt mark))
5519 (end (max pt mark))
5520 (new
5521 (funcall redisplay-highlight-region-function
5522 start end window rol)))
5523 (unless (equal new rol)
5524 (set-window-parameter window 'internal-region-overlay
5525 new))))))
5527 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5528 "Hook run just before redisplay.
5529 It is called in each window that is to be redisplayed. It takes one argument,
5530 which is the window that will be redisplayed. When run, the `current-buffer'
5531 is set to the buffer displayed in that window.")
5533 (defun redisplay--pre-redisplay-functions (windows)
5534 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5535 (if (null windows)
5536 (with-current-buffer (window-buffer (selected-window))
5537 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5538 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5539 (with-current-buffer (window-buffer win)
5540 (run-hook-with-args 'pre-redisplay-functions win))))))
5542 (add-function :before pre-redisplay-function
5543 #'redisplay--pre-redisplay-functions)
5546 (defvar-local mark-ring nil
5547 "The list of former marks of the current buffer, most recent first.")
5548 (put 'mark-ring 'permanent-local t)
5550 (defcustom mark-ring-max 16
5551 "Maximum size of mark ring. Start discarding off end if gets this big."
5552 :type 'integer
5553 :group 'editing-basics)
5555 (defvar global-mark-ring nil
5556 "The list of saved global marks, most recent first.")
5558 (defcustom global-mark-ring-max 16
5559 "Maximum size of global mark ring. \
5560 Start discarding off end if gets this big."
5561 :type 'integer
5562 :group 'editing-basics)
5564 (defun pop-to-mark-command ()
5565 "Jump to mark, and pop a new position for mark off the ring.
5566 \(Does not affect global mark ring)."
5567 (interactive)
5568 (if (null (mark t))
5569 (user-error "No mark set in this buffer")
5570 (if (= (point) (mark t))
5571 (message "Mark popped"))
5572 (goto-char (mark t))
5573 (pop-mark)))
5575 (defun push-mark-command (arg &optional nomsg)
5576 "Set mark at where point is.
5577 If no prefix ARG and mark is already set there, just activate it.
5578 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5579 (interactive "P")
5580 (let ((mark (mark t)))
5581 (if (or arg (null mark) (/= mark (point)))
5582 (push-mark nil nomsg t)
5583 (activate-mark 'no-tmm)
5584 (unless nomsg
5585 (message "Mark activated")))))
5587 (defcustom set-mark-command-repeat-pop nil
5588 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5589 That means that C-u \\[set-mark-command] \\[set-mark-command]
5590 will pop the mark twice, and
5591 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5592 will pop the mark three times.
5594 A value of nil means \\[set-mark-command]'s behavior does not change
5595 after C-u \\[set-mark-command]."
5596 :type 'boolean
5597 :group 'editing-basics)
5599 (defun set-mark-command (arg)
5600 "Set the mark where point is, and activate it; or jump to the mark.
5601 Setting the mark also alters the region, which is the text
5602 between point and mark; this is the closest equivalent in
5603 Emacs to what some editors call the \"selection\".
5605 With no prefix argument, set the mark at point, and push the
5606 old mark position on local mark ring. Also push the new mark on
5607 global mark ring, if the previous mark was set in another buffer.
5609 When Transient Mark Mode is off, immediately repeating this
5610 command activates `transient-mark-mode' temporarily.
5612 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5613 jump to the mark, and set the mark from
5614 position popped off the local mark ring (this does not affect the global
5615 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5616 mark ring (see `pop-global-mark').
5618 If `set-mark-command-repeat-pop' is non-nil, repeating
5619 the \\[set-mark-command] command with no prefix argument pops the next position
5620 off the local (or global) mark ring and jumps there.
5622 With \\[universal-argument] \\[universal-argument] as prefix
5623 argument, unconditionally set mark where point is, even if
5624 `set-mark-command-repeat-pop' is non-nil.
5626 Novice Emacs Lisp programmers often try to use the mark for the wrong
5627 purposes. See the documentation of `set-mark' for more information."
5628 (interactive "P")
5629 (cond ((eq transient-mark-mode 'lambda)
5630 (kill-local-variable 'transient-mark-mode))
5631 ((eq (car-safe transient-mark-mode) 'only)
5632 (deactivate-mark)))
5633 (cond
5634 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5635 (push-mark-command nil))
5636 ((not (eq this-command 'set-mark-command))
5637 (if arg
5638 (pop-to-mark-command)
5639 (push-mark-command t)))
5640 ((and set-mark-command-repeat-pop
5641 (eq last-command 'pop-global-mark)
5642 (not arg))
5643 (setq this-command 'pop-global-mark)
5644 (pop-global-mark))
5645 ((or (and set-mark-command-repeat-pop
5646 (eq last-command 'pop-to-mark-command))
5647 arg)
5648 (setq this-command 'pop-to-mark-command)
5649 (pop-to-mark-command))
5650 ((eq last-command 'set-mark-command)
5651 (if (region-active-p)
5652 (progn
5653 (deactivate-mark)
5654 (message "Mark deactivated"))
5655 (activate-mark)
5656 (message "Mark activated")))
5658 (push-mark-command nil))))
5660 (defun push-mark (&optional location nomsg activate)
5661 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5662 If the last global mark pushed was not in the current buffer,
5663 also push LOCATION on the global mark ring.
5664 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5666 Novice Emacs Lisp programmers often try to use the mark for the wrong
5667 purposes. See the documentation of `set-mark' for more information.
5669 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5670 (unless (null (mark t))
5671 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5672 (when (> (length mark-ring) mark-ring-max)
5673 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5674 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5675 (set-marker (mark-marker) (or location (point)) (current-buffer))
5676 ;; Now push the mark on the global mark ring.
5677 (if (and global-mark-ring
5678 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5679 ;; The last global mark pushed was in this same buffer.
5680 ;; Don't push another one.
5682 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5683 (when (> (length global-mark-ring) global-mark-ring-max)
5684 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5685 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5686 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5687 (message "Mark set"))
5688 (if (or activate (not transient-mark-mode))
5689 (set-mark (mark t)))
5690 nil)
5692 (defun pop-mark ()
5693 "Pop off mark ring into the buffer's actual mark.
5694 Does not set point. Does nothing if mark ring is empty."
5695 (when mark-ring
5696 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5697 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5698 (move-marker (car mark-ring) nil)
5699 (if (null (mark t)) (ding))
5700 (setq mark-ring (cdr mark-ring)))
5701 (deactivate-mark))
5703 (define-obsolete-function-alias
5704 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5705 (defun exchange-point-and-mark (&optional arg)
5706 "Put the mark where point is now, and point where the mark is now.
5707 This command works even when the mark is not active,
5708 and it reactivates the mark.
5710 If Transient Mark mode is on, a prefix ARG deactivates the mark
5711 if it is active, and otherwise avoids reactivating it. If
5712 Transient Mark mode is off, a prefix ARG enables Transient Mark
5713 mode temporarily."
5714 (interactive "P")
5715 (let ((omark (mark t))
5716 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5717 (if (null omark)
5718 (user-error "No mark set in this buffer"))
5719 (set-mark (point))
5720 (goto-char omark)
5721 (cond (temp-highlight
5722 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5723 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5724 (not (or arg (region-active-p))))
5725 (deactivate-mark))
5726 (t (activate-mark)))
5727 nil))
5729 (defcustom shift-select-mode t
5730 "When non-nil, shifted motion keys activate the mark momentarily.
5732 While the mark is activated in this way, any shift-translated point
5733 motion key extends the region, and if Transient Mark mode was off, it
5734 is temporarily turned on. Furthermore, the mark will be deactivated
5735 by any subsequent point motion key that was not shift-translated, or
5736 by any action that normally deactivates the mark in Transient Mark mode.
5738 See `this-command-keys-shift-translated' for the meaning of
5739 shift-translation."
5740 :type 'boolean
5741 :group 'editing-basics)
5743 (defun handle-shift-selection ()
5744 "Activate/deactivate mark depending on invocation thru shift translation.
5745 This function is called by `call-interactively' when a command
5746 with a `^' character in its `interactive' spec is invoked, before
5747 running the command itself.
5749 If `shift-select-mode' is enabled and the command was invoked
5750 through shift translation, set the mark and activate the region
5751 temporarily, unless it was already set in this way. See
5752 `this-command-keys-shift-translated' for the meaning of shift
5753 translation.
5755 Otherwise, if the region has been activated temporarily,
5756 deactivate it, and restore the variable `transient-mark-mode' to
5757 its earlier value."
5758 (cond ((and shift-select-mode this-command-keys-shift-translated)
5759 (unless (and mark-active
5760 (eq (car-safe transient-mark-mode) 'only))
5761 (setq-local transient-mark-mode
5762 (cons 'only
5763 (unless (eq transient-mark-mode 'lambda)
5764 transient-mark-mode)))
5765 (push-mark nil nil t)))
5766 ((eq (car-safe transient-mark-mode) 'only)
5767 (setq transient-mark-mode (cdr transient-mark-mode))
5768 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5769 (kill-local-variable 'transient-mark-mode))
5770 (deactivate-mark))))
5772 (define-minor-mode transient-mark-mode
5773 "Toggle Transient Mark mode.
5774 With a prefix argument ARG, enable Transient Mark mode if ARG is
5775 positive, and disable it otherwise. If called from Lisp, enable
5776 Transient Mark mode if ARG is omitted or nil.
5778 Transient Mark mode is a global minor mode. When enabled, the
5779 region is highlighted with the `region' face whenever the mark
5780 is active. The mark is \"deactivated\" by changing the buffer,
5781 and after certain other operations that set the mark but whose
5782 main purpose is something else--for example, incremental search,
5783 \\[beginning-of-buffer], and \\[end-of-buffer].
5785 You can also deactivate the mark by typing \\[keyboard-quit] or
5786 \\[keyboard-escape-quit].
5788 Many commands change their behavior when Transient Mark mode is
5789 in effect and the mark is active, by acting on the region instead
5790 of their usual default part of the buffer's text. Examples of
5791 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5792 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5793 To see the documentation of commands which are sensitive to the
5794 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5795 or \"mark.*active\" at the prompt."
5796 :global t
5797 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5798 :variable (default-value 'transient-mark-mode))
5800 (defvar widen-automatically t
5801 "Non-nil means it is ok for commands to call `widen' when they want to.
5802 Some commands will do this in order to go to positions outside
5803 the current accessible part of the buffer.
5805 If `widen-automatically' is nil, these commands will do something else
5806 as a fallback, and won't change the buffer bounds.")
5808 (defvar non-essential nil
5809 "Whether the currently executing code is performing an essential task.
5810 This variable should be non-nil only when running code which should not
5811 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5812 user for a password when we are simply scanning a set of files in the
5813 background or displaying possible completions before the user even asked
5814 for it.")
5816 (defun pop-global-mark ()
5817 "Pop off global mark ring and jump to the top location."
5818 (interactive)
5819 ;; Pop entries which refer to non-existent buffers.
5820 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5821 (setq global-mark-ring (cdr global-mark-ring)))
5822 (or global-mark-ring
5823 (error "No global mark set"))
5824 (let* ((marker (car global-mark-ring))
5825 (buffer (marker-buffer marker))
5826 (position (marker-position marker)))
5827 (setq global-mark-ring (nconc (cdr global-mark-ring)
5828 (list (car global-mark-ring))))
5829 (set-buffer buffer)
5830 (or (and (>= position (point-min))
5831 (<= position (point-max)))
5832 (if widen-automatically
5833 (widen)
5834 (error "Global mark position is outside accessible part of buffer")))
5835 (goto-char position)
5836 (switch-to-buffer buffer)))
5838 (defcustom next-line-add-newlines nil
5839 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5840 :type 'boolean
5841 :version "21.1"
5842 :group 'editing-basics)
5844 (defun next-line (&optional arg try-vscroll)
5845 "Move cursor vertically down ARG lines.
5846 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5847 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5848 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5849 function will not vscroll.
5851 ARG defaults to 1.
5853 If there is no character in the target line exactly under the current column,
5854 the cursor is positioned after the character in that line which spans this
5855 column, or at the end of the line if it is not long enough.
5856 If there is no line in the buffer after this one, behavior depends on the
5857 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5858 to create a line, and moves the cursor to that line. Otherwise it moves the
5859 cursor to the end of the buffer.
5861 If the variable `line-move-visual' is non-nil, this command moves
5862 by display lines. Otherwise, it moves by buffer lines, without
5863 taking variable-width characters or continued lines into account.
5864 See \\[next-logical-line] for a command that always moves by buffer lines.
5866 The command \\[set-goal-column] can be used to create
5867 a semipermanent goal column for this command.
5868 Then instead of trying to move exactly vertically (or as close as possible),
5869 this command moves to the specified goal column (or as close as possible).
5870 The goal column is stored in the variable `goal-column', which is nil
5871 when there is no goal column. Note that setting `goal-column'
5872 overrides `line-move-visual' and causes this command to move by buffer
5873 lines rather than by display lines."
5874 (declare (interactive-only forward-line))
5875 (interactive "^p\np")
5876 (or arg (setq arg 1))
5877 (if (and next-line-add-newlines (= arg 1))
5878 (if (save-excursion (end-of-line) (eobp))
5879 ;; When adding a newline, don't expand an abbrev.
5880 (let ((abbrev-mode nil))
5881 (end-of-line)
5882 (insert (if use-hard-newlines hard-newline "\n")))
5883 (line-move arg nil nil try-vscroll))
5884 (if (called-interactively-p 'interactive)
5885 (condition-case err
5886 (line-move arg nil nil try-vscroll)
5887 ((beginning-of-buffer end-of-buffer)
5888 (signal (car err) (cdr err))))
5889 (line-move arg nil nil try-vscroll)))
5890 nil)
5892 (defun previous-line (&optional arg try-vscroll)
5893 "Move cursor vertically up ARG lines.
5894 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5895 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5896 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5897 function will not vscroll.
5899 ARG defaults to 1.
5901 If there is no character in the target line exactly over the current column,
5902 the cursor is positioned after the character in that line which spans this
5903 column, or at the end of the line if it is not long enough.
5905 If the variable `line-move-visual' is non-nil, this command moves
5906 by display lines. Otherwise, it moves by buffer lines, without
5907 taking variable-width characters or continued lines into account.
5908 See \\[previous-logical-line] for a command that always moves by buffer lines.
5910 The command \\[set-goal-column] can be used to create
5911 a semipermanent goal column for this command.
5912 Then instead of trying to move exactly vertically (or as close as possible),
5913 this command moves to the specified goal column (or as close as possible).
5914 The goal column is stored in the variable `goal-column', which is nil
5915 when there is no goal column. Note that setting `goal-column'
5916 overrides `line-move-visual' and causes this command to move by buffer
5917 lines rather than by display lines."
5918 (declare (interactive-only
5919 "use `forward-line' with negative argument instead."))
5920 (interactive "^p\np")
5921 (or arg (setq arg 1))
5922 (if (called-interactively-p 'interactive)
5923 (condition-case err
5924 (line-move (- arg) nil nil try-vscroll)
5925 ((beginning-of-buffer end-of-buffer)
5926 (signal (car err) (cdr err))))
5927 (line-move (- arg) nil nil try-vscroll))
5928 nil)
5930 (defcustom track-eol nil
5931 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5932 This means moving to the end of each line moved onto.
5933 The beginning of a blank line does not count as the end of a line.
5934 This has no effect when the variable `line-move-visual' is non-nil."
5935 :type 'boolean
5936 :group 'editing-basics)
5938 (defcustom goal-column nil
5939 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5940 A non-nil setting overrides the variable `line-move-visual', which see."
5941 :type '(choice integer
5942 (const :tag "None" nil))
5943 :group 'editing-basics)
5944 (make-variable-buffer-local 'goal-column)
5946 (defvar temporary-goal-column 0
5947 "Current goal column for vertical motion.
5948 It is the column where point was at the start of the current run
5949 of vertical motion commands.
5951 When moving by visual lines via the function `line-move-visual', it is a cons
5952 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5953 divided by the default column width, and HSCROLL is the number of
5954 columns by which window is scrolled from left margin.
5956 When the `track-eol' feature is doing its job, the value is
5957 `most-positive-fixnum'.")
5959 (defvar last--line-number-width 0
5960 "Last value of width used for displaying line numbers.
5961 Used internally by `line-move-visual'.")
5963 (defcustom line-move-ignore-invisible t
5964 "Non-nil means commands that move by lines ignore invisible newlines.
5965 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5966 as if newlines that are invisible didn't exist, and count
5967 only visible newlines. Thus, moving across across 2 newlines
5968 one of which is invisible will be counted as a one-line move.
5969 Also, a non-nil value causes invisible text to be ignored when
5970 counting columns for the purposes of keeping point in the same
5971 column by \\[next-line] and \\[previous-line].
5973 Outline mode sets this."
5974 :type 'boolean
5975 :group 'editing-basics)
5977 (defcustom line-move-visual t
5978 "When non-nil, `line-move' moves point by visual lines.
5979 This movement is based on where the cursor is displayed on the
5980 screen, instead of relying on buffer contents alone. It takes
5981 into account variable-width characters and line continuation.
5982 If nil, `line-move' moves point by logical lines.
5983 A non-nil setting of `goal-column' overrides the value of this variable
5984 and forces movement by logical lines.
5985 A window that is horizontally scrolled also forces movement by logical
5986 lines."
5987 :type 'boolean
5988 :group 'editing-basics
5989 :version "23.1")
5991 ;; Only used if display-graphic-p.
5992 (declare-function font-info "font.c" (name &optional frame))
5994 (defun default-font-height ()
5995 "Return the height in pixels of the current buffer's default face font.
5997 If the default font is remapped (see `face-remapping-alist'), the
5998 function returns the height of the remapped face."
5999 (let ((default-font (face-font 'default)))
6000 (cond
6001 ((and (display-multi-font-p)
6002 ;; Avoid calling font-info if the frame's default font was
6003 ;; not changed since the frame was created. That's because
6004 ;; font-info is expensive for some fonts, see bug #14838.
6005 (not (string= (frame-parameter nil 'font) default-font)))
6006 (aref (font-info default-font) 3))
6007 (t (frame-char-height)))))
6009 (defun default-font-width ()
6010 "Return the width in pixels of the current buffer's default face font.
6012 If the default font is remapped (see `face-remapping-alist'), the
6013 function returns the width of the remapped face."
6014 (let ((default-font (face-font 'default)))
6015 (cond
6016 ((and (display-multi-font-p)
6017 ;; Avoid calling font-info if the frame's default font was
6018 ;; not changed since the frame was created. That's because
6019 ;; font-info is expensive for some fonts, see bug #14838.
6020 (not (string= (frame-parameter nil 'font) default-font)))
6021 (let* ((info (font-info (face-font 'default)))
6022 (width (aref info 11)))
6023 (if (> width 0)
6024 width
6025 (aref info 10))))
6026 (t (frame-char-width)))))
6028 (defun default-line-height ()
6029 "Return the pixel height of current buffer's default-face text line.
6031 The value includes `line-spacing', if any, defined for the buffer
6032 or the frame."
6033 (let ((dfh (default-font-height))
6034 (lsp (if (display-graphic-p)
6035 (or line-spacing
6036 (default-value 'line-spacing)
6037 (frame-parameter nil 'line-spacing)
6039 0)))
6040 (if (floatp lsp)
6041 (setq lsp (truncate (* (frame-char-height) lsp))))
6042 (+ dfh lsp)))
6044 (defun window-screen-lines ()
6045 "Return the number of screen lines in the text area of the selected window.
6047 This is different from `window-text-height' in that this function counts
6048 lines in units of the height of the font used by the default face displayed
6049 in the window, not in units of the frame's default font, and also accounts
6050 for `line-spacing', if any, defined for the window's buffer or frame.
6052 The value is a floating-point number."
6053 (let ((edges (window-inside-pixel-edges))
6054 (dlh (default-line-height)))
6055 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
6057 ;; Returns non-nil if partial move was done.
6058 (defun line-move-partial (arg noerror &optional _to-end)
6059 (if (< arg 0)
6060 ;; Move backward (up).
6061 ;; If already vscrolled, reduce vscroll
6062 (let ((vs (window-vscroll nil t))
6063 (dlh (default-line-height)))
6064 (when (> vs dlh)
6065 (set-window-vscroll nil (- vs dlh) t)))
6067 ;; Move forward (down).
6068 (let* ((lh (window-line-height -1))
6069 (rowh (car lh))
6070 (vpos (nth 1 lh))
6071 (ypos (nth 2 lh))
6072 (rbot (nth 3 lh))
6073 (this-lh (window-line-height))
6074 (this-height (car this-lh))
6075 (this-ypos (nth 2 this-lh))
6076 (dlh (default-line-height))
6077 (wslines (window-screen-lines))
6078 (edges (window-inside-pixel-edges))
6079 (winh (- (nth 3 edges) (nth 1 edges) 1))
6080 py vs last-line)
6081 (if (> (mod wslines 1.0) 0.0)
6082 (setq wslines (round (+ wslines 0.5))))
6083 (when (or (null lh)
6084 (>= rbot dlh)
6085 (<= ypos (- dlh))
6086 (null this-lh)
6087 (<= this-ypos (- dlh)))
6088 (unless lh
6089 (let ((wend (pos-visible-in-window-p t nil t)))
6090 (setq rbot (nth 3 wend)
6091 rowh (nth 4 wend)
6092 vpos (nth 5 wend))))
6093 (unless this-lh
6094 (let ((wstart (pos-visible-in-window-p nil nil t)))
6095 (setq this-ypos (nth 2 wstart)
6096 this-height (nth 4 wstart))))
6097 (setq py
6098 (or (nth 1 this-lh)
6099 (let ((ppos (posn-at-point))
6100 col-row)
6101 (setq col-row (posn-actual-col-row ppos))
6102 (if col-row
6103 (- (cdr col-row) (window-vscroll))
6104 (cdr (posn-col-row ppos))))))
6105 ;; VPOS > 0 means the last line is only partially visible.
6106 ;; But if the part that is visible is at least as tall as the
6107 ;; default font, that means the line is actually fully
6108 ;; readable, and something like line-spacing is hidden. So in
6109 ;; that case we accept the last line in the window as still
6110 ;; visible, and consider the margin as starting one line
6111 ;; later.
6112 (if (and vpos (> vpos 0))
6113 (if (and rowh
6114 (>= rowh (default-font-height))
6115 (< rowh dlh))
6116 (setq last-line (min (- wslines scroll-margin) vpos))
6117 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6118 (cond
6119 ;; If last line of window is fully visible, and vscrolling
6120 ;; more would make this line invisible, move forward.
6121 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6122 (null this-height)
6123 (<= this-height dlh))
6124 (or (null rbot) (= rbot 0)))
6125 nil)
6126 ;; If cursor is not in the bottom scroll margin, and the
6127 ;; current line is is not too tall, move forward.
6128 ((and (or (null this-height) (<= this-height winh))
6129 vpos
6130 (> vpos 0)
6131 (< py last-line))
6132 nil)
6133 ;; When already vscrolled, we vscroll some more if we can,
6134 ;; or clear vscroll and move forward at end of tall image.
6135 ((> vs 0)
6136 (when (or (and rbot (> rbot 0))
6137 (and this-height (> this-height dlh)))
6138 (set-window-vscroll nil (+ vs dlh) t)))
6139 ;; If cursor just entered the bottom scroll margin, move forward,
6140 ;; but also optionally vscroll one line so redisplay won't recenter.
6141 ((and vpos
6142 (> vpos 0)
6143 (= py last-line))
6144 ;; Don't vscroll if the partially-visible line at window
6145 ;; bottom is not too tall (a.k.a. "just one more text
6146 ;; line"): in that case, we do want redisplay to behave
6147 ;; normally, i.e. recenter or whatever.
6149 ;; Note: ROWH + RBOT from the value returned by
6150 ;; pos-visible-in-window-p give the total height of the
6151 ;; partially-visible glyph row at the end of the window. As
6152 ;; we are dealing with floats, we disregard sub-pixel
6153 ;; discrepancies between that and DLH.
6154 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6155 (set-window-vscroll nil dlh t))
6156 (line-move-1 arg noerror)
6158 ;; If there are lines above the last line, scroll-up one line.
6159 ((and vpos (> vpos 0))
6160 (scroll-up 1)
6162 ;; Finally, start vscroll.
6164 (set-window-vscroll nil dlh t)))))))
6167 ;; This is like line-move-1 except that it also performs
6168 ;; vertical scrolling of tall images if appropriate.
6169 ;; That is not really a clean thing to do, since it mixes
6170 ;; scrolling with cursor motion. But so far we don't have
6171 ;; a cleaner solution to the problem of making C-n do something
6172 ;; useful given a tall image.
6173 (defun line-move (arg &optional noerror _to-end try-vscroll)
6174 "Move forward ARG lines.
6175 If NOERROR, don't signal an error if we can't move ARG lines.
6176 TO-END is unused.
6177 TRY-VSCROLL controls whether to vscroll tall lines: if either
6178 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6179 not vscroll."
6180 (if noninteractive
6181 (line-move-1 arg noerror)
6182 (unless (and auto-window-vscroll try-vscroll
6183 ;; Only vscroll for single line moves
6184 (= (abs arg) 1)
6185 ;; Under scroll-conservatively, the display engine
6186 ;; does this better.
6187 (zerop scroll-conservatively)
6188 ;; But don't vscroll in a keyboard macro.
6189 (not defining-kbd-macro)
6190 (not executing-kbd-macro)
6191 (line-move-partial arg noerror))
6192 (set-window-vscroll nil 0 t)
6193 (if (and line-move-visual
6194 ;; Display-based column are incompatible with goal-column.
6195 (not goal-column)
6196 ;; When the text in the window is scrolled to the left,
6197 ;; display-based motion doesn't make sense (because each
6198 ;; logical line occupies exactly one screen line).
6199 (not (> (window-hscroll) 0))
6200 ;; Likewise when the text _was_ scrolled to the left
6201 ;; when the current run of vertical motion commands
6202 ;; started.
6203 (not (and (memq last-command
6204 `(next-line previous-line ,this-command))
6205 auto-hscroll-mode
6206 (numberp temporary-goal-column)
6207 (>= temporary-goal-column
6208 (- (window-width) hscroll-margin)))))
6209 (prog1 (line-move-visual arg noerror)
6210 ;; If we moved into a tall line, set vscroll to make
6211 ;; scrolling through tall images more smooth.
6212 (let ((lh (line-pixel-height))
6213 (edges (window-inside-pixel-edges))
6214 (dlh (default-line-height))
6215 winh)
6216 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6217 (if (and (< arg 0)
6218 (< (point) (window-start))
6219 (> lh winh))
6220 (set-window-vscroll
6222 (- lh dlh) t))))
6223 (line-move-1 arg noerror)))))
6225 ;; Display-based alternative to line-move-1.
6226 ;; Arg says how many lines to move. The value is t if we can move the
6227 ;; specified number of lines.
6228 (defun line-move-visual (arg &optional noerror)
6229 "Move ARG lines forward.
6230 If NOERROR, don't signal an error if we can't move that many lines."
6231 (let ((opoint (point))
6232 (hscroll (window-hscroll))
6233 (lnum-width (line-number-display-width t))
6234 target-hscroll)
6235 ;; Check if the previous command was a line-motion command, or if
6236 ;; we were called from some other command.
6237 (if (and (consp temporary-goal-column)
6238 (memq last-command `(next-line previous-line ,this-command)))
6239 ;; If so, there's no need to reset `temporary-goal-column',
6240 ;; but we may need to hscroll.
6241 (progn
6242 (if (or (/= (cdr temporary-goal-column) hscroll)
6243 (> (cdr temporary-goal-column) 0))
6244 (setq target-hscroll (cdr temporary-goal-column)))
6245 ;; Update the COLUMN part of temporary-goal-column if the
6246 ;; line-number display changed its width since the last
6247 ;; time.
6248 (setq temporary-goal-column
6249 (cons (+ (car temporary-goal-column)
6250 (/ (float (- lnum-width last--line-number-width))
6251 (frame-char-width)))
6252 (cdr temporary-goal-column)))
6253 (setq last--line-number-width lnum-width))
6254 ;; Otherwise, we should reset `temporary-goal-column'.
6255 (let ((posn (posn-at-point))
6256 x-pos)
6257 (cond
6258 ;; Handle the `overflow-newline-into-fringe' case
6259 ;; (left-fringe is for the R2L case):
6260 ((memq (nth 1 posn) '(right-fringe left-fringe))
6261 (setq temporary-goal-column (cons (window-width) hscroll)))
6262 ((car (posn-x-y posn))
6263 (setq x-pos (car (posn-x-y posn)))
6264 ;; In R2L lines, the X pixel coordinate is measured from the
6265 ;; left edge of the window, but columns are still counted
6266 ;; from the logical-order beginning of the line, i.e. from
6267 ;; the right edge in this case. We need to adjust for that.
6268 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6269 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6270 (setq temporary-goal-column
6271 (cons (/ (float x-pos)
6272 (frame-char-width))
6273 hscroll)))
6274 (executing-kbd-macro
6275 ;; When we move beyond the first/last character visible in
6276 ;; the window, posn-at-point will return nil, so we need to
6277 ;; approximate the goal column as below.
6278 (setq temporary-goal-column
6279 (mod (current-column) (window-text-width)))))))
6280 (if target-hscroll
6281 (set-window-hscroll (selected-window) target-hscroll))
6282 ;; vertical-motion can move more than it was asked to if it moves
6283 ;; across display strings with newlines. We don't want to ring
6284 ;; the bell and announce beginning/end of buffer in that case.
6285 (or (and (or (and (>= arg 0)
6286 (>= (vertical-motion
6287 (cons (or goal-column
6288 (if (consp temporary-goal-column)
6289 (car temporary-goal-column)
6290 temporary-goal-column))
6291 arg))
6292 arg))
6293 (and (< arg 0)
6294 (<= (vertical-motion
6295 (cons (or goal-column
6296 (if (consp temporary-goal-column)
6297 (car temporary-goal-column)
6298 temporary-goal-column))
6299 arg))
6300 arg)))
6301 (or (>= arg 0)
6302 (/= (point) opoint)
6303 ;; If the goal column lies on a display string,
6304 ;; `vertical-motion' advances the cursor to the end
6305 ;; of the string. For arg < 0, this can cause the
6306 ;; cursor to get stuck. (Bug#3020).
6307 (= (vertical-motion arg) arg)))
6308 (unless noerror
6309 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6310 nil)))))
6312 ;; This is the guts of next-line and previous-line.
6313 ;; Arg says how many lines to move.
6314 ;; The value is t if we can move the specified number of lines.
6315 (defun line-move-1 (arg &optional noerror _to-end)
6316 ;; Don't run any point-motion hooks, and disregard intangibility,
6317 ;; for intermediate positions.
6318 (let ((inhibit-point-motion-hooks t)
6319 (opoint (point))
6320 (orig-arg arg))
6321 (if (consp temporary-goal-column)
6322 (setq temporary-goal-column (+ (car temporary-goal-column)
6323 (cdr temporary-goal-column))))
6324 (unwind-protect
6325 (progn
6326 (if (not (memq last-command '(next-line previous-line)))
6327 (setq temporary-goal-column
6328 (if (and track-eol (eolp)
6329 ;; Don't count beg of empty line as end of line
6330 ;; unless we just did explicit end-of-line.
6331 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6332 most-positive-fixnum
6333 (current-column))))
6335 (if (not (or (integerp selective-display)
6336 line-move-ignore-invisible))
6337 ;; Use just newline characters.
6338 ;; Set ARG to 0 if we move as many lines as requested.
6339 (or (if (> arg 0)
6340 (progn (if (> arg 1) (forward-line (1- arg)))
6341 ;; This way of moving forward ARG lines
6342 ;; verifies that we have a newline after the last one.
6343 ;; It doesn't get confused by intangible text.
6344 (end-of-line)
6345 (if (zerop (forward-line 1))
6346 (setq arg 0)))
6347 (and (zerop (forward-line arg))
6348 (bolp)
6349 (setq arg 0)))
6350 (unless noerror
6351 (signal (if (< arg 0)
6352 'beginning-of-buffer
6353 'end-of-buffer)
6354 nil)))
6355 ;; Move by arg lines, but ignore invisible ones.
6356 (let (done)
6357 (while (and (> arg 0) (not done))
6358 ;; If the following character is currently invisible,
6359 ;; skip all characters with that same `invisible' property value.
6360 (while (and (not (eobp)) (invisible-p (point)))
6361 (goto-char (next-char-property-change (point))))
6362 ;; Move a line.
6363 ;; We don't use `end-of-line', since we want to escape
6364 ;; from field boundaries occurring exactly at point.
6365 (goto-char (constrain-to-field
6366 (let ((inhibit-field-text-motion t))
6367 (line-end-position))
6368 (point) t t
6369 'inhibit-line-move-field-capture))
6370 ;; If there's no invisibility here, move over the newline.
6371 (cond
6372 ((eobp)
6373 (if (not noerror)
6374 (signal 'end-of-buffer nil)
6375 (setq done t)))
6376 ((and (> arg 1) ;; Use vertical-motion for last move
6377 (not (integerp selective-display))
6378 (not (invisible-p (point))))
6379 ;; We avoid vertical-motion when possible
6380 ;; because that has to fontify.
6381 (forward-line 1))
6382 ;; Otherwise move a more sophisticated way.
6383 ((zerop (vertical-motion 1))
6384 (if (not noerror)
6385 (signal 'end-of-buffer nil)
6386 (setq done t))))
6387 (unless done
6388 (setq arg (1- arg))))
6389 ;; The logic of this is the same as the loop above,
6390 ;; it just goes in the other direction.
6391 (while (and (< arg 0) (not done))
6392 ;; For completely consistency with the forward-motion
6393 ;; case, we should call beginning-of-line here.
6394 ;; However, if point is inside a field and on a
6395 ;; continued line, the call to (vertical-motion -1)
6396 ;; below won't move us back far enough; then we return
6397 ;; to the same column in line-move-finish, and point
6398 ;; gets stuck -- cyd
6399 (forward-line 0)
6400 (cond
6401 ((bobp)
6402 (if (not noerror)
6403 (signal 'beginning-of-buffer nil)
6404 (setq done t)))
6405 ((and (< arg -1) ;; Use vertical-motion for last move
6406 (not (integerp selective-display))
6407 (not (invisible-p (1- (point)))))
6408 (forward-line -1))
6409 ((zerop (vertical-motion -1))
6410 (if (not noerror)
6411 (signal 'beginning-of-buffer nil)
6412 (setq done t))))
6413 (unless done
6414 (setq arg (1+ arg))
6415 (while (and ;; Don't move over previous invis lines
6416 ;; if our target is the middle of this line.
6417 (or (zerop (or goal-column temporary-goal-column))
6418 (< arg 0))
6419 (not (bobp)) (invisible-p (1- (point))))
6420 (goto-char (previous-char-property-change (point))))))))
6421 ;; This is the value the function returns.
6422 (= arg 0))
6424 (cond ((> arg 0)
6425 ;; If we did not move down as far as desired, at least go
6426 ;; to end of line. Be sure to call point-entered and
6427 ;; point-left-hooks.
6428 (let* ((npoint (prog1 (line-end-position)
6429 (goto-char opoint)))
6430 (inhibit-point-motion-hooks nil))
6431 (goto-char npoint)))
6432 ((< arg 0)
6433 ;; If we did not move up as far as desired,
6434 ;; at least go to beginning of line.
6435 (let* ((npoint (prog1 (line-beginning-position)
6436 (goto-char opoint)))
6437 (inhibit-point-motion-hooks nil))
6438 (goto-char npoint)))
6440 (line-move-finish (or goal-column temporary-goal-column)
6441 opoint (> orig-arg 0)))))))
6443 (defun line-move-finish (column opoint forward)
6444 (let ((repeat t))
6445 (while repeat
6446 ;; Set REPEAT to t to repeat the whole thing.
6447 (setq repeat nil)
6449 (let (new
6450 (old (point))
6451 (line-beg (line-beginning-position))
6452 (line-end
6453 ;; Compute the end of the line
6454 ;; ignoring effectively invisible newlines.
6455 (save-excursion
6456 ;; Like end-of-line but ignores fields.
6457 (skip-chars-forward "^\n")
6458 (while (and (not (eobp)) (invisible-p (point)))
6459 (goto-char (next-char-property-change (point)))
6460 (skip-chars-forward "^\n"))
6461 (point))))
6463 ;; Move to the desired column.
6464 (if (and line-move-visual
6465 (not (or truncate-lines truncate-partial-width-windows)))
6466 ;; Under line-move-visual, goal-column should be
6467 ;; interpreted in units of the frame's canonical character
6468 ;; width, which is exactly what vertical-motion does.
6469 (vertical-motion (cons column 0))
6470 (line-move-to-column (truncate column)))
6472 ;; Corner case: suppose we start out in a field boundary in
6473 ;; the middle of a continued line. When we get to
6474 ;; line-move-finish, point is at the start of a new *screen*
6475 ;; line but the same text line; then line-move-to-column would
6476 ;; move us backwards. Test using C-n with point on the "x" in
6477 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6478 (and forward
6479 (< (point) old)
6480 (goto-char old))
6482 (setq new (point))
6484 ;; Process intangibility within a line.
6485 ;; With inhibit-point-motion-hooks bound to nil, a call to
6486 ;; goto-char moves point past intangible text.
6488 ;; However, inhibit-point-motion-hooks controls both the
6489 ;; intangibility and the point-entered/point-left hooks. The
6490 ;; following hack avoids calling the point-* hooks
6491 ;; unnecessarily. Note that we move *forward* past intangible
6492 ;; text when the initial and final points are the same.
6493 (goto-char new)
6494 (let ((inhibit-point-motion-hooks nil))
6495 (goto-char new)
6497 ;; If intangibility moves us to a different (later) place
6498 ;; in the same line, use that as the destination.
6499 (if (<= (point) line-end)
6500 (setq new (point))
6501 ;; If that position is "too late",
6502 ;; try the previous allowable position.
6503 ;; See if it is ok.
6504 (backward-char)
6505 (if (if forward
6506 ;; If going forward, don't accept the previous
6507 ;; allowable position if it is before the target line.
6508 (< line-beg (point))
6509 ;; If going backward, don't accept the previous
6510 ;; allowable position if it is still after the target line.
6511 (<= (point) line-end))
6512 (setq new (point))
6513 ;; As a last resort, use the end of the line.
6514 (setq new line-end))))
6516 ;; Now move to the updated destination, processing fields
6517 ;; as well as intangibility.
6518 (goto-char opoint)
6519 (let ((inhibit-point-motion-hooks nil))
6520 (goto-char
6521 ;; Ignore field boundaries if the initial and final
6522 ;; positions have the same `field' property, even if the
6523 ;; fields are non-contiguous. This seems to be "nicer"
6524 ;; behavior in many situations.
6525 (if (eq (get-char-property new 'field)
6526 (get-char-property opoint 'field))
6528 (constrain-to-field new opoint t t
6529 'inhibit-line-move-field-capture))))
6531 ;; If all this moved us to a different line,
6532 ;; retry everything within that new line.
6533 (when (or (< (point) line-beg) (> (point) line-end))
6534 ;; Repeat the intangibility and field processing.
6535 (setq repeat t))))))
6537 (defun line-move-to-column (col)
6538 "Try to find column COL, considering invisibility.
6539 This function works only in certain cases,
6540 because what we really need is for `move-to-column'
6541 and `current-column' to be able to ignore invisible text."
6542 (if (zerop col)
6543 (beginning-of-line)
6544 (move-to-column col))
6546 (when (and line-move-ignore-invisible
6547 (not (bolp)) (invisible-p (1- (point))))
6548 (let ((normal-location (point))
6549 (normal-column (current-column)))
6550 ;; If the following character is currently invisible,
6551 ;; skip all characters with that same `invisible' property value.
6552 (while (and (not (eobp))
6553 (invisible-p (point)))
6554 (goto-char (next-char-property-change (point))))
6555 ;; Have we advanced to a larger column position?
6556 (if (> (current-column) normal-column)
6557 ;; We have made some progress towards the desired column.
6558 ;; See if we can make any further progress.
6559 (line-move-to-column (+ (current-column) (- col normal-column)))
6560 ;; Otherwise, go to the place we originally found
6561 ;; and move back over invisible text.
6562 ;; that will get us to the same place on the screen
6563 ;; but with a more reasonable buffer position.
6564 (goto-char normal-location)
6565 (let ((line-beg
6566 ;; We want the real line beginning, so it's consistent
6567 ;; with bolp below, otherwise we might infloop.
6568 (let ((inhibit-field-text-motion t))
6569 (line-beginning-position))))
6570 (while (and (not (bolp)) (invisible-p (1- (point))))
6571 (goto-char (previous-char-property-change (point) line-beg))))))))
6573 (defun move-end-of-line (arg)
6574 "Move point to end of current line as displayed.
6575 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6576 If point reaches the beginning or end of buffer, it stops there.
6578 To ignore the effects of the `intangible' text or overlay
6579 property, bind `inhibit-point-motion-hooks' to t.
6580 If there is an image in the current line, this function
6581 disregards newlines that are part of the text on which the image
6582 rests."
6583 (interactive "^p")
6584 (or arg (setq arg 1))
6585 (let (done)
6586 (while (not done)
6587 (let ((newpos
6588 (save-excursion
6589 (let ((goal-column 0)
6590 (line-move-visual nil))
6591 (and (line-move arg t)
6592 ;; With bidi reordering, we may not be at bol,
6593 ;; so make sure we are.
6594 (skip-chars-backward "^\n")
6595 (not (bobp))
6596 (progn
6597 (while (and (not (bobp)) (invisible-p (1- (point))))
6598 (goto-char (previous-single-char-property-change
6599 (point) 'invisible)))
6600 (backward-char 1)))
6601 (point)))))
6602 (goto-char newpos)
6603 (if (and (> (point) newpos)
6604 (eq (preceding-char) ?\n))
6605 (backward-char 1)
6606 (if (and (> (point) newpos) (not (eobp))
6607 (not (eq (following-char) ?\n)))
6608 ;; If we skipped something intangible and now we're not
6609 ;; really at eol, keep going.
6610 (setq arg 1)
6611 (setq done t)))))))
6613 (defun move-beginning-of-line (arg)
6614 "Move point to beginning of current line as displayed.
6615 \(If there's an image in the line, this disregards newlines
6616 which are part of the text that the image rests on.)
6618 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6619 If point reaches the beginning or end of buffer, it stops there.
6620 \(But if the buffer doesn't end in a newline, it stops at the
6621 beginning of the last line.)
6622 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6623 (interactive "^p")
6624 (or arg (setq arg 1))
6626 (let ((orig (point))
6627 first-vis first-vis-field-value)
6629 ;; Move by lines, if ARG is not 1 (the default).
6630 (if (/= arg 1)
6631 (let ((line-move-visual nil))
6632 (line-move (1- arg) t)))
6634 ;; Move to beginning-of-line, ignoring fields and invisible text.
6635 (skip-chars-backward "^\n")
6636 (while (and (not (bobp)) (invisible-p (1- (point))))
6637 (goto-char (previous-char-property-change (point)))
6638 (skip-chars-backward "^\n"))
6640 ;; Now find first visible char in the line.
6641 (while (and (< (point) orig) (invisible-p (point)))
6642 (goto-char (next-char-property-change (point) orig)))
6643 (setq first-vis (point))
6645 ;; See if fields would stop us from reaching FIRST-VIS.
6646 (setq first-vis-field-value
6647 (constrain-to-field first-vis orig (/= arg 1) t nil))
6649 (goto-char (if (/= first-vis-field-value first-vis)
6650 ;; If yes, obey them.
6651 first-vis-field-value
6652 ;; Otherwise, move to START with attention to fields.
6653 ;; (It is possible that fields never matter in this case.)
6654 (constrain-to-field (point) orig
6655 (/= arg 1) t nil)))))
6658 ;; Many people have said they rarely use this feature, and often type
6659 ;; it by accident. Maybe it shouldn't even be on a key.
6660 (put 'set-goal-column 'disabled t)
6662 (defun set-goal-column (arg)
6663 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6664 Those commands will move to this position in the line moved to
6665 rather than trying to keep the same horizontal position.
6666 With a non-nil argument ARG, clears out the goal column
6667 so that \\[next-line] and \\[previous-line] resume vertical motion.
6668 The goal column is stored in the variable `goal-column'.
6669 This is a buffer-local setting."
6670 (interactive "P")
6671 (if arg
6672 (progn
6673 (setq goal-column nil)
6674 (message "No goal column"))
6675 (setq goal-column (current-column))
6676 ;; The older method below can be erroneous if `set-goal-column' is bound
6677 ;; to a sequence containing %
6678 ;;(message (substitute-command-keys
6679 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6680 ;;goal-column)
6681 (message "%s"
6682 (concat
6683 (format "Goal column %d " goal-column)
6684 (substitute-command-keys
6685 "(use \\[set-goal-column] with an arg to unset it)")))
6688 nil)
6690 ;;; Editing based on visual lines, as opposed to logical lines.
6692 (defun end-of-visual-line (&optional n)
6693 "Move point to end of current visual line.
6694 With argument N not nil or 1, move forward N - 1 visual lines first.
6695 If point reaches the beginning or end of buffer, it stops there.
6696 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6697 (interactive "^p")
6698 (or n (setq n 1))
6699 (if (/= n 1)
6700 (let ((line-move-visual t))
6701 (line-move (1- n) t)))
6702 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6703 ;; constrain to field boundaries, so we don't either.
6704 (vertical-motion (cons (window-width) 0)))
6706 (defun beginning-of-visual-line (&optional n)
6707 "Move point to beginning of current visual line.
6708 With argument N not nil or 1, move forward N - 1 visual lines first.
6709 If point reaches the beginning or end of buffer, it stops there.
6710 \(But if the buffer doesn't end in a newline, it stops at the
6711 beginning of the last visual line.)
6712 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6713 (interactive "^p")
6714 (or n (setq n 1))
6715 (let ((opoint (point)))
6716 (if (/= n 1)
6717 (let ((line-move-visual t))
6718 (line-move (1- n) t)))
6719 (vertical-motion 0)
6720 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6721 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6723 (defun kill-visual-line (&optional arg)
6724 "Kill the rest of the visual line.
6725 With prefix argument ARG, kill that many visual lines from point.
6726 If ARG is negative, kill visual lines backward.
6727 If ARG is zero, kill the text before point on the current visual
6728 line.
6730 If you want to append the killed line to the last killed text,
6731 use \\[append-next-kill] before \\[kill-line].
6733 If the buffer is read-only, Emacs will beep and refrain from deleting
6734 the line, but put the line in the kill ring anyway. This means that
6735 you can use this command to copy text from a read-only buffer.
6736 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6737 even beep.)"
6738 (interactive "P")
6739 ;; Like in `kill-line', it's better to move point to the other end
6740 ;; of the kill before killing.
6741 (let ((opoint (point))
6742 (kill-whole-line (and kill-whole-line (bolp))))
6743 (if arg
6744 (vertical-motion (prefix-numeric-value arg))
6745 (end-of-visual-line 1)
6746 (if (= (point) opoint)
6747 (vertical-motion 1)
6748 ;; Skip any trailing whitespace at the end of the visual line.
6749 ;; We used to do this only if `show-trailing-whitespace' is
6750 ;; nil, but that's wrong; the correct thing would be to check
6751 ;; whether the trailing whitespace is highlighted. But, it's
6752 ;; OK to just do this unconditionally.
6753 (skip-chars-forward " \t")))
6754 (kill-region opoint (if (and kill-whole-line (= (following-char) ?\n))
6755 (1+ (point))
6756 (point)))))
6758 (defun next-logical-line (&optional arg try-vscroll)
6759 "Move cursor vertically down ARG lines.
6760 This is identical to `next-line', except that it always moves
6761 by logical lines instead of visual lines, ignoring the value of
6762 the variable `line-move-visual'."
6763 (interactive "^p\np")
6764 (let ((line-move-visual nil))
6765 (with-no-warnings
6766 (next-line arg try-vscroll))))
6768 (defun previous-logical-line (&optional arg try-vscroll)
6769 "Move cursor vertically up ARG lines.
6770 This is identical to `previous-line', except that it always moves
6771 by logical lines instead of visual lines, ignoring the value of
6772 the variable `line-move-visual'."
6773 (interactive "^p\np")
6774 (let ((line-move-visual nil))
6775 (with-no-warnings
6776 (previous-line arg try-vscroll))))
6778 (defgroup visual-line nil
6779 "Editing based on visual lines."
6780 :group 'convenience
6781 :version "23.1")
6783 (defvar visual-line-mode-map
6784 (let ((map (make-sparse-keymap)))
6785 (define-key map [remap kill-line] 'kill-visual-line)
6786 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6787 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6788 ;; These keybindings interfere with xterm function keys. Are
6789 ;; there any other suitable bindings?
6790 ;; (define-key map "\M-[" 'previous-logical-line)
6791 ;; (define-key map "\M-]" 'next-logical-line)
6792 map))
6794 (defcustom visual-line-fringe-indicators '(nil nil)
6795 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6796 The value should be a list of the form (LEFT RIGHT), where LEFT
6797 and RIGHT are symbols representing the bitmaps to display, to
6798 indicate wrapped lines, in the left and right fringes respectively.
6799 See also `fringe-indicator-alist'.
6800 The default is not to display fringe indicators for wrapped lines.
6801 This variable does not affect fringe indicators displayed for
6802 other purposes."
6803 :type '(list (choice (const :tag "Hide left indicator" nil)
6804 (const :tag "Left curly arrow" left-curly-arrow)
6805 (symbol :tag "Other bitmap"))
6806 (choice (const :tag "Hide right indicator" nil)
6807 (const :tag "Right curly arrow" right-curly-arrow)
6808 (symbol :tag "Other bitmap")))
6809 :set (lambda (symbol value)
6810 (dolist (buf (buffer-list))
6811 (with-current-buffer buf
6812 (when (and (boundp 'visual-line-mode)
6813 (symbol-value 'visual-line-mode))
6814 (setq fringe-indicator-alist
6815 (cons (cons 'continuation value)
6816 (assq-delete-all
6817 'continuation
6818 (copy-tree fringe-indicator-alist)))))))
6819 (set-default symbol value)))
6821 (defvar visual-line--saved-state nil)
6823 (define-minor-mode visual-line-mode
6824 "Toggle visual line based editing (Visual Line mode) in the current buffer.
6825 Interactively, with a prefix argument, enable
6826 Visual Line mode if the prefix argument is positive,
6827 and disable it otherwise. If called from Lisp, toggle
6828 the mode if ARG is `toggle', disable the mode if ARG is
6829 a non-positive integer, and enable the mode otherwise
6830 \(including if ARG is omitted or nil or a positive integer).
6832 When Visual Line mode is enabled, `word-wrap' is turned on in
6833 this buffer, and simple editing commands are redefined to act on
6834 visual lines, not logical lines. See Info node `Visual Line
6835 Mode' for details."
6836 :keymap visual-line-mode-map
6837 :group 'visual-line
6838 :lighter " Wrap"
6839 (if visual-line-mode
6840 (progn
6841 (set (make-local-variable 'visual-line--saved-state) nil)
6842 ;; Save the local values of some variables, to be restored if
6843 ;; visual-line-mode is turned off.
6844 (dolist (var '(line-move-visual truncate-lines
6845 truncate-partial-width-windows
6846 word-wrap fringe-indicator-alist))
6847 (if (local-variable-p var)
6848 (push (cons var (symbol-value var))
6849 visual-line--saved-state)))
6850 (set (make-local-variable 'line-move-visual) t)
6851 (set (make-local-variable 'truncate-partial-width-windows) nil)
6852 (setq truncate-lines nil
6853 word-wrap t
6854 fringe-indicator-alist
6855 (cons (cons 'continuation visual-line-fringe-indicators)
6856 fringe-indicator-alist)))
6857 (kill-local-variable 'line-move-visual)
6858 (kill-local-variable 'word-wrap)
6859 (kill-local-variable 'truncate-lines)
6860 (kill-local-variable 'truncate-partial-width-windows)
6861 (kill-local-variable 'fringe-indicator-alist)
6862 (dolist (saved visual-line--saved-state)
6863 (set (make-local-variable (car saved)) (cdr saved)))
6864 (kill-local-variable 'visual-line--saved-state)))
6866 (defun turn-on-visual-line-mode ()
6867 (visual-line-mode 1))
6869 (define-globalized-minor-mode global-visual-line-mode
6870 visual-line-mode turn-on-visual-line-mode)
6873 (defun transpose-chars (arg)
6874 "Interchange characters around point, moving forward one character.
6875 With prefix arg ARG, effect is to take character before point
6876 and drag it forward past ARG other characters (backward if ARG negative).
6877 If no argument and at end of line, the previous two chars are exchanged."
6878 (interactive "*P")
6879 (when (and (null arg) (eolp) (not (bobp))
6880 (not (get-text-property (1- (point)) 'read-only)))
6881 (forward-char -1))
6882 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6884 (defun transpose-words (arg)
6885 "Interchange words around point, leaving point at end of them.
6886 With prefix arg ARG, effect is to take word before or around point
6887 and drag it forward past ARG other words (backward if ARG negative).
6888 If ARG is zero, the words around or after point and around or after mark
6889 are interchanged."
6890 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6891 (interactive "*p")
6892 (transpose-subr 'forward-word arg))
6894 (defun transpose-sexps (arg)
6895 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6896 Unlike `transpose-words', point must be between the two sexps and not
6897 in the middle of a sexp to be transposed.
6898 With non-zero prefix arg ARG, effect is to take the sexp before point
6899 and drag it forward past ARG other sexps (backward if ARG is negative).
6900 If ARG is zero, the sexps ending at or after point and at or after mark
6901 are interchanged."
6902 (interactive "*p")
6903 (transpose-subr
6904 (lambda (arg)
6905 ;; Here we should try to simulate the behavior of
6906 ;; (cons (progn (forward-sexp x) (point))
6907 ;; (progn (forward-sexp (- x)) (point)))
6908 ;; Except that we don't want to rely on the second forward-sexp
6909 ;; putting us back to where we want to be, since forward-sexp-function
6910 ;; might do funny things like infix-precedence.
6911 (if (if (> arg 0)
6912 (looking-at "\\sw\\|\\s_")
6913 (and (not (bobp))
6914 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6915 ;; Jumping over a symbol. We might be inside it, mind you.
6916 (progn (funcall (if (> arg 0)
6917 'skip-syntax-backward 'skip-syntax-forward)
6918 "w_")
6919 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6920 ;; Otherwise, we're between sexps. Take a step back before jumping
6921 ;; to make sure we'll obey the same precedence no matter which direction
6922 ;; we're going.
6923 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6924 (cons (save-excursion (forward-sexp arg) (point))
6925 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6926 (not (zerop (funcall (if (> arg 0)
6927 'skip-syntax-forward
6928 'skip-syntax-backward)
6929 ".")))))
6930 (point)))))
6931 arg 'special))
6933 (defun transpose-lines (arg)
6934 "Exchange current line and previous line, leaving point after both.
6935 With argument ARG, takes previous line and moves it past ARG lines.
6936 With argument 0, interchanges line point is in with line mark is in."
6937 (interactive "*p")
6938 (transpose-subr (function
6939 (lambda (arg)
6940 (if (> arg 0)
6941 (progn
6942 ;; Move forward over ARG lines,
6943 ;; but create newlines if necessary.
6944 (setq arg (forward-line arg))
6945 (if (/= (preceding-char) ?\n)
6946 (setq arg (1+ arg)))
6947 (if (> arg 0)
6948 (newline arg)))
6949 (forward-line arg))))
6950 arg))
6952 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6953 ;; which seems inconsistent with the ARG /= 0 case.
6954 ;; FIXME document SPECIAL.
6955 (defun transpose-subr (mover arg &optional special)
6956 "Subroutine to do the work of transposing objects.
6957 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6958 moves forward by units of the given object (e.g. forward-sentence,
6959 forward-paragraph). If ARG is zero, exchanges the current object
6960 with the one containing mark. If ARG is an integer, moves the
6961 current object past ARG following (if ARG is positive) or
6962 preceding (if ARG is negative) objects, leaving point after the
6963 current object."
6964 (let ((aux (if special mover
6965 (lambda (x)
6966 (cons (progn (funcall mover x) (point))
6967 (progn (funcall mover (- x)) (point))))))
6968 pos1 pos2)
6969 (cond
6970 ((= arg 0)
6971 (save-excursion
6972 (setq pos1 (funcall aux 1))
6973 (goto-char (or (mark) (error "No mark set in this buffer")))
6974 (setq pos2 (funcall aux 1))
6975 (transpose-subr-1 pos1 pos2))
6976 (exchange-point-and-mark))
6977 ((> arg 0)
6978 (setq pos1 (funcall aux -1))
6979 (setq pos2 (funcall aux arg))
6980 (transpose-subr-1 pos1 pos2)
6981 (goto-char (car pos2)))
6983 (setq pos1 (funcall aux -1))
6984 (goto-char (car pos1))
6985 (setq pos2 (funcall aux arg))
6986 (transpose-subr-1 pos1 pos2)
6987 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6989 (defun transpose-subr-1 (pos1 pos2)
6990 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6991 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6992 (when (> (car pos1) (car pos2))
6993 (let ((swap pos1))
6994 (setq pos1 pos2 pos2 swap)))
6995 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6996 (atomic-change-group
6997 ;; This sequence of insertions attempts to preserve marker
6998 ;; positions at the start and end of the transposed objects.
6999 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
7000 (len1 (- (cdr pos1) (car pos1)))
7001 (len2 (length word))
7002 (boundary (make-marker)))
7003 (set-marker boundary (car pos2))
7004 (goto-char (cdr pos1))
7005 (insert-before-markers word)
7006 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
7007 (goto-char boundary)
7008 (insert word)
7009 (goto-char (+ boundary len1))
7010 (delete-region (point) (+ (point) len2))
7011 (set-marker boundary nil))))
7013 (defun backward-word (&optional arg)
7014 "Move backward until encountering the beginning of a word.
7015 With argument ARG, do this that many times.
7016 If ARG is omitted or nil, move point backward one word.
7018 The word boundaries are normally determined by the buffer's syntax
7019 table, but `find-word-boundary-function-table', such as set up
7020 by `subword-mode', can change that. If a Lisp program needs to
7021 move by words determined strictly by the syntax table, it should
7022 use `backward-word-strictly' instead."
7023 (interactive "^p")
7024 (forward-word (- (or arg 1))))
7026 (defun mark-word (&optional arg allow-extend)
7027 "Set mark ARG words away from point.
7028 The place mark goes is the same place \\[forward-word] would
7029 move to with the same argument.
7030 Interactively, if this command is repeated
7031 or (in Transient Mark mode) if the mark is active,
7032 it marks the next ARG words after the ones already marked."
7033 (interactive "P\np")
7034 (cond ((and allow-extend
7035 (or (and (eq last-command this-command) (mark t))
7036 (region-active-p)))
7037 (setq arg (if arg (prefix-numeric-value arg)
7038 (if (< (mark) (point)) -1 1)))
7039 (set-mark
7040 (save-excursion
7041 (goto-char (mark))
7042 (forward-word arg)
7043 (point))))
7045 (push-mark
7046 (save-excursion
7047 (forward-word (prefix-numeric-value arg))
7048 (point))
7049 nil t))))
7051 (defun kill-word (arg)
7052 "Kill characters forward until encountering the end of a word.
7053 With argument ARG, do this that many times."
7054 (interactive "p")
7055 (kill-region (point) (progn (forward-word arg) (point))))
7057 (defun backward-kill-word (arg)
7058 "Kill characters backward until encountering the beginning of a word.
7059 With argument ARG, do this that many times."
7060 (interactive "p")
7061 (kill-word (- arg)))
7063 (defun current-word (&optional strict really-word)
7064 "Return the word at or near point, as a string.
7065 The return value includes no text properties.
7067 If optional arg STRICT is non-nil, return nil unless point is
7068 within or adjacent to a word, otherwise look for a word within
7069 point's line. If there is no word anywhere on point's line, the
7070 value is nil regardless of STRICT.
7072 By default, this function treats as a single word any sequence of
7073 characters that have either word or symbol syntax. If optional
7074 arg REALLY-WORD is non-nil, only characters of word syntax can
7075 constitute a word."
7076 (save-excursion
7077 (let* ((oldpoint (point)) (start (point)) (end (point))
7078 (syntaxes (if really-word "w" "w_"))
7079 (not-syntaxes (concat "^" syntaxes)))
7080 (skip-syntax-backward syntaxes) (setq start (point))
7081 (goto-char oldpoint)
7082 (skip-syntax-forward syntaxes) (setq end (point))
7083 (when (and (eq start oldpoint) (eq end oldpoint)
7084 ;; Point is neither within nor adjacent to a word.
7085 (not strict))
7086 ;; Look for preceding word in same line.
7087 (skip-syntax-backward not-syntaxes (line-beginning-position))
7088 (if (bolp)
7089 ;; No preceding word in same line.
7090 ;; Look for following word in same line.
7091 (progn
7092 (skip-syntax-forward not-syntaxes (line-end-position))
7093 (setq start (point))
7094 (skip-syntax-forward syntaxes)
7095 (setq end (point)))
7096 (setq end (point))
7097 (skip-syntax-backward syntaxes)
7098 (setq start (point))))
7099 ;; If we found something nonempty, return it as a string.
7100 (unless (= start end)
7101 (buffer-substring-no-properties start end)))))
7103 (defcustom fill-prefix nil
7104 "String for filling to insert at front of new line, or nil for none."
7105 :type '(choice (const :tag "None" nil)
7106 string)
7107 :group 'fill)
7108 (make-variable-buffer-local 'fill-prefix)
7109 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
7111 (defcustom auto-fill-inhibit-regexp nil
7112 "Regexp to match lines which should not be auto-filled."
7113 :type '(choice (const :tag "None" nil)
7114 regexp)
7115 :group 'fill)
7117 (defun do-auto-fill ()
7118 "The default value for `normal-auto-fill-function'.
7119 This is the default auto-fill function, some major modes use a different one.
7120 Returns t if it really did any work."
7121 (let (fc justify give-up
7122 (fill-prefix fill-prefix))
7123 (if (or (not (setq justify (current-justification)))
7124 (null (setq fc (current-fill-column)))
7125 (and (eq justify 'left)
7126 (<= (current-column) fc))
7127 (and auto-fill-inhibit-regexp
7128 (save-excursion (beginning-of-line)
7129 (looking-at auto-fill-inhibit-regexp))))
7130 nil ;; Auto-filling not required
7131 (if (memq justify '(full center right))
7132 (save-excursion (unjustify-current-line)))
7134 ;; Choose a fill-prefix automatically.
7135 (when (and adaptive-fill-mode
7136 (or (null fill-prefix) (string= fill-prefix "")))
7137 (let ((prefix
7138 (fill-context-prefix
7139 (save-excursion (fill-forward-paragraph -1) (point))
7140 (save-excursion (fill-forward-paragraph 1) (point)))))
7141 (and prefix (not (equal prefix ""))
7142 ;; Use auto-indentation rather than a guessed empty prefix.
7143 (not (and fill-indent-according-to-mode
7144 (string-match "\\`[ \t]*\\'" prefix)))
7145 (setq fill-prefix prefix))))
7147 (while (and (not give-up) (> (current-column) fc))
7148 ;; Determine where to split the line.
7149 (let ((fill-point
7150 (save-excursion
7151 (beginning-of-line)
7152 ;; Don't split earlier in the line than the length of the
7153 ;; fill prefix, since the resulting line would be longer.
7154 (when fill-prefix
7155 (move-to-column (string-width fill-prefix)))
7156 (let ((after-prefix (point)))
7157 (move-to-column (1+ fc))
7158 (fill-move-to-break-point after-prefix)
7159 (point)))))
7161 ;; See whether the place we found is any good.
7162 (if (save-excursion
7163 (goto-char fill-point)
7164 (or (bolp)
7165 ;; There is no use breaking at end of line.
7166 (save-excursion (skip-chars-forward " ") (eolp))
7167 ;; Don't split right after a comment starter
7168 ;; since we would just make another comment starter.
7169 (and comment-start-skip
7170 (let ((limit (point)))
7171 (beginning-of-line)
7172 (and (re-search-forward comment-start-skip
7173 limit t)
7174 (eq (point) limit))))))
7175 ;; No good place to break => stop trying.
7176 (setq give-up t)
7177 ;; Ok, we have a useful place to break the line. Do it.
7178 (let ((prev-column (current-column)))
7179 ;; If point is at the fill-point, do not `save-excursion'.
7180 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7181 ;; point will end up before it rather than after it.
7182 (if (save-excursion
7183 (skip-chars-backward " \t")
7184 (= (point) fill-point))
7185 (default-indent-new-line t)
7186 (save-excursion
7187 (goto-char fill-point)
7188 (default-indent-new-line t)))
7189 ;; Now do justification, if required
7190 (if (not (eq justify 'left))
7191 (save-excursion
7192 (end-of-line 0)
7193 (justify-current-line justify nil t)))
7194 ;; If making the new line didn't reduce the hpos of
7195 ;; the end of the line, then give up now;
7196 ;; trying again will not help.
7197 (if (>= (current-column) prev-column)
7198 (setq give-up t))))))
7199 ;; Justify last line.
7200 (justify-current-line justify t t)
7201 t)))
7203 (defvar comment-line-break-function 'comment-indent-new-line
7204 "Mode-specific function which line breaks and continues a comment.
7205 This function is called during auto-filling when a comment syntax
7206 is defined.
7207 The function should take a single optional argument, which is a flag
7208 indicating whether it should use soft newlines.")
7210 (defun default-indent-new-line (&optional soft)
7211 "Break line at point and indent.
7212 If a comment syntax is defined, call `comment-indent-new-line'.
7214 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7215 unless optional argument SOFT is non-nil."
7216 (interactive)
7217 (if comment-start
7218 (funcall comment-line-break-function soft)
7219 ;; Insert the newline before removing empty space so that markers
7220 ;; get preserved better.
7221 (if soft (insert-and-inherit ?\n) (newline 1))
7222 (save-excursion (forward-char -1) (delete-horizontal-space))
7223 (delete-horizontal-space)
7225 (if (and fill-prefix (not adaptive-fill-mode))
7226 ;; Blindly trust a non-adaptive fill-prefix.
7227 (progn
7228 (indent-to-left-margin)
7229 (insert-before-markers-and-inherit fill-prefix))
7231 (cond
7232 ;; If there's an adaptive prefix, use it unless we're inside
7233 ;; a comment and the prefix is not a comment starter.
7234 (fill-prefix
7235 (indent-to-left-margin)
7236 (insert-and-inherit fill-prefix))
7237 ;; If we're not inside a comment, just try to indent.
7238 (t (indent-according-to-mode))))))
7240 (defun internal-auto-fill ()
7241 "The function called by `self-insert-command' to perform auto-filling."
7242 (when (or (not comment-start)
7243 (not comment-auto-fill-only-comments)
7244 (nth 4 (syntax-ppss)))
7245 (funcall auto-fill-function)))
7247 (defvar normal-auto-fill-function 'do-auto-fill
7248 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7249 Some major modes set this.")
7251 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7252 ;; `functions' and `hooks' are usually unsafe to set, but setting
7253 ;; auto-fill-function to nil in a file-local setting is safe and
7254 ;; can be useful to prevent auto-filling.
7255 (put 'auto-fill-function 'safe-local-variable 'null)
7257 (define-minor-mode auto-fill-mode
7258 "Toggle automatic line breaking (Auto Fill mode).
7259 Interactively, with a prefix argument, enable
7260 Auto Fill mode if the prefix argument is positive,
7261 and disable it otherwise. If called from Lisp, toggle
7262 the mode if ARG is `toggle', disable the mode if ARG is
7263 a non-positive integer, and enable the mode otherwise
7264 \(including if ARG is omitted or nil or a positive integer).
7266 When Auto Fill mode is enabled, inserting a space at a column
7267 beyond `current-fill-column' automatically breaks the line at a
7268 previous space.
7270 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7271 non-nil.
7273 The value of `normal-auto-fill-function' specifies the function to use
7274 for `auto-fill-function' when turning Auto Fill mode on."
7275 :variable (auto-fill-function
7276 . (lambda (v) (setq auto-fill-function
7277 (if v normal-auto-fill-function)))))
7279 ;; This holds a document string used to document auto-fill-mode.
7280 (defun auto-fill-function ()
7281 "Automatically break line at a previous space, in insertion of text."
7282 nil)
7284 (defun turn-on-auto-fill ()
7285 "Unconditionally turn on Auto Fill mode."
7286 (auto-fill-mode 1))
7288 (defun turn-off-auto-fill ()
7289 "Unconditionally turn off Auto Fill mode."
7290 (auto-fill-mode -1))
7292 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7294 (defun set-fill-column (arg)
7295 "Set `fill-column' to specified argument.
7296 Use \\[universal-argument] followed by a number to specify a column.
7297 Just \\[universal-argument] as argument means to use the current column."
7298 (interactive
7299 (list (or current-prefix-arg
7300 ;; We used to use current-column silently, but C-x f is too easily
7301 ;; typed as a typo for C-x C-f, so we turned it into an error and
7302 ;; now an interactive prompt.
7303 (read-number "Set fill-column to: " (current-column)))))
7304 (if (consp arg)
7305 (setq arg (current-column)))
7306 (if (not (integerp arg))
7307 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7308 (error "set-fill-column requires an explicit argument")
7309 (message "Fill column set to %d (was %d)" arg fill-column)
7310 (setq fill-column arg)))
7312 (defun set-selective-display (arg)
7313 "Set `selective-display' to ARG; clear it if no arg.
7314 When the value of `selective-display' is a number > 0,
7315 lines whose indentation is >= that value are not displayed.
7316 The variable `selective-display' has a separate value for each buffer."
7317 (interactive "P")
7318 (if (eq selective-display t)
7319 (error "selective-display already in use for marked lines"))
7320 (let ((current-vpos
7321 (save-restriction
7322 (narrow-to-region (point-min) (point))
7323 (goto-char (window-start))
7324 (vertical-motion (window-height)))))
7325 (setq selective-display
7326 (and arg (prefix-numeric-value arg)))
7327 (recenter current-vpos))
7328 (set-window-start (selected-window) (window-start))
7329 (princ "selective-display set to " t)
7330 (prin1 selective-display t)
7331 (princ "." t))
7333 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7335 (defun toggle-truncate-lines (&optional arg)
7336 "Toggle truncating of long lines for the current buffer.
7337 When truncating is off, long lines are folded.
7338 With prefix argument ARG, truncate long lines if ARG is positive,
7339 otherwise fold them. Note that in side-by-side windows, this
7340 command has no effect if `truncate-partial-width-windows' is
7341 non-nil."
7342 (interactive "P")
7343 (setq truncate-lines
7344 (if (null arg)
7345 (not truncate-lines)
7346 (> (prefix-numeric-value arg) 0)))
7347 (force-mode-line-update)
7348 (unless truncate-lines
7349 (let ((buffer (current-buffer)))
7350 (walk-windows (lambda (window)
7351 (if (eq buffer (window-buffer window))
7352 (set-window-hscroll window 0)))
7353 nil t)))
7354 (message "Truncate long lines %s"
7355 (if truncate-lines "enabled" "disabled")))
7357 (defun toggle-word-wrap (&optional arg)
7358 "Toggle whether to use word-wrapping for continuation lines.
7359 With prefix argument ARG, wrap continuation lines at word boundaries
7360 if ARG is positive, otherwise wrap them at the right screen edge.
7361 This command toggles the value of `word-wrap'. It has no effect
7362 if long lines are truncated."
7363 (interactive "P")
7364 (setq word-wrap
7365 (if (null arg)
7366 (not word-wrap)
7367 (> (prefix-numeric-value arg) 0)))
7368 (force-mode-line-update)
7369 (message "Word wrapping %s"
7370 (if word-wrap "enabled" "disabled")))
7372 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7373 "The string displayed in the mode line when in overwrite mode.")
7374 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7375 "The string displayed in the mode line when in binary overwrite mode.")
7377 (define-minor-mode overwrite-mode
7378 "Toggle Overwrite mode.
7379 With a prefix argument ARG, enable Overwrite mode if ARG is
7380 positive, and disable it otherwise. If called from Lisp, enable
7381 the mode if ARG is omitted or nil.
7383 When Overwrite mode is enabled, printing characters typed in
7384 replace existing text on a one-for-one basis, rather than pushing
7385 it to the right. At the end of a line, such characters extend
7386 the line. Before a tab, such characters insert until the tab is
7387 filled in. \\[quoted-insert] still inserts characters in
7388 overwrite mode; this is supposed to make it easier to insert
7389 characters when necessary."
7390 :variable (overwrite-mode
7391 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7393 (define-minor-mode binary-overwrite-mode
7394 "Toggle Binary Overwrite mode.
7395 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7396 is positive, and disable it otherwise. If called from Lisp,
7397 enable the mode if ARG is omitted or nil.
7399 When Binary Overwrite mode is enabled, printing characters typed
7400 in replace existing text. Newlines are not treated specially, so
7401 typing at the end of a line joins the line to the next, with the
7402 typed character between them. Typing before a tab character
7403 simply replaces the tab with the character typed.
7404 \\[quoted-insert] replaces the text at the cursor, just as
7405 ordinary typing characters do.
7407 Note that Binary Overwrite mode is not its own minor mode; it is
7408 a specialization of overwrite mode, entered by setting the
7409 `overwrite-mode' variable to `overwrite-mode-binary'."
7410 :variable (overwrite-mode
7411 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7413 (define-minor-mode line-number-mode
7414 "Toggle line number display in the mode line (Line Number mode).
7415 With a prefix argument ARG, enable Line Number mode if ARG is
7416 positive, and disable it otherwise. If called from Lisp, enable
7417 the mode if ARG is omitted or nil.
7419 Line numbers do not appear for very large buffers and buffers
7420 with very long lines; see variables `line-number-display-limit'
7421 and `line-number-display-limit-width'."
7422 :init-value t :global t :group 'mode-line)
7424 (define-minor-mode column-number-mode
7425 "Toggle column number display in the mode line (Column Number mode).
7426 With a prefix argument ARG, enable Column Number mode if ARG is
7427 positive, and disable it otherwise.
7429 If called from Lisp, enable the mode if ARG is omitted or nil."
7430 :global t :group 'mode-line)
7432 (define-minor-mode size-indication-mode
7433 "Toggle buffer size display in the mode line (Size Indication mode).
7434 With a prefix argument ARG, enable Size Indication mode if ARG is
7435 positive, and disable it otherwise.
7437 If called from Lisp, enable the mode if ARG is omitted or nil."
7438 :global t :group 'mode-line)
7440 (define-minor-mode auto-save-mode
7441 "Toggle auto-saving in the current buffer (Auto Save mode).
7442 With a prefix argument ARG, enable Auto Save mode if ARG is
7443 positive, and disable it otherwise.
7445 If called from Lisp, enable the mode if ARG is omitted or nil."
7446 :variable ((and buffer-auto-save-file-name
7447 ;; If auto-save is off because buffer has shrunk,
7448 ;; then toggling should turn it on.
7449 (>= buffer-saved-size 0))
7450 . (lambda (val)
7451 (setq buffer-auto-save-file-name
7452 (cond
7453 ((null val) nil)
7454 ((and buffer-file-name auto-save-visited-file-name
7455 (not buffer-read-only))
7456 buffer-file-name)
7457 (t (make-auto-save-file-name))))))
7458 ;; If -1 was stored here, to temporarily turn off saving,
7459 ;; turn it back on.
7460 (and (< buffer-saved-size 0)
7461 (setq buffer-saved-size 0)))
7463 (defgroup paren-blinking nil
7464 "Blinking matching of parens and expressions."
7465 :prefix "blink-matching-"
7466 :group 'paren-matching)
7468 (defcustom blink-matching-paren t
7469 "Non-nil means show matching open-paren when close-paren is inserted.
7470 If t, highlight the paren. If `jump', briefly move cursor to its
7471 position. If `jump-offscreen', move cursor there even if the
7472 position is off screen. With any other non-nil value, the
7473 off-screen position of the opening paren will be shown in the
7474 echo area."
7475 :type '(choice
7476 (const :tag "Disable" nil)
7477 (const :tag "Highlight" t)
7478 (const :tag "Move cursor" jump)
7479 (const :tag "Move cursor, even if off screen" jump-offscreen))
7480 :group 'paren-blinking)
7482 (defcustom blink-matching-paren-on-screen t
7483 "Non-nil means show matching open-paren when it is on screen.
7484 If nil, don't show it (but the open-paren can still be shown
7485 in the echo area when it is off screen).
7487 This variable has no effect if `blink-matching-paren' is nil.
7488 \(In that case, the open-paren is never shown.)
7489 It is also ignored if `show-paren-mode' is enabled."
7490 :type 'boolean
7491 :group 'paren-blinking)
7493 (defcustom blink-matching-paren-distance (* 100 1024)
7494 "If non-nil, maximum distance to search backwards for matching open-paren.
7495 If nil, search stops at the beginning of the accessible portion of the buffer."
7496 :version "23.2" ; 25->100k
7497 :type '(choice (const nil) integer)
7498 :group 'paren-blinking)
7500 (defcustom blink-matching-delay 1
7501 "Time in seconds to delay after showing a matching paren."
7502 :type 'number
7503 :group 'paren-blinking)
7505 (defcustom blink-matching-paren-dont-ignore-comments nil
7506 "If nil, `blink-matching-paren' ignores comments.
7507 More precisely, when looking for the matching parenthesis,
7508 it skips the contents of comments that end before point."
7509 :type 'boolean
7510 :group 'paren-blinking)
7512 (defun blink-matching-check-mismatch (start end)
7513 "Return whether or not START...END are matching parens.
7514 END is the current point and START is the blink position.
7515 START might be nil if no matching starter was found.
7516 Returns non-nil if we find there is a mismatch."
7517 (let* ((end-syntax (syntax-after (1- end)))
7518 (matching-paren (and (consp end-syntax)
7519 (eq (syntax-class end-syntax) 5)
7520 (cdr end-syntax))))
7521 ;; For self-matched chars like " and $, we can't know when they're
7522 ;; mismatched or unmatched, so we can only do it for parens.
7523 (when matching-paren
7524 (not (and start
7526 (eq (char-after start) matching-paren)
7527 ;; The cdr might hold a new paren-class info rather than
7528 ;; a matching-char info, in which case the two CDRs
7529 ;; should match.
7530 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7532 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7533 "Function to check parentheses mismatches.
7534 The function takes two arguments (START and END) where START is the
7535 position just before the opening token and END is the position right after.
7536 START can be nil, if it was not found.
7537 The function should return non-nil if the two tokens do not match.")
7539 (defvar blink-matching--overlay
7540 (let ((ol (make-overlay (point) (point) nil t)))
7541 (overlay-put ol 'face 'show-paren-match)
7542 (delete-overlay ol)
7544 "Overlay used to highlight the matching paren.")
7546 (defun blink-matching-open ()
7547 "Momentarily highlight the beginning of the sexp before point."
7548 (interactive)
7549 (when (and (not (bobp))
7550 blink-matching-paren)
7551 (let* ((oldpos (point))
7552 (message-log-max nil) ; Don't log messages about paren matching.
7553 (blinkpos
7554 (save-excursion
7555 (save-restriction
7556 (if blink-matching-paren-distance
7557 (narrow-to-region
7558 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7559 (- (point) blink-matching-paren-distance))
7560 oldpos))
7561 (let ((parse-sexp-ignore-comments
7562 (and parse-sexp-ignore-comments
7563 (not blink-matching-paren-dont-ignore-comments))))
7564 (condition-case ()
7565 (progn
7566 (syntax-propertize (point))
7567 (forward-sexp -1)
7568 ;; backward-sexp skips backward over prefix chars,
7569 ;; so move back to the matching paren.
7570 (while (and (< (point) (1- oldpos))
7571 (let ((code (syntax-after (point))))
7572 (or (eq (syntax-class code) 6)
7573 (eq (logand 1048576 (car code))
7574 1048576))))
7575 (forward-char 1))
7576 (point))
7577 (error nil))))))
7578 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7579 (cond
7580 (mismatch
7581 (if blinkpos
7582 (if (minibufferp)
7583 (minibuffer-message "Mismatched parentheses")
7584 (message "Mismatched parentheses"))
7585 (if (minibufferp)
7586 (minibuffer-message "No matching parenthesis found")
7587 (message "No matching parenthesis found"))))
7588 ((not blinkpos) nil)
7589 ((or
7590 (eq blink-matching-paren 'jump-offscreen)
7591 (pos-visible-in-window-p blinkpos))
7592 ;; Matching open within window, temporarily move to or highlight
7593 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7594 ;; is non-nil.
7595 (and blink-matching-paren-on-screen
7596 (not show-paren-mode)
7597 (if (memq blink-matching-paren '(jump jump-offscreen))
7598 (save-excursion
7599 (goto-char blinkpos)
7600 (sit-for blink-matching-delay))
7601 (unwind-protect
7602 (progn
7603 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7604 (current-buffer))
7605 (sit-for blink-matching-delay))
7606 (delete-overlay blink-matching--overlay)))))
7608 (let ((open-paren-line-string
7609 (save-excursion
7610 (goto-char blinkpos)
7611 ;; Show what precedes the open in its line, if anything.
7612 (cond
7613 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7614 (buffer-substring (line-beginning-position)
7615 (1+ blinkpos)))
7616 ;; Show what follows the open in its line, if anything.
7617 ((save-excursion
7618 (forward-char 1)
7619 (skip-chars-forward " \t")
7620 (not (eolp)))
7621 (buffer-substring blinkpos
7622 (line-end-position)))
7623 ;; Otherwise show the previous nonblank line,
7624 ;; if there is one.
7625 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7626 (concat
7627 (buffer-substring (progn
7628 (skip-chars-backward "\n \t")
7629 (line-beginning-position))
7630 (progn (end-of-line)
7631 (skip-chars-backward " \t")
7632 (point)))
7633 ;; Replace the newline and other whitespace with `...'.
7634 "..."
7635 (buffer-substring blinkpos (1+ blinkpos))))
7636 ;; There is nothing to show except the char itself.
7637 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7638 (minibuffer-message
7639 "Matches %s"
7640 (substring-no-properties open-paren-line-string))))))))
7642 (defvar blink-paren-function 'blink-matching-open
7643 "Function called, if non-nil, whenever a close parenthesis is inserted.
7644 More precisely, a char with closeparen syntax is self-inserted.")
7646 (defun blink-paren-post-self-insert-function ()
7647 (when (and (eq (char-before) last-command-event) ; Sanity check.
7648 (memq (char-syntax last-command-event) '(?\) ?\$))
7649 blink-paren-function
7650 (not executing-kbd-macro)
7651 (not noninteractive)
7652 ;; Verify an even number of quoting characters precede the close.
7653 ;; FIXME: Also check if this parenthesis closes a comment as
7654 ;; can happen in Pascal and SML.
7655 (= 1 (logand 1 (- (point)
7656 (save-excursion
7657 (forward-char -1)
7658 (skip-syntax-backward "/\\")
7659 (point))))))
7660 (funcall blink-paren-function)))
7662 (put 'blink-paren-post-self-insert-function 'priority 100)
7664 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7665 ;; Most likely, this hook is nil, so this arg doesn't matter,
7666 ;; but I use it as a reminder that this function usually
7667 ;; likes to be run after others since it does
7668 ;; `sit-for'. That's also the reason it get a `priority' prop
7669 ;; of 100.
7670 'append)
7672 ;; This executes C-g typed while Emacs is waiting for a command.
7673 ;; Quitting out of a program does not go through here;
7674 ;; that happens in the maybe_quit function at the C code level.
7675 (defun keyboard-quit ()
7676 "Signal a `quit' condition.
7677 During execution of Lisp code, this character causes a quit directly.
7678 At top-level, as an editor command, this simply beeps."
7679 (interactive)
7680 ;; Avoid adding the region to the window selection.
7681 (setq saved-region-selection nil)
7682 (let (select-active-regions)
7683 (deactivate-mark))
7684 (if (fboundp 'kmacro-keyboard-quit)
7685 (kmacro-keyboard-quit))
7686 (when completion-in-region-mode
7687 (completion-in-region-mode -1))
7688 ;; Force the next redisplay cycle to remove the "Def" indicator from
7689 ;; all the mode lines.
7690 (if defining-kbd-macro
7691 (force-mode-line-update t))
7692 (setq defining-kbd-macro nil)
7693 (let ((debug-on-quit nil))
7694 (signal 'quit nil)))
7696 (defvar buffer-quit-function nil
7697 "Function to call to \"quit\" the current buffer, or nil if none.
7698 \\[keyboard-escape-quit] calls this function when its more local actions
7699 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7701 (defun keyboard-escape-quit ()
7702 "Exit the current \"mode\" (in a generalized sense of the word).
7703 This command can exit an interactive command such as `query-replace',
7704 can clear out a prefix argument or a region,
7705 can get out of the minibuffer or other recursive edit,
7706 cancel the use of the current buffer (for special-purpose buffers),
7707 or go back to just one window (by deleting all but the selected window)."
7708 (interactive)
7709 (cond ((eq last-command 'mode-exited) nil)
7710 ((region-active-p)
7711 (deactivate-mark))
7712 ((> (minibuffer-depth) 0)
7713 (abort-recursive-edit))
7714 (current-prefix-arg
7715 nil)
7716 ((> (recursion-depth) 0)
7717 (exit-recursive-edit))
7718 (buffer-quit-function
7719 (funcall buffer-quit-function))
7720 ((not (one-window-p t))
7721 (delete-other-windows))
7722 ((string-match "^ \\*" (buffer-name (current-buffer)))
7723 (bury-buffer))))
7725 (defun play-sound-file (file &optional volume device)
7726 "Play sound stored in FILE.
7727 VOLUME and DEVICE correspond to the keywords of the sound
7728 specification for `play-sound'."
7729 (interactive "fPlay sound file: ")
7730 (let ((sound (list :file file)))
7731 (if volume
7732 (plist-put sound :volume volume))
7733 (if device
7734 (plist-put sound :device device))
7735 (push 'sound sound)
7736 (play-sound sound)))
7739 (defcustom read-mail-command 'rmail
7740 "Your preference for a mail reading package.
7741 This is used by some keybindings which support reading mail.
7742 See also `mail-user-agent' concerning sending mail."
7743 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7744 (function-item :tag "Gnus" :format "%t\n" gnus)
7745 (function-item :tag "Emacs interface to MH"
7746 :format "%t\n" mh-rmail)
7747 (function :tag "Other"))
7748 :version "21.1"
7749 :group 'mail)
7751 (defcustom mail-user-agent 'message-user-agent
7752 "Your preference for a mail composition package.
7753 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7754 outgoing email message. This variable lets you specify which
7755 mail-sending package you prefer.
7757 Valid values include:
7759 `message-user-agent' -- use the Message package.
7760 See Info node `(message)'.
7761 `sendmail-user-agent' -- use the Mail package.
7762 See Info node `(emacs)Sending Mail'.
7763 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7764 See Info node `(mh-e)'.
7765 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7766 paraphernalia if Gnus is running, particularly
7767 the Gcc: header for archiving.
7769 Additional valid symbols may be available; check with the author of
7770 your package for details. The function should return non-nil if it
7771 succeeds.
7773 See also `read-mail-command' concerning reading mail."
7774 :type '(radio (function-item :tag "Message package"
7775 :format "%t\n"
7776 message-user-agent)
7777 (function-item :tag "Mail package"
7778 :format "%t\n"
7779 sendmail-user-agent)
7780 (function-item :tag "Emacs interface to MH"
7781 :format "%t\n"
7782 mh-e-user-agent)
7783 (function-item :tag "Message with full Gnus features"
7784 :format "%t\n"
7785 gnus-user-agent)
7786 (function :tag "Other"))
7787 :version "23.2" ; sendmail->message
7788 :group 'mail)
7790 (defcustom compose-mail-user-agent-warnings t
7791 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7792 If the value of `mail-user-agent' is the default, and the user
7793 appears to have customizations applying to the old default,
7794 `compose-mail' issues a warning."
7795 :type 'boolean
7796 :version "23.2"
7797 :group 'mail)
7799 (defun rfc822-goto-eoh ()
7800 "If the buffer starts with a mail header, move point to the header's end.
7801 Otherwise, moves to `point-min'.
7802 The end of the header is the start of the next line, if there is one,
7803 else the end of the last line. This function obeys RFC822."
7804 (goto-char (point-min))
7805 (when (re-search-forward
7806 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7807 (goto-char (match-beginning 0))))
7809 ;; Used by Rmail (e.g., rmail-forward).
7810 (defvar mail-encode-mml nil
7811 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7812 the outgoing message before sending it.")
7814 (defun compose-mail (&optional to subject other-headers continue
7815 switch-function yank-action send-actions
7816 return-action)
7817 "Start composing a mail message to send.
7818 This uses the user's chosen mail composition package
7819 as selected with the variable `mail-user-agent'.
7820 The optional arguments TO and SUBJECT specify recipients
7821 and the initial Subject field, respectively.
7823 OTHER-HEADERS is an alist specifying additional
7824 header fields. Elements look like (HEADER . VALUE) where both
7825 HEADER and VALUE are strings.
7827 CONTINUE, if non-nil, says to continue editing a message already
7828 being composed. Interactively, CONTINUE is the prefix argument.
7830 SWITCH-FUNCTION, if non-nil, is a function to use to
7831 switch to and display the buffer used for mail composition.
7833 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7834 to insert the raw text of the message being replied to.
7835 It has the form (FUNCTION . ARGS). The user agent will apply
7836 FUNCTION to ARGS, to insert the raw text of the original message.
7837 \(The user agent will also run `mail-citation-hook', *after* the
7838 original text has been inserted in this way.)
7840 SEND-ACTIONS is a list of actions to call when the message is sent.
7841 Each action has the form (FUNCTION . ARGS).
7843 RETURN-ACTION, if non-nil, is an action for returning to the
7844 caller. It has the form (FUNCTION . ARGS). The function is
7845 called after the mail has been sent or put aside, and the mail
7846 buffer buried."
7847 (interactive
7848 (list nil nil nil current-prefix-arg))
7850 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7851 ;; from sendmail-user-agent to message-user-agent. Some users may
7852 ;; encounter incompatibilities. This hack tries to detect problems
7853 ;; and warn about them.
7854 (and compose-mail-user-agent-warnings
7855 (eq mail-user-agent 'message-user-agent)
7856 (let (warn-vars)
7857 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7858 mail-yank-hooks mail-archive-file-name
7859 mail-default-reply-to mail-mailing-lists
7860 mail-self-blind))
7861 (and (boundp var)
7862 (symbol-value var)
7863 (push var warn-vars)))
7864 (when warn-vars
7865 (display-warning 'mail
7866 (format-message "\
7867 The default mail mode is now Message mode.
7868 You have the following Mail mode variable%s customized:
7869 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7870 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7871 (if (> (length warn-vars) 1) "s" "")
7872 (mapconcat 'symbol-name
7873 warn-vars " "))))))
7875 (let ((function (get mail-user-agent 'composefunc)))
7876 (funcall function to subject other-headers continue switch-function
7877 yank-action send-actions return-action)))
7879 (defun compose-mail-other-window (&optional to subject other-headers continue
7880 yank-action send-actions
7881 return-action)
7882 "Like \\[compose-mail], but edit the outgoing message in another window."
7883 (interactive (list nil nil nil current-prefix-arg))
7884 (compose-mail to subject other-headers continue
7885 'switch-to-buffer-other-window yank-action send-actions
7886 return-action))
7888 (defun compose-mail-other-frame (&optional to subject other-headers continue
7889 yank-action send-actions
7890 return-action)
7891 "Like \\[compose-mail], but edit the outgoing message in another frame."
7892 (interactive (list nil nil nil current-prefix-arg))
7893 (compose-mail to subject other-headers continue
7894 'switch-to-buffer-other-frame yank-action send-actions
7895 return-action))
7898 (defvar set-variable-value-history nil
7899 "History of values entered with `set-variable'.
7901 Maximum length of the history list is determined by the value
7902 of `history-length', which see.")
7904 (defun set-variable (variable value &optional make-local)
7905 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7906 VARIABLE should be a user option variable name, a Lisp variable
7907 meant to be customized by users. You should enter VALUE in Lisp syntax,
7908 so if you want VALUE to be a string, you must surround it with doublequotes.
7909 VALUE is used literally, not evaluated.
7911 If VARIABLE has a `variable-interactive' property, that is used as if
7912 it were the arg to `interactive' (which see) to interactively read VALUE.
7914 If VARIABLE has been defined with `defcustom', then the type information
7915 in the definition is used to check that VALUE is valid.
7917 Note that this function is at heart equivalent to the basic `set' function.
7918 For a variable defined with `defcustom', it does not pay attention to
7919 any :set property that the variable might have (if you want that, use
7920 \\[customize-set-variable] instead).
7922 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7923 (interactive
7924 (let* ((default-var (variable-at-point))
7925 (var (if (custom-variable-p default-var)
7926 (read-variable (format "Set variable (default %s): " default-var)
7927 default-var)
7928 (read-variable "Set variable: ")))
7929 (minibuffer-help-form '(describe-variable var))
7930 (prop (get var 'variable-interactive))
7931 (obsolete (car (get var 'byte-obsolete-variable)))
7932 (prompt (format "Set %s %s to value: " var
7933 (cond ((local-variable-p var)
7934 "(buffer-local)")
7935 ((or current-prefix-arg
7936 (local-variable-if-set-p var))
7937 "buffer-locally")
7938 (t "globally"))))
7939 (val (progn
7940 (when obsolete
7941 (message (concat "`%S' is obsolete; "
7942 (if (symbolp obsolete) "use `%S' instead" "%s"))
7943 var obsolete)
7944 (sit-for 3))
7945 (if prop
7946 ;; Use VAR's `variable-interactive' property
7947 ;; as an interactive spec for prompting.
7948 (call-interactively `(lambda (arg)
7949 (interactive ,prop)
7950 arg))
7951 (read-from-minibuffer prompt nil
7952 read-expression-map t
7953 'set-variable-value-history
7954 (format "%S" (symbol-value var)))))))
7955 (list var val current-prefix-arg)))
7957 (and (custom-variable-p variable)
7958 (not (get variable 'custom-type))
7959 (custom-load-symbol variable))
7960 (let ((type (get variable 'custom-type)))
7961 (when type
7962 ;; Match with custom type.
7963 (require 'cus-edit)
7964 (setq type (widget-convert type))
7965 (unless (widget-apply type :match value)
7966 (user-error "Value `%S' does not match type %S of %S"
7967 value (car type) variable))))
7969 (if make-local
7970 (make-local-variable variable))
7972 (set variable value)
7974 ;; Force a thorough redisplay for the case that the variable
7975 ;; has an effect on the display, like `tab-width' has.
7976 (force-mode-line-update))
7978 ;; Define the major mode for lists of completions.
7980 (defvar completion-list-mode-map
7981 (let ((map (make-sparse-keymap)))
7982 (define-key map [mouse-2] 'choose-completion)
7983 (define-key map [follow-link] 'mouse-face)
7984 (define-key map [down-mouse-2] nil)
7985 (define-key map "\C-m" 'choose-completion)
7986 (define-key map "\e\e\e" 'delete-completion-window)
7987 (define-key map [left] 'previous-completion)
7988 (define-key map [right] 'next-completion)
7989 (define-key map [?\t] 'next-completion)
7990 (define-key map [backtab] 'previous-completion)
7991 (define-key map "q" 'quit-window)
7992 (define-key map "z" 'kill-current-buffer)
7993 map)
7994 "Local map for completion list buffers.")
7996 ;; Completion mode is suitable only for specially formatted data.
7997 (put 'completion-list-mode 'mode-class 'special)
7999 (defvar completion-reference-buffer nil
8000 "Record the buffer that was current when the completion list was requested.
8001 This is a local variable in the completion list buffer.
8002 Initial value is nil to avoid some compiler warnings.")
8004 (defvar completion-no-auto-exit nil
8005 "Non-nil means `choose-completion-string' should never exit the minibuffer.
8006 This also applies to other functions such as `choose-completion'.")
8008 (defvar completion-base-position nil
8009 "Position of the base of the text corresponding to the shown completions.
8010 This variable is used in the *Completions* buffers.
8011 Its value is a list of the form (START END) where START is the place
8012 where the completion should be inserted and END (if non-nil) is the end
8013 of the text to replace. If END is nil, point is used instead.")
8015 (defvar completion-list-insert-choice-function #'completion--replace
8016 "Function to use to insert the text chosen in *Completions*.
8017 Called with three arguments (BEG END TEXT), it should replace the text
8018 between BEG and END with TEXT. Expected to be set buffer-locally
8019 in the *Completions* buffer.")
8021 (defvar completion-base-size nil
8022 "Number of chars before point not involved in completion.
8023 This is a local variable in the completion list buffer.
8024 It refers to the chars in the minibuffer if completing in the
8025 minibuffer, or in `completion-reference-buffer' otherwise.
8026 Only characters in the field at point are included.
8028 If nil, Emacs determines which part of the tail end of the
8029 buffer's text is involved in completion by comparing the text
8030 directly.")
8031 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
8033 (defun delete-completion-window ()
8034 "Delete the completion list window.
8035 Go to the window from which completion was requested."
8036 (interactive)
8037 (let ((buf completion-reference-buffer))
8038 (if (one-window-p t)
8039 (if (window-dedicated-p) (delete-frame))
8040 (delete-window (selected-window))
8041 (if (get-buffer-window buf)
8042 (select-window (get-buffer-window buf))))))
8044 (defun previous-completion (n)
8045 "Move to the previous item in the completion list."
8046 (interactive "p")
8047 (next-completion (- n)))
8049 (defun next-completion (n)
8050 "Move to the next item in the completion list.
8051 With prefix argument N, move N items (negative N means move backward)."
8052 (interactive "p")
8053 (let ((beg (point-min)) (end (point-max)))
8054 (while (and (> n 0) (not (eobp)))
8055 ;; If in a completion, move to the end of it.
8056 (when (get-text-property (point) 'mouse-face)
8057 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8058 ;; Move to start of next one.
8059 (unless (get-text-property (point) 'mouse-face)
8060 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8061 (setq n (1- n)))
8062 (while (and (< n 0) (not (bobp)))
8063 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
8064 ;; If in a completion, move to the start of it.
8065 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
8066 (goto-char (previous-single-property-change
8067 (point) 'mouse-face nil beg)))
8068 ;; Move to end of the previous completion.
8069 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
8070 (goto-char (previous-single-property-change
8071 (point) 'mouse-face nil beg)))
8072 ;; Move to the start of that one.
8073 (goto-char (previous-single-property-change
8074 (point) 'mouse-face nil beg))
8075 (setq n (1+ n))))))
8077 (defun choose-completion (&optional event)
8078 "Choose the completion at point.
8079 If EVENT, use EVENT's position to determine the starting position."
8080 (interactive (list last-nonmenu-event))
8081 ;; In case this is run via the mouse, give temporary modes such as
8082 ;; isearch a chance to turn off.
8083 (run-hooks 'mouse-leave-buffer-hook)
8084 (with-current-buffer (window-buffer (posn-window (event-start event)))
8085 (let ((buffer completion-reference-buffer)
8086 (base-size completion-base-size)
8087 (base-position completion-base-position)
8088 (insert-function completion-list-insert-choice-function)
8089 (choice
8090 (save-excursion
8091 (goto-char (posn-point (event-start event)))
8092 (let (beg end)
8093 (cond
8094 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
8095 (setq end (point) beg (1+ (point))))
8096 ((and (not (bobp))
8097 (get-text-property (1- (point)) 'mouse-face))
8098 (setq end (1- (point)) beg (point)))
8099 (t (error "No completion here")))
8100 (setq beg (previous-single-property-change beg 'mouse-face))
8101 (setq end (or (next-single-property-change end 'mouse-face)
8102 (point-max)))
8103 (buffer-substring-no-properties beg end)))))
8105 (unless (buffer-live-p buffer)
8106 (error "Destination buffer is dead"))
8107 (quit-window nil (posn-window (event-start event)))
8109 (with-current-buffer buffer
8110 (choose-completion-string
8111 choice buffer
8112 (or base-position
8113 (when base-size
8114 ;; Someone's using old completion code that doesn't know
8115 ;; about base-position yet.
8116 (list (+ base-size (field-beginning))))
8117 ;; If all else fails, just guess.
8118 (list (choose-completion-guess-base-position choice)))
8119 insert-function)))))
8121 ;; Delete the longest partial match for STRING
8122 ;; that can be found before POINT.
8123 (defun choose-completion-guess-base-position (string)
8124 (save-excursion
8125 (let ((opoint (point))
8126 len)
8127 ;; Try moving back by the length of the string.
8128 (goto-char (max (- (point) (length string))
8129 (minibuffer-prompt-end)))
8130 ;; See how far back we were actually able to move. That is the
8131 ;; upper bound on how much we can match and delete.
8132 (setq len (- opoint (point)))
8133 (if completion-ignore-case
8134 (setq string (downcase string)))
8135 (while (and (> len 0)
8136 (let ((tail (buffer-substring (point) opoint)))
8137 (if completion-ignore-case
8138 (setq tail (downcase tail)))
8139 (not (string= tail (substring string 0 len)))))
8140 (setq len (1- len))
8141 (forward-char 1))
8142 (point))))
8144 (defun choose-completion-delete-max-match (string)
8145 (declare (obsolete choose-completion-guess-base-position "23.2"))
8146 (delete-region (choose-completion-guess-base-position string) (point)))
8148 (defvar choose-completion-string-functions nil
8149 "Functions that may override the normal insertion of a completion choice.
8150 These functions are called in order with three arguments:
8151 CHOICE - the string to insert in the buffer,
8152 BUFFER - the buffer in which the choice should be inserted,
8153 BASE-POSITION - where to insert the completion.
8155 If a function in the list returns non-nil, that function is supposed
8156 to have inserted the CHOICE in the BUFFER, and possibly exited
8157 the minibuffer; no further functions will be called.
8159 If all functions in the list return nil, that means to use
8160 the default method of inserting the completion in BUFFER.")
8162 (defun choose-completion-string (choice &optional
8163 buffer base-position insert-function)
8164 "Switch to BUFFER and insert the completion choice CHOICE.
8165 BASE-POSITION says where to insert the completion.
8166 INSERT-FUNCTION says how to insert the completion and falls
8167 back on `completion-list-insert-choice-function' when nil."
8169 ;; If BUFFER is the minibuffer, exit the minibuffer
8170 ;; unless it is reading a file name and CHOICE is a directory,
8171 ;; or completion-no-auto-exit is non-nil.
8173 ;; Some older code may call us passing `base-size' instead of
8174 ;; `base-position'. It's difficult to make any use of `base-size',
8175 ;; so we just ignore it.
8176 (unless (consp base-position)
8177 (message "Obsolete `base-size' passed to choose-completion-string")
8178 (setq base-position nil))
8180 (let* ((buffer (or buffer completion-reference-buffer))
8181 (mini-p (minibufferp buffer)))
8182 ;; If BUFFER is a minibuffer, barf unless it's the currently
8183 ;; active minibuffer.
8184 (if (and mini-p
8185 (not (and (active-minibuffer-window)
8186 (equal buffer
8187 (window-buffer (active-minibuffer-window))))))
8188 (error "Minibuffer is not active for completion")
8189 ;; Set buffer so buffer-local choose-completion-string-functions works.
8190 (set-buffer buffer)
8191 (unless (run-hook-with-args-until-success
8192 'choose-completion-string-functions
8193 ;; The fourth arg used to be `mini-p' but was useless
8194 ;; (since minibufferp can be used on the `buffer' arg)
8195 ;; and indeed unused. The last used to be `base-size', so we
8196 ;; keep it to try and avoid breaking old code.
8197 choice buffer base-position nil)
8198 ;; This remove-text-properties should be unnecessary since `choice'
8199 ;; comes from buffer-substring-no-properties.
8200 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8201 ;; Insert the completion into the buffer where it was requested.
8202 (funcall (or insert-function completion-list-insert-choice-function)
8203 (or (car base-position) (point))
8204 (or (cadr base-position) (point))
8205 choice)
8206 ;; Update point in the window that BUFFER is showing in.
8207 (let ((window (get-buffer-window buffer t)))
8208 (set-window-point window (point)))
8209 ;; If completing for the minibuffer, exit it with this choice.
8210 (and (not completion-no-auto-exit)
8211 (minibufferp buffer)
8212 minibuffer-completion-table
8213 ;; If this is reading a file name, and the file name chosen
8214 ;; is a directory, don't exit the minibuffer.
8215 (let* ((result (buffer-substring (field-beginning) (point)))
8216 (bounds
8217 (completion-boundaries result minibuffer-completion-table
8218 minibuffer-completion-predicate
8219 "")))
8220 (if (eq (car bounds) (length result))
8221 ;; The completion chosen leads to a new set of completions
8222 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8223 (let ((mini (active-minibuffer-window)))
8224 (select-window mini)
8225 (when minibuffer-auto-raise
8226 (raise-frame (window-frame mini))))
8227 (exit-minibuffer))))))))
8229 (define-derived-mode completion-list-mode nil "Completion List"
8230 "Major mode for buffers showing lists of possible completions.
8231 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8232 to select the completion near point.
8233 Or click to select one with the mouse.
8235 \\{completion-list-mode-map}"
8236 (set (make-local-variable 'completion-base-size) nil))
8238 (defun completion-list-mode-finish ()
8239 "Finish setup of the completions buffer.
8240 Called from `temp-buffer-show-hook'."
8241 (when (eq major-mode 'completion-list-mode)
8242 (setq buffer-read-only t)))
8244 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8247 ;; Variables and faces used in `completion-setup-function'.
8249 (defcustom completion-show-help t
8250 "Non-nil means show help message in *Completions* buffer."
8251 :type 'boolean
8252 :version "22.1"
8253 :group 'completion)
8255 ;; This function goes in completion-setup-hook, so that it is called
8256 ;; after the text of the completion list buffer is written.
8257 (defun completion-setup-function ()
8258 (let* ((mainbuf (current-buffer))
8259 (base-dir
8260 ;; FIXME: This is a bad hack. We try to set the default-directory
8261 ;; in the *Completions* buffer so that the relative file names
8262 ;; displayed there can be treated as valid file names, independently
8263 ;; from the completion context. But this suffers from many problems:
8264 ;; - It's not clear when the completions are file names. With some
8265 ;; completion tables (e.g. bzr revision specs), the listed
8266 ;; completions can mix file names and other things.
8267 ;; - It doesn't pay attention to possible quoting.
8268 ;; - With fancy completion styles, the code below will not always
8269 ;; find the right base directory.
8270 (if minibuffer-completing-file-name
8271 (file-name-as-directory
8272 (expand-file-name
8273 (buffer-substring (minibuffer-prompt-end)
8274 (- (point) (or completion-base-size 0))))))))
8275 (with-current-buffer standard-output
8276 (let ((base-size completion-base-size) ;Read before killing localvars.
8277 (base-position completion-base-position)
8278 (insert-fun completion-list-insert-choice-function))
8279 (completion-list-mode)
8280 (set (make-local-variable 'completion-base-size) base-size)
8281 (set (make-local-variable 'completion-base-position) base-position)
8282 (set (make-local-variable 'completion-list-insert-choice-function)
8283 insert-fun))
8284 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8285 (if base-dir (setq default-directory base-dir))
8286 ;; Maybe insert help string.
8287 (when completion-show-help
8288 (goto-char (point-min))
8289 (if (display-mouse-p)
8290 (insert "Click on a completion to select it.\n"))
8291 (insert (substitute-command-keys
8292 "In this buffer, type \\[choose-completion] to \
8293 select the completion near point.\n\n"))))))
8295 (add-hook 'completion-setup-hook 'completion-setup-function)
8297 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8298 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8300 (defun switch-to-completions ()
8301 "Select the completion list window."
8302 (interactive)
8303 (let ((window (or (get-buffer-window "*Completions*" 0)
8304 ;; Make sure we have a completions window.
8305 (progn (minibuffer-completion-help)
8306 (get-buffer-window "*Completions*" 0)))))
8307 (when window
8308 (select-window window)
8309 ;; In the new buffer, go to the first completion.
8310 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8311 (when (bobp)
8312 (next-completion 1)))))
8314 ;;; Support keyboard commands to turn on various modifiers.
8316 ;; These functions -- which are not commands -- each add one modifier
8317 ;; to the following event.
8319 (defun event-apply-alt-modifier (_ignore-prompt)
8320 "\\<function-key-map>Add the Alt modifier to the following event.
8321 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8322 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8323 (defun event-apply-super-modifier (_ignore-prompt)
8324 "\\<function-key-map>Add the Super modifier to the following event.
8325 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8326 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8327 (defun event-apply-hyper-modifier (_ignore-prompt)
8328 "\\<function-key-map>Add the Hyper modifier to the following event.
8329 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8330 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8331 (defun event-apply-shift-modifier (_ignore-prompt)
8332 "\\<function-key-map>Add the Shift modifier to the following event.
8333 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8334 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8335 (defun event-apply-control-modifier (_ignore-prompt)
8336 "\\<function-key-map>Add the Ctrl modifier to the following event.
8337 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8338 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8339 (defun event-apply-meta-modifier (_ignore-prompt)
8340 "\\<function-key-map>Add the Meta modifier to the following event.
8341 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8342 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8344 (defun event-apply-modifier (event symbol lshiftby prefix)
8345 "Apply a modifier flag to event EVENT.
8346 SYMBOL is the name of this modifier, as a symbol.
8347 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8348 PREFIX is the string that represents this modifier in an event type symbol."
8349 (if (numberp event)
8350 (cond ((eq symbol 'control)
8351 (if (and (<= (downcase event) ?z)
8352 (>= (downcase event) ?a))
8353 (- (downcase event) ?a -1)
8354 (if (and (<= (downcase event) ?Z)
8355 (>= (downcase event) ?A))
8356 (- (downcase event) ?A -1)
8357 (logior (lsh 1 lshiftby) event))))
8358 ((eq symbol 'shift)
8359 (if (and (<= (downcase event) ?z)
8360 (>= (downcase event) ?a))
8361 (upcase event)
8362 (logior (lsh 1 lshiftby) event)))
8364 (logior (lsh 1 lshiftby) event)))
8365 (if (memq symbol (event-modifiers event))
8366 event
8367 (let ((event-type (if (symbolp event) event (car event))))
8368 (setq event-type (intern (concat prefix (symbol-name event-type))))
8369 (if (symbolp event)
8370 event-type
8371 (cons event-type (cdr event)))))))
8373 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8374 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8375 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8376 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8377 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8378 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8380 ;;;; Keypad support.
8382 ;; Make the keypad keys act like ordinary typing keys. If people add
8383 ;; bindings for the function key symbols, then those bindings will
8384 ;; override these, so this shouldn't interfere with any existing
8385 ;; bindings.
8387 ;; Also tell read-char how to handle these keys.
8388 (mapc
8389 (lambda (keypad-normal)
8390 (let ((keypad (nth 0 keypad-normal))
8391 (normal (nth 1 keypad-normal)))
8392 (put keypad 'ascii-character normal)
8393 (define-key function-key-map (vector keypad) (vector normal))))
8394 ;; See also kp-keys bound in bindings.el.
8395 '((kp-space ?\s)
8396 (kp-tab ?\t)
8397 (kp-enter ?\r)
8398 (kp-separator ?,)
8399 (kp-equal ?=)
8400 ;; Do the same for various keys that are represented as symbols under
8401 ;; GUIs but naturally correspond to characters.
8402 (backspace 127)
8403 (delete 127)
8404 (tab ?\t)
8405 (linefeed ?\n)
8406 (clear ?\C-l)
8407 (return ?\C-m)
8408 (escape ?\e)
8411 ;;;;
8412 ;;;; forking a twin copy of a buffer.
8413 ;;;;
8415 (defvar clone-buffer-hook nil
8416 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8418 (defvar clone-indirect-buffer-hook nil
8419 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8421 (defun clone-process (process &optional newname)
8422 "Create a twin copy of PROCESS.
8423 If NEWNAME is nil, it defaults to PROCESS' name;
8424 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8425 If PROCESS is associated with a buffer, the new process will be associated
8426 with the current buffer instead.
8427 Returns nil if PROCESS has already terminated."
8428 (setq newname (or newname (process-name process)))
8429 (if (string-match "<[0-9]+>\\'" newname)
8430 (setq newname (substring newname 0 (match-beginning 0))))
8431 (when (memq (process-status process) '(run stop open))
8432 (let* ((process-connection-type (process-tty-name process))
8433 (new-process
8434 (if (memq (process-status process) '(open))
8435 (let ((args (process-contact process t)))
8436 (setq args (plist-put args :name newname))
8437 (setq args (plist-put args :buffer
8438 (if (process-buffer process)
8439 (current-buffer))))
8440 (apply 'make-network-process args))
8441 (apply 'start-process newname
8442 (if (process-buffer process) (current-buffer))
8443 (process-command process)))))
8444 (set-process-query-on-exit-flag
8445 new-process (process-query-on-exit-flag process))
8446 (set-process-inherit-coding-system-flag
8447 new-process (process-inherit-coding-system-flag process))
8448 (set-process-filter new-process (process-filter process))
8449 (set-process-sentinel new-process (process-sentinel process))
8450 (set-process-plist new-process (copy-sequence (process-plist process)))
8451 new-process)))
8453 ;; things to maybe add (currently partly covered by `funcall mode'):
8454 ;; - syntax-table
8455 ;; - overlays
8456 (defun clone-buffer (&optional newname display-flag)
8457 "Create and return a twin copy of the current buffer.
8458 Unlike an indirect buffer, the new buffer can be edited
8459 independently of the old one (if it is not read-only).
8460 NEWNAME is the name of the new buffer. It may be modified by
8461 adding or incrementing <N> at the end as necessary to create a
8462 unique buffer name. If nil, it defaults to the name of the
8463 current buffer, with the proper suffix. If DISPLAY-FLAG is
8464 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8465 clone a file-visiting buffer, or a buffer whose major mode symbol
8466 has a non-nil `no-clone' property, results in an error.
8468 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8469 current buffer with appropriate suffix. However, if a prefix
8470 argument is given, then the command prompts for NEWNAME in the
8471 minibuffer.
8473 This runs the normal hook `clone-buffer-hook' in the new buffer
8474 after it has been set up properly in other respects."
8475 (interactive
8476 (progn
8477 (if buffer-file-name
8478 (error "Cannot clone a file-visiting buffer"))
8479 (if (get major-mode 'no-clone)
8480 (error "Cannot clone a buffer in %s mode" mode-name))
8481 (list (if current-prefix-arg
8482 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8483 t)))
8484 (if buffer-file-name
8485 (error "Cannot clone a file-visiting buffer"))
8486 (if (get major-mode 'no-clone)
8487 (error "Cannot clone a buffer in %s mode" mode-name))
8488 (setq newname (or newname (buffer-name)))
8489 (if (string-match "<[0-9]+>\\'" newname)
8490 (setq newname (substring newname 0 (match-beginning 0))))
8491 (let ((buf (current-buffer))
8492 (ptmin (point-min))
8493 (ptmax (point-max))
8494 (pt (point))
8495 (mk (if mark-active (mark t)))
8496 (modified (buffer-modified-p))
8497 (mode major-mode)
8498 (lvars (buffer-local-variables))
8499 (process (get-buffer-process (current-buffer)))
8500 (new (generate-new-buffer (or newname (buffer-name)))))
8501 (save-restriction
8502 (widen)
8503 (with-current-buffer new
8504 (insert-buffer-substring buf)))
8505 (with-current-buffer new
8506 (narrow-to-region ptmin ptmax)
8507 (goto-char pt)
8508 (if mk (set-mark mk))
8509 (set-buffer-modified-p modified)
8511 ;; Clone the old buffer's process, if any.
8512 (when process (clone-process process))
8514 ;; Now set up the major mode.
8515 (funcall mode)
8517 ;; Set up other local variables.
8518 (mapc (lambda (v)
8519 (condition-case () ;in case var is read-only
8520 (if (symbolp v)
8521 (makunbound v)
8522 (set (make-local-variable (car v)) (cdr v)))
8523 (error nil)))
8524 lvars)
8526 ;; Run any hooks (typically set up by the major mode
8527 ;; for cloning to work properly).
8528 (run-hooks 'clone-buffer-hook))
8529 (if display-flag
8530 ;; Presumably the current buffer is shown in the selected frame, so
8531 ;; we want to display the clone elsewhere.
8532 (let ((same-window-regexps nil)
8533 (same-window-buffer-names))
8534 (pop-to-buffer new)))
8535 new))
8538 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8539 "Create an indirect buffer that is a twin copy of the current buffer.
8541 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8542 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8543 or if not called with a prefix arg, NEWNAME defaults to the current
8544 buffer's name. The name is modified by adding a `<N>' suffix to it
8545 or by incrementing the N in an existing suffix. Trying to clone a
8546 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8547 property results in an error.
8549 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8550 This is always done when called interactively.
8552 Optional third arg NORECORD non-nil means do not put this buffer at the
8553 front of the list of recently selected ones.
8555 Returns the newly created indirect buffer."
8556 (interactive
8557 (progn
8558 (if (get major-mode 'no-clone-indirect)
8559 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8560 (list (if current-prefix-arg
8561 (read-buffer "Name of indirect buffer: " (current-buffer)))
8562 t)))
8563 (if (get major-mode 'no-clone-indirect)
8564 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8565 (setq newname (or newname (buffer-name)))
8566 (if (string-match "<[0-9]+>\\'" newname)
8567 (setq newname (substring newname 0 (match-beginning 0))))
8568 (let* ((name (generate-new-buffer-name newname))
8569 (buffer (make-indirect-buffer (current-buffer) name t)))
8570 (with-current-buffer buffer
8571 (run-hooks 'clone-indirect-buffer-hook))
8572 (when display-flag
8573 (pop-to-buffer buffer nil norecord))
8574 buffer))
8577 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8578 "Like `clone-indirect-buffer' but display in another window."
8579 (interactive
8580 (progn
8581 (if (get major-mode 'no-clone-indirect)
8582 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8583 (list (if current-prefix-arg
8584 (read-buffer "Name of indirect buffer: " (current-buffer)))
8585 t)))
8586 (let ((pop-up-windows t))
8587 (clone-indirect-buffer newname display-flag norecord)))
8590 ;;; Handling of Backspace and Delete keys.
8592 (defcustom normal-erase-is-backspace 'maybe
8593 "Set the default behavior of the Delete and Backspace keys.
8595 If set to t, Delete key deletes forward and Backspace key deletes
8596 backward.
8598 If set to nil, both Delete and Backspace keys delete backward.
8600 If set to `maybe' (which is the default), Emacs automatically
8601 selects a behavior. On window systems, the behavior depends on
8602 the keyboard used. If the keyboard has both a Backspace key and
8603 a Delete key, and both are mapped to their usual meanings, the
8604 option's default value is set to t, so that Backspace can be used
8605 to delete backward, and Delete can be used to delete forward.
8607 If not running under a window system, customizing this option
8608 accomplishes a similar effect by mapping C-h, which is usually
8609 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8610 via `keyboard-translate'. The former functionality of C-h is
8611 available on the F1 key. You should probably not use this
8612 setting if you don't have both Backspace, Delete and F1 keys.
8614 Setting this variable with setq doesn't take effect. Programmatically,
8615 call `normal-erase-is-backspace-mode' (which see) instead."
8616 :type '(choice (const :tag "Off" nil)
8617 (const :tag "Maybe" maybe)
8618 (other :tag "On" t))
8619 :group 'editing-basics
8620 :version "21.1"
8621 :set (lambda (symbol value)
8622 ;; The fboundp is because of a problem with :set when
8623 ;; dumping Emacs. It doesn't really matter.
8624 (if (fboundp 'normal-erase-is-backspace-mode)
8625 (normal-erase-is-backspace-mode (or value 0))
8626 (set-default symbol value))))
8628 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8629 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8630 (unless frame (setq frame (selected-frame)))
8631 (with-selected-frame frame
8632 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8633 (normal-erase-is-backspace-mode
8634 (if (if (eq normal-erase-is-backspace 'maybe)
8635 (and (not noninteractive)
8636 (or (memq system-type '(ms-dos windows-nt))
8637 (memq window-system '(w32 ns))
8638 (and (memq window-system '(x))
8639 (fboundp 'x-backspace-delete-keys-p)
8640 (x-backspace-delete-keys-p))
8641 ;; If the terminal Emacs is running on has erase char
8642 ;; set to ^H, use the Backspace key for deleting
8643 ;; backward, and the Delete key for deleting forward.
8644 (and (null window-system)
8645 (eq tty-erase-char ?\^H))))
8646 normal-erase-is-backspace)
8647 1 0)))))
8649 (define-minor-mode normal-erase-is-backspace-mode
8650 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8651 With a prefix argument ARG, enable this feature if ARG is
8652 positive, and disable it otherwise. If called from Lisp, enable
8653 the mode if ARG is omitted or nil.
8655 On window systems, when this mode is on, Delete is mapped to C-d
8656 and Backspace is mapped to DEL; when this mode is off, both
8657 Delete and Backspace are mapped to DEL. (The remapping goes via
8658 `local-function-key-map', so binding Delete or Backspace in the
8659 global or local keymap will override that.)
8661 In addition, on window systems, the bindings of C-Delete, M-Delete,
8662 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8663 the global keymap in accordance with the functionality of Delete and
8664 Backspace. For example, if Delete is remapped to C-d, which deletes
8665 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8666 to DEL, which deletes backward, C-Delete is bound to
8667 `backward-kill-word'.
8669 If not running on a window system, a similar effect is accomplished by
8670 remapping C-h (normally produced by the Backspace key) and DEL via
8671 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8672 to C-d; if it's off, the keys are not remapped.
8674 When not running on a window system, and this mode is turned on, the
8675 former functionality of C-h is available on the F1 key. You should
8676 probably not turn on this mode on a text-only terminal if you don't
8677 have both Backspace, Delete and F1 keys.
8679 See also `normal-erase-is-backspace'."
8680 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8681 . (lambda (v)
8682 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8683 (if v 1 0))))
8684 (let ((enabled (eq 1 (terminal-parameter
8685 nil 'normal-erase-is-backspace))))
8687 (cond ((or (memq window-system '(x w32 ns pc))
8688 (memq system-type '(ms-dos windows-nt)))
8689 (let ((bindings
8690 `(([M-delete] [M-backspace])
8691 ([C-M-delete] [C-M-backspace])
8692 ([?\e C-delete] [?\e C-backspace]))))
8694 (if enabled
8695 (progn
8696 (define-key local-function-key-map [delete] [deletechar])
8697 (define-key local-function-key-map [kp-delete] [deletechar])
8698 (define-key local-function-key-map [backspace] [?\C-?])
8699 (dolist (b bindings)
8700 ;; Not sure if input-decode-map is really right, but
8701 ;; keyboard-translate-table (used below) only works
8702 ;; for integer events, and key-translation-table is
8703 ;; global (like the global-map, used earlier).
8704 (define-key input-decode-map (car b) nil)
8705 (define-key input-decode-map (cadr b) nil)))
8706 (define-key local-function-key-map [delete] [?\C-?])
8707 (define-key local-function-key-map [kp-delete] [?\C-?])
8708 (define-key local-function-key-map [backspace] [?\C-?])
8709 (dolist (b bindings)
8710 (define-key input-decode-map (car b) (cadr b))
8711 (define-key input-decode-map (cadr b) (car b))))))
8713 (if enabled
8714 (progn
8715 (keyboard-translate ?\C-h ?\C-?)
8716 (keyboard-translate ?\C-? ?\C-d))
8717 (keyboard-translate ?\C-h ?\C-h)
8718 (keyboard-translate ?\C-? ?\C-?))))
8720 (if (called-interactively-p 'interactive)
8721 (message "Delete key deletes %s"
8722 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8723 "forward" "backward")))))
8725 (defvar vis-mode-saved-buffer-invisibility-spec nil
8726 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8728 (define-minor-mode read-only-mode
8729 "Change whether the current buffer is read-only.
8730 With prefix argument ARG, make the buffer read-only if ARG is
8731 positive, otherwise make it writable. If buffer is read-only
8732 and `view-read-only' is non-nil, enter view mode.
8734 Do not call this from a Lisp program unless you really intend to
8735 do the same thing as the \\[read-only-mode] command, including
8736 possibly enabling or disabling View mode. Also, note that this
8737 command works by setting the variable `buffer-read-only', which
8738 does not affect read-only regions caused by text properties. To
8739 ignore read-only status in a Lisp program (whether due to text
8740 properties or buffer state), bind `inhibit-read-only' temporarily
8741 to a non-nil value."
8742 :variable buffer-read-only
8743 (cond
8744 ((and (not buffer-read-only) view-mode)
8745 (View-exit-and-edit)
8746 (make-local-variable 'view-read-only)
8747 (setq view-read-only t)) ; Must leave view mode.
8748 ((and buffer-read-only view-read-only
8749 ;; If view-mode is already active, `view-mode-enter' is a nop.
8750 (not view-mode)
8751 (not (eq (get major-mode 'mode-class) 'special)))
8752 (view-mode-enter))))
8754 (define-minor-mode visible-mode
8755 "Toggle making all invisible text temporarily visible (Visible mode).
8756 With a prefix argument ARG, enable Visible mode if ARG is
8757 positive, and disable it otherwise. If called from Lisp, enable
8758 the mode if ARG is omitted or nil.
8760 This mode works by saving the value of `buffer-invisibility-spec'
8761 and setting it to nil."
8762 :lighter " Vis"
8763 :group 'editing-basics
8764 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8765 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8766 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8767 (when visible-mode
8768 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8769 buffer-invisibility-spec)
8770 (setq buffer-invisibility-spec nil)))
8772 (defvar messages-buffer-mode-map
8773 (let ((map (make-sparse-keymap)))
8774 (set-keymap-parent map special-mode-map)
8775 (define-key map "g" nil) ; nothing to revert
8776 map))
8778 (define-derived-mode messages-buffer-mode special-mode "Messages"
8779 "Major mode used in the \"*Messages*\" buffer.")
8781 (defun messages-buffer ()
8782 "Return the \"*Messages*\" buffer.
8783 If it does not exist, create and it switch it to `messages-buffer-mode'."
8784 (or (get-buffer "*Messages*")
8785 (with-current-buffer (get-buffer-create "*Messages*")
8786 (messages-buffer-mode)
8787 (current-buffer))))
8790 ;; Minibuffer prompt stuff.
8792 ;;(defun minibuffer-prompt-modification (start end)
8793 ;; (error "You cannot modify the prompt"))
8796 ;;(defun minibuffer-prompt-insertion (start end)
8797 ;; (let ((inhibit-modification-hooks t))
8798 ;; (delete-region start end)
8799 ;; ;; Discard undo information for the text insertion itself
8800 ;; ;; and for the text deletion.above.
8801 ;; (when (consp buffer-undo-list)
8802 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8803 ;; (message "You cannot modify the prompt")))
8806 ;;(setq minibuffer-prompt-properties
8807 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8808 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8811 ;;;; Problematic external packages.
8813 ;; rms says this should be done by specifying symbols that define
8814 ;; versions together with bad values. This is therefore not as
8815 ;; flexible as it could be. See the thread:
8816 ;; https://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8817 (defconst bad-packages-alist
8818 ;; Not sure exactly which semantic versions have problems.
8819 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8820 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8821 "The version of `semantic' loaded does not work in Emacs 22.
8822 It can cause constant high CPU load.
8823 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8824 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8825 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8826 ;; provided the `CUA-mode' feature. Since this is no longer true,
8827 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8828 (CUA-mode t nil
8829 "CUA-mode is now part of the standard GNU Emacs distribution,
8830 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8832 You have loaded an older version of CUA-mode which does not work
8833 correctly with this version of Emacs. You should remove the old
8834 version and use the one distributed with Emacs."))
8835 "Alist of packages known to cause problems in this version of Emacs.
8836 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8837 PACKAGE is either a regular expression to match file names, or a
8838 symbol (a feature name), like for `with-eval-after-load'.
8839 SYMBOL is either the name of a string variable, or t. Upon
8840 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8841 warning using STRING as the message.")
8843 (defun bad-package-check (package)
8844 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8845 (condition-case nil
8846 (let* ((list (assoc package bad-packages-alist))
8847 (symbol (nth 1 list)))
8848 (and list
8849 (boundp symbol)
8850 (or (eq symbol t)
8851 (and (stringp (setq symbol (eval symbol)))
8852 (string-match-p (nth 2 list) symbol)))
8853 (display-warning package (nth 3 list) :warning)))
8854 (error nil)))
8856 (dolist (elem bad-packages-alist)
8857 (let ((pkg (car elem)))
8858 (with-eval-after-load pkg
8859 (bad-package-check pkg))))
8862 ;;; Generic dispatcher commands
8864 ;; Macro `define-alternatives' is used to create generic commands.
8865 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8866 ;; that can have different alternative implementations where choosing
8867 ;; among them is exclusively a matter of user preference.
8869 ;; (define-alternatives COMMAND) creates a new interactive command
8870 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8871 ;; Typically, the user will not need to customize this variable; packages
8872 ;; wanting to add alternative implementations should use
8874 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8876 (defmacro define-alternatives (command &rest customizations)
8877 "Define the new command `COMMAND'.
8879 The argument `COMMAND' should be a symbol.
8881 Running `M-x COMMAND RET' for the first time prompts for which
8882 alternative to use and records the selected command as a custom
8883 variable.
8885 Running `C-u M-x COMMAND RET' prompts again for an alternative
8886 and overwrites the previous choice.
8888 The variable `COMMAND-alternatives' contains an alist with
8889 alternative implementations of COMMAND. `define-alternatives'
8890 does not have any effect until this variable is set.
8892 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8893 `defcustom' keywords and values to add to the declaration of
8894 `COMMAND-alternatives' (typically :group and :version)."
8895 (let* ((command-name (symbol-name command))
8896 (varalt-name (concat command-name "-alternatives"))
8897 (varalt-sym (intern varalt-name))
8898 (varimp-sym (intern (concat command-name "--implementation"))))
8899 `(progn
8901 (defcustom ,varalt-sym nil
8902 ,(format "Alist of alternative implementations for the `%s' command.
8904 Each entry must be a pair (ALTNAME . ALTFUN), where:
8905 ALTNAME - The name shown at user to describe the alternative implementation.
8906 ALTFUN - The function called to implement this alternative."
8907 command-name)
8908 :type '(alist :key-type string :value-type function)
8909 ,@customizations)
8911 (put ',varalt-sym 'definition-name ',command)
8912 (defvar ,varimp-sym nil "Internal use only.")
8914 (defun ,command (&optional arg)
8915 ,(format "Run generic command `%s'.
8916 If used for the first time, or with interactive ARG, ask the user which
8917 implementation to use for `%s'. The variable `%s'
8918 contains the list of implementations currently supported for this command."
8919 command-name command-name varalt-name)
8920 (interactive "P")
8921 (when (or arg (null ,varimp-sym))
8922 (let ((val (completing-read
8923 ,(format-message
8924 "Select implementation for command `%s': "
8925 command-name)
8926 ,varalt-sym nil t)))
8927 (unless (string-equal val "")
8928 (when (null ,varimp-sym)
8929 (message
8930 "Use C-u M-x %s RET`to select another implementation"
8931 ,command-name)
8932 (sit-for 3))
8933 (customize-save-variable ',varimp-sym
8934 (cdr (assoc-string val ,varalt-sym))))))
8935 (if ,varimp-sym
8936 (call-interactively ,varimp-sym)
8937 (message "%s" ,(format-message
8938 "No implementation selected for command `%s'"
8939 command-name)))))))
8942 ;;; Functions for changing capitalization that Do What I Mean
8943 (defun upcase-dwim (arg)
8944 "Upcase words in the region, if active; if not, upcase word at point.
8945 If the region is active, this function calls `upcase-region'.
8946 Otherwise, it calls `upcase-word', with prefix argument passed to it
8947 to upcase ARG words."
8948 (interactive "*p")
8949 (if (use-region-p)
8950 (upcase-region (region-beginning) (region-end))
8951 (upcase-word arg)))
8953 (defun downcase-dwim (arg)
8954 "Downcase words in the region, if active; if not, downcase word at point.
8955 If the region is active, this function calls `downcase-region'.
8956 Otherwise, it calls `downcase-word', with prefix argument passed to it
8957 to downcase ARG words."
8958 (interactive "*p")
8959 (if (use-region-p)
8960 (downcase-region (region-beginning) (region-end))
8961 (downcase-word arg)))
8963 (defun capitalize-dwim (arg)
8964 "Capitalize words in the region, if active; if not, capitalize word at point.
8965 If the region is active, this function calls `capitalize-region'.
8966 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8967 to capitalize ARG words."
8968 (interactive "*p")
8969 (if (use-region-p)
8970 (capitalize-region (region-beginning) (region-end))
8971 (capitalize-word arg)))
8975 (provide 'simple)
8977 ;;; simple.el ends here