; Fix typo in INSTALL
[emacs.git] / lisp / simple.el
blobdf664fc0503ad2df3e92ad01bfb547f9c5caaa78
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2017 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: internal
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
29 ;;; Code:
31 (eval-when-compile (require 'cl-lib))
33 (declare-function widget-convert "wid-edit" (type &rest args))
34 (declare-function shell-mode "shell" ())
36 ;;; From compile.el
37 (defvar compilation-current-error)
38 (defvar compilation-context-lines)
40 (defcustom shell-command-dont-erase-buffer nil
41 "If non-nil, output buffer is not erased between shell commands.
42 Also, a non-nil value set the point in the output buffer
43 once the command complete.
44 The value `beg-last-out' set point at the beginning of the output,
45 `end-last-out' set point at the end of the buffer, `save-point'
46 restore the buffer position before the command."
47 :type '(choice
48 (const :tag "Erase buffer" nil)
49 (const :tag "Set point to beginning of last output" beg-last-out)
50 (const :tag "Set point to end of last output" end-last-out)
51 (const :tag "Save point" save-point))
52 :group 'shell
53 :version "26.1")
55 (defvar shell-command-saved-pos nil
56 "Point position in the output buffer after command complete.
57 It is an alist (BUFFER . POS), where BUFFER is the output
58 buffer, and POS is the point position in BUFFER once the command finish.
59 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
61 (defcustom idle-update-delay 0.5
62 "Idle time delay before updating various things on the screen.
63 Various Emacs features that update auxiliary information when point moves
64 wait this many seconds after Emacs becomes idle before doing an update."
65 :type 'number
66 :group 'display
67 :version "22.1")
69 (defgroup killing nil
70 "Killing and yanking commands."
71 :group 'editing)
73 (defgroup paren-matching nil
74 "Highlight (un)matching of parens and expressions."
75 :group 'matching)
77 ;;; next-error support framework
79 (defgroup next-error nil
80 "`next-error' support framework."
81 :group 'compilation
82 :version "22.1")
84 (defface next-error
85 '((t (:inherit region)))
86 "Face used to highlight next error locus."
87 :group 'next-error
88 :version "22.1")
90 (defcustom next-error-highlight 0.5
91 "Highlighting of locations in selected source buffers.
92 If a number, highlight the locus in `next-error' face for the given time
93 in seconds, or until the next command is executed.
94 If t, highlight the locus until the next command is executed, or until
95 some other locus replaces it.
96 If nil, don't highlight the locus in the source buffer.
97 If `fringe-arrow', indicate the locus by the fringe arrow
98 indefinitely until some other locus replaces it."
99 :type '(choice (number :tag "Highlight for specified time")
100 (const :tag "Semipermanent highlighting" t)
101 (const :tag "No highlighting" nil)
102 (const :tag "Fringe arrow" fringe-arrow))
103 :group 'next-error
104 :version "22.1")
106 (defcustom next-error-highlight-no-select 0.5
107 "Highlighting of locations in `next-error-no-select'.
108 If number, highlight the locus in `next-error' face for given time in seconds.
109 If t, highlight the locus indefinitely until some other locus replaces it.
110 If nil, don't highlight the locus in the source buffer.
111 If `fringe-arrow', indicate the locus by the fringe arrow
112 indefinitely until some other locus replaces it."
113 :type '(choice (number :tag "Highlight for specified time")
114 (const :tag "Semipermanent highlighting" t)
115 (const :tag "No highlighting" nil)
116 (const :tag "Fringe arrow" fringe-arrow))
117 :group 'next-error
118 :version "22.1")
120 (defcustom next-error-recenter nil
121 "Display the line in the visited source file recentered as specified.
122 If non-nil, the value is passed directly to `recenter'."
123 :type '(choice (integer :tag "Line to recenter to")
124 (const :tag "Center of window" (4))
125 (const :tag "No recentering" nil))
126 :group 'next-error
127 :version "23.1")
129 (defcustom next-error-hook nil
130 "List of hook functions run by `next-error' after visiting source file."
131 :type 'hook
132 :group 'next-error)
134 (defvar next-error-highlight-timer nil)
136 (defvar next-error-overlay-arrow-position nil)
137 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
138 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
140 (defvar next-error-last-buffer nil
141 "The most recent `next-error' buffer.
142 A buffer becomes most recent when its compilation, grep, or
143 similar mode is started, or when it is used with \\[next-error]
144 or \\[compile-goto-error].")
146 (defvar next-error-function nil
147 "Function to use to find the next error in the current buffer.
148 The function is called with 2 parameters:
149 ARG is an integer specifying by how many errors to move.
150 RESET is a boolean which, if non-nil, says to go back to the beginning
151 of the errors before moving.
152 Major modes providing compile-like functionality should set this variable
153 to indicate to `next-error' that this is a candidate buffer and how
154 to navigate in it.")
155 (make-variable-buffer-local 'next-error-function)
157 (defvar next-error-move-function nil
158 "Function to use to move to an error locus.
159 It takes two arguments, a buffer position in the error buffer
160 and a buffer position in the error locus buffer.
161 The buffer for the error locus should already be current.
162 nil means use goto-char using the second argument position.")
163 (make-variable-buffer-local 'next-error-move-function)
165 (defsubst next-error-buffer-p (buffer
166 &optional avoid-current
167 extra-test-inclusive
168 extra-test-exclusive)
169 "Return non-nil if BUFFER is a `next-error' capable buffer.
170 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
171 return nil.
173 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
174 BUFFER would not normally qualify. If it returns non-nil, BUFFER
175 is considered `next-error' capable, anyway, and the function
176 returns non-nil.
178 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
179 buffer would normally qualify. If it returns nil, BUFFER is
180 rejected, and the function returns nil."
181 (and (buffer-name buffer) ;First make sure it's live.
182 (not (and avoid-current (eq buffer (current-buffer))))
183 (with-current-buffer buffer
184 (if next-error-function ; This is the normal test.
185 ;; Optionally reject some buffers.
186 (if extra-test-exclusive
187 (funcall extra-test-exclusive)
189 ;; Optionally accept some other buffers.
190 (and extra-test-inclusive
191 (funcall extra-test-inclusive))))))
193 (defun next-error-find-buffer (&optional avoid-current
194 extra-test-inclusive
195 extra-test-exclusive)
196 "Return a `next-error' capable buffer.
198 If AVOID-CURRENT is non-nil, treat the current buffer
199 as an absolute last resort only.
201 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
202 that normally would not qualify. If it returns t, the buffer
203 in question is treated as usable.
205 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
206 that would normally be considered usable. If it returns nil,
207 that buffer is rejected."
209 ;; 1. If one window on the selected frame displays such buffer, return it.
210 (let ((window-buffers
211 (delete-dups
212 (delq nil (mapcar (lambda (w)
213 (if (next-error-buffer-p
214 (window-buffer w)
215 avoid-current
216 extra-test-inclusive extra-test-exclusive)
217 (window-buffer w)))
218 (window-list))))))
219 (if (eq (length window-buffers) 1)
220 (car window-buffers)))
221 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
222 (if (and next-error-last-buffer
223 (next-error-buffer-p next-error-last-buffer avoid-current
224 extra-test-inclusive extra-test-exclusive))
225 next-error-last-buffer)
226 ;; 3. If the current buffer is acceptable, choose it.
227 (if (next-error-buffer-p (current-buffer) avoid-current
228 extra-test-inclusive extra-test-exclusive)
229 (current-buffer))
230 ;; 4. Look for any acceptable buffer.
231 (let ((buffers (buffer-list)))
232 (while (and buffers
233 (not (next-error-buffer-p
234 (car buffers) avoid-current
235 extra-test-inclusive extra-test-exclusive)))
236 (setq buffers (cdr buffers)))
237 (car buffers))
238 ;; 5. Use the current buffer as a last resort if it qualifies,
239 ;; even despite AVOID-CURRENT.
240 (and avoid-current
241 (next-error-buffer-p (current-buffer) nil
242 extra-test-inclusive extra-test-exclusive)
243 (progn
244 (message "This is the only buffer with error message locations")
245 (current-buffer)))
246 ;; 6. Give up.
247 (error "No buffers contain error message locations")))
249 (defun next-error (&optional arg reset)
250 "Visit next `next-error' message and corresponding source code.
252 If all the error messages parsed so far have been processed already,
253 the message buffer is checked for new ones.
255 A prefix ARG specifies how many error messages to move;
256 negative means move back to previous error messages.
257 Just \\[universal-argument] as a prefix means reparse the error message buffer
258 and start at the first error.
260 The RESET argument specifies that we should restart from the beginning.
262 \\[next-error] normally uses the most recently started
263 compilation, grep, or occur buffer. It can also operate on any
264 buffer with output from the \\[compile], \\[grep] commands, or,
265 more generally, on any buffer in Compilation mode or with
266 Compilation Minor mode enabled, or any buffer in which
267 `next-error-function' is bound to an appropriate function.
268 To specify use of a particular buffer for error messages, type
269 \\[next-error] in that buffer when it is the only one displayed
270 in the current frame.
272 Once \\[next-error] has chosen the buffer for error messages, it
273 runs `next-error-hook' with `run-hooks', and stays with that buffer
274 until you use it in some other buffer which uses Compilation mode
275 or Compilation Minor mode.
277 To control which errors are matched, customize the variable
278 `compilation-error-regexp-alist'."
279 (interactive "P")
280 (if (consp arg) (setq reset t arg nil))
281 (when (setq next-error-last-buffer (next-error-find-buffer))
282 ;; we know here that next-error-function is a valid symbol we can funcall
283 (with-current-buffer next-error-last-buffer
284 (funcall next-error-function (prefix-numeric-value arg) reset)
285 (when next-error-recenter
286 (recenter next-error-recenter))
287 (run-hooks 'next-error-hook))))
289 (defun next-error-internal ()
290 "Visit the source code corresponding to the `next-error' message at point."
291 (setq next-error-last-buffer (current-buffer))
292 ;; we know here that next-error-function is a valid symbol we can funcall
293 (with-current-buffer next-error-last-buffer
294 (funcall next-error-function 0 nil)
295 (when next-error-recenter
296 (recenter next-error-recenter))
297 (run-hooks 'next-error-hook)))
299 (defalias 'goto-next-locus 'next-error)
300 (defalias 'next-match 'next-error)
302 (defun previous-error (&optional n)
303 "Visit previous `next-error' message and corresponding source code.
305 Prefix arg N says how many error messages to move backwards (or
306 forwards, if negative).
308 This operates on the output from the \\[compile] and \\[grep] commands."
309 (interactive "p")
310 (next-error (- (or n 1))))
312 (defun first-error (&optional n)
313 "Restart at the first error.
314 Visit corresponding source code.
315 With prefix arg N, visit the source code of the Nth error.
316 This operates on the output from the \\[compile] command, for instance."
317 (interactive "p")
318 (next-error n t))
320 (defun next-error-no-select (&optional n)
321 "Move point to the next error in the `next-error' buffer and highlight match.
322 Prefix arg N says how many error messages to move forwards (or
323 backwards, if negative).
324 Finds and highlights the source line like \\[next-error], but does not
325 select the source buffer."
326 (interactive "p")
327 (let ((next-error-highlight next-error-highlight-no-select))
328 (next-error n))
329 (pop-to-buffer next-error-last-buffer))
331 (defun previous-error-no-select (&optional n)
332 "Move point to the previous error in the `next-error' buffer and highlight match.
333 Prefix arg N says how many error messages to move backwards (or
334 forwards, if negative).
335 Finds and highlights the source line like \\[previous-error], but does not
336 select the source buffer."
337 (interactive "p")
338 (next-error-no-select (- (or n 1))))
340 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
341 (defvar next-error-follow-last-line nil)
343 (define-minor-mode next-error-follow-minor-mode
344 "Minor mode for compilation, occur and diff modes.
345 With a prefix argument ARG, enable mode if ARG is positive, and
346 disable it otherwise. If called from Lisp, enable mode if ARG is
347 omitted or nil.
348 When turned on, cursor motion in the compilation, grep, occur or diff
349 buffer causes automatic display of the corresponding source code location."
350 :group 'next-error :init-value nil :lighter " Fol"
351 (if (not next-error-follow-minor-mode)
352 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
353 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
354 (make-local-variable 'next-error-follow-last-line)))
356 ;; Used as a `post-command-hook' by `next-error-follow-mode'
357 ;; for the *Compilation* *grep* and *Occur* buffers.
358 (defun next-error-follow-mode-post-command-hook ()
359 (unless (equal next-error-follow-last-line (line-number-at-pos))
360 (setq next-error-follow-last-line (line-number-at-pos))
361 (condition-case nil
362 (let ((compilation-context-lines nil))
363 (setq compilation-current-error (point))
364 (next-error-no-select 0))
365 (error t))))
370 (defun fundamental-mode ()
371 "Major mode not specialized for anything in particular.
372 Other major modes are defined by comparison with this one."
373 (interactive)
374 (kill-all-local-variables)
375 (run-mode-hooks))
377 ;; Special major modes to view specially formatted data rather than files.
379 (defvar special-mode-map
380 (let ((map (make-sparse-keymap)))
381 (suppress-keymap map)
382 (define-key map "q" 'quit-window)
383 (define-key map " " 'scroll-up-command)
384 (define-key map [?\S-\ ] 'scroll-down-command)
385 (define-key map "\C-?" 'scroll-down-command)
386 (define-key map "?" 'describe-mode)
387 (define-key map "h" 'describe-mode)
388 (define-key map ">" 'end-of-buffer)
389 (define-key map "<" 'beginning-of-buffer)
390 (define-key map "g" 'revert-buffer)
391 map))
393 (put 'special-mode 'mode-class 'special)
394 (define-derived-mode special-mode nil "Special"
395 "Parent major mode from which special major modes should inherit."
396 (setq buffer-read-only t))
398 ;; Making and deleting lines.
400 (defvar self-insert-uses-region-functions nil
401 "Special hook to tell if `self-insert-command' will use the region.
402 It must be called via `run-hook-with-args-until-success' with no arguments.
403 Any `post-self-insert-command' which consumes the region should
404 register a function on this hook so that things like `delete-selection-mode'
405 can refrain from consuming the region.")
407 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
408 "Propertized string representing a hard newline character.")
410 (defun newline (&optional arg interactive)
411 "Insert a newline, and move to left margin of the new line if it's blank.
412 If option `use-hard-newlines' is non-nil, the newline is marked with the
413 text-property `hard'.
414 With ARG, insert that many newlines.
416 If `electric-indent-mode' is enabled, this indents the final new line
417 that it adds, and reindents the preceding line. To just insert
418 a newline, use \\[electric-indent-just-newline].
420 Calls `auto-fill-function' if the current column number is greater
421 than the value of `fill-column' and ARG is nil.
422 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
423 (interactive "*P\np")
424 (barf-if-buffer-read-only)
425 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
426 ;; Set last-command-event to tell self-insert what to insert.
427 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
428 (beforepos (point))
429 (last-command-event ?\n)
430 ;; Don't auto-fill if we have a numeric argument.
431 (auto-fill-function (if arg nil auto-fill-function))
432 (arg (prefix-numeric-value arg))
433 (postproc
434 ;; Do the rest in post-self-insert-hook, because we want to do it
435 ;; *before* other functions on that hook.
436 (lambda ()
437 ;; We are not going to insert any newlines if arg is
438 ;; non-positive.
439 (or (and (numberp arg) (<= arg 0))
440 (cl-assert (eq ?\n (char-before))))
441 ;; Mark the newline(s) `hard'.
442 (if use-hard-newlines
443 (set-hard-newline-properties
444 (- (point) arg) (point)))
445 ;; If the newline leaves the previous line blank, and we
446 ;; have a left margin, delete that from the blank line.
447 (save-excursion
448 (goto-char beforepos)
449 (beginning-of-line)
450 (and (looking-at "[ \t]$")
451 (> (current-left-margin) 0)
452 (delete-region (point)
453 (line-end-position))))
454 ;; Indent the line after the newline, except in one case:
455 ;; when we added the newline at the beginning of a line which
456 ;; starts a page.
457 (or was-page-start
458 (move-to-left-margin nil t)))))
459 (unwind-protect
460 (if (not interactive)
461 ;; FIXME: For non-interactive uses, many calls actually
462 ;; just want (insert "\n"), so maybe we should do just
463 ;; that, so as to avoid the risk of filling or running
464 ;; abbrevs unexpectedly.
465 (let ((post-self-insert-hook (list postproc)))
466 (self-insert-command arg))
467 (unwind-protect
468 (progn
469 (add-hook 'post-self-insert-hook postproc nil t)
470 (self-insert-command arg))
471 ;; We first used let-binding to protect the hook, but that
472 ;; was naive since add-hook affects the symbol-default
473 ;; value of the variable, whereas the let-binding might
474 ;; only protect the buffer-local value.
475 (remove-hook 'post-self-insert-hook postproc t)))
476 (cl-assert (not (member postproc post-self-insert-hook)))
477 (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
478 nil)
480 (defun set-hard-newline-properties (from to)
481 (let ((sticky (get-text-property from 'rear-nonsticky)))
482 (put-text-property from to 'hard 't)
483 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
484 (if (and (listp sticky) (not (memq 'hard sticky)))
485 (put-text-property from (point) 'rear-nonsticky
486 (cons 'hard sticky)))))
488 (defun open-line (n)
489 "Insert a newline and leave point before it.
490 If there is a fill prefix and/or a `left-margin', insert them on
491 the new line if the line would have been blank.
492 With arg N, insert N newlines."
493 (interactive "*p")
494 (let* ((do-fill-prefix (and fill-prefix (bolp)))
495 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
496 (loc (point-marker))
497 ;; Don't expand an abbrev before point.
498 (abbrev-mode nil))
499 (newline n)
500 (goto-char loc)
501 (while (> n 0)
502 (cond ((bolp)
503 (if do-left-margin (indent-to (current-left-margin)))
504 (if do-fill-prefix (insert-and-inherit fill-prefix))))
505 (forward-line 1)
506 (setq n (1- n)))
507 (goto-char loc)
508 ;; Necessary in case a margin or prefix was inserted.
509 (end-of-line)))
511 (defun split-line (&optional arg)
512 "Split current line, moving portion beyond point vertically down.
513 If the current line starts with `fill-prefix', insert it on the new
514 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
516 When called from Lisp code, ARG may be a prefix string to copy."
517 (interactive "*P")
518 (skip-chars-forward " \t")
519 (let* ((col (current-column))
520 (pos (point))
521 ;; What prefix should we check for (nil means don't).
522 (prefix (cond ((stringp arg) arg)
523 (arg nil)
524 (t fill-prefix)))
525 ;; Does this line start with it?
526 (have-prfx (and prefix
527 (save-excursion
528 (beginning-of-line)
529 (looking-at (regexp-quote prefix))))))
530 (newline 1)
531 (if have-prfx (insert-and-inherit prefix))
532 (indent-to col 0)
533 (goto-char pos)))
535 (defun delete-indentation (&optional arg)
536 "Join this line to previous and fix up whitespace at join.
537 If there is a fill prefix, delete it from the beginning of this line.
538 With argument, join this line to following line."
539 (interactive "*P")
540 (beginning-of-line)
541 (if arg (forward-line 1))
542 (if (eq (preceding-char) ?\n)
543 (progn
544 (delete-region (point) (1- (point)))
545 ;; If the second line started with the fill prefix,
546 ;; delete the prefix.
547 (if (and fill-prefix
548 (<= (+ (point) (length fill-prefix)) (point-max))
549 (string= fill-prefix
550 (buffer-substring (point)
551 (+ (point) (length fill-prefix)))))
552 (delete-region (point) (+ (point) (length fill-prefix))))
553 (fixup-whitespace))))
555 (defalias 'join-line #'delete-indentation) ; easier to find
557 (defun delete-blank-lines ()
558 "On blank line, delete all surrounding blank lines, leaving just one.
559 On isolated blank line, delete that one.
560 On nonblank line, delete any immediately following blank lines."
561 (interactive "*")
562 (let (thisblank singleblank)
563 (save-excursion
564 (beginning-of-line)
565 (setq thisblank (looking-at "[ \t]*$"))
566 ;; Set singleblank if there is just one blank line here.
567 (setq singleblank
568 (and thisblank
569 (not (looking-at "[ \t]*\n[ \t]*$"))
570 (or (bobp)
571 (progn (forward-line -1)
572 (not (looking-at "[ \t]*$")))))))
573 ;; Delete preceding blank lines, and this one too if it's the only one.
574 (if thisblank
575 (progn
576 (beginning-of-line)
577 (if singleblank (forward-line 1))
578 (delete-region (point)
579 (if (re-search-backward "[^ \t\n]" nil t)
580 (progn (forward-line 1) (point))
581 (point-min)))))
582 ;; Delete following blank lines, unless the current line is blank
583 ;; and there are no following blank lines.
584 (if (not (and thisblank singleblank))
585 (save-excursion
586 (end-of-line)
587 (forward-line 1)
588 (delete-region (point)
589 (if (re-search-forward "[^ \t\n]" nil t)
590 (progn (beginning-of-line) (point))
591 (point-max)))))
592 ;; Handle the special case where point is followed by newline and eob.
593 ;; Delete the line, leaving point at eob.
594 (if (looking-at "^[ \t]*\n\\'")
595 (delete-region (point) (point-max)))))
597 (defcustom delete-trailing-lines t
598 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
599 Trailing lines are deleted only if `delete-trailing-whitespace'
600 is called on the entire buffer (rather than an active region)."
601 :type 'boolean
602 :group 'editing
603 :version "24.3")
605 (defun region-modifiable-p (start end)
606 "Return non-nil if the region contains no read-only text."
607 (and (not (get-text-property start 'read-only))
608 (eq end (next-single-property-change start 'read-only nil end))))
610 (defun delete-trailing-whitespace (&optional start end)
611 "Delete trailing whitespace between START and END.
612 If called interactively, START and END are the start/end of the
613 region if the mark is active, or of the buffer's accessible
614 portion if the mark is inactive.
616 This command deletes whitespace characters after the last
617 non-whitespace character in each line between START and END. It
618 does not consider formfeed characters to be whitespace.
620 If this command acts on the entire buffer (i.e. if called
621 interactively with the mark inactive, or called from Lisp with
622 END nil), it also deletes all trailing lines at the end of the
623 buffer if the variable `delete-trailing-lines' is non-nil."
624 (interactive (progn
625 (barf-if-buffer-read-only)
626 (if (use-region-p)
627 (list (region-beginning) (region-end))
628 (list nil nil))))
629 (save-match-data
630 (save-excursion
631 (let ((end-marker (and end (copy-marker end))))
632 (goto-char (or start (point-min)))
633 (with-syntax-table (make-syntax-table (syntax-table))
634 ;; Don't delete formfeeds, even if they are considered whitespace.
635 (modify-syntax-entry ?\f "_")
636 (while (re-search-forward "\\s-$" end-marker t)
637 (skip-syntax-backward "-" (line-beginning-position))
638 (let ((b (point)) (e (match-end 0)))
639 (when (region-modifiable-p b e)
640 (delete-region b e)))))
641 (if end
642 (set-marker end-marker nil)
643 ;; Delete trailing empty lines.
644 (and delete-trailing-lines
645 ;; Really the end of buffer.
646 (= (goto-char (point-max)) (1+ (buffer-size)))
647 (<= (skip-chars-backward "\n") -2)
648 (region-modifiable-p (1+ (point)) (point-max))
649 (delete-region (1+ (point)) (point-max)))))))
650 ;; Return nil for the benefit of `write-file-functions'.
651 nil)
653 (defun newline-and-indent ()
654 "Insert a newline, then indent according to major mode.
655 Indentation is done using the value of `indent-line-function'.
656 In programming language modes, this is the same as TAB.
657 In some text modes, where TAB inserts a tab, this command indents to the
658 column specified by the function `current-left-margin'."
659 (interactive "*")
660 (delete-horizontal-space t)
661 (newline nil t)
662 (indent-according-to-mode))
664 (defun reindent-then-newline-and-indent ()
665 "Reindent current line, insert newline, then indent the new line.
666 Indentation of both lines is done according to the current major mode,
667 which means calling the current value of `indent-line-function'.
668 In programming language modes, this is the same as TAB.
669 In some text modes, where TAB inserts a tab, this indents to the
670 column specified by the function `current-left-margin'."
671 (interactive "*")
672 (let ((pos (point)))
673 ;; Be careful to insert the newline before indenting the line.
674 ;; Otherwise, the indentation might be wrong.
675 (newline)
676 (save-excursion
677 (goto-char pos)
678 ;; We are at EOL before the call to indent-according-to-mode, and
679 ;; after it we usually are as well, but not always. We tried to
680 ;; address it with `save-excursion' but that uses a normal marker
681 ;; whereas we need `move after insertion', so we do the save/restore
682 ;; by hand.
683 (setq pos (copy-marker pos t))
684 (indent-according-to-mode)
685 (goto-char pos)
686 ;; Remove the trailing white-space after indentation because
687 ;; indentation may introduce the whitespace.
688 (delete-horizontal-space t))
689 (indent-according-to-mode)))
691 (defcustom read-quoted-char-radix 8
692 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
693 Legitimate radix values are 8, 10 and 16."
694 :type '(choice (const 8) (const 10) (const 16))
695 :group 'editing-basics)
697 (defun read-quoted-char (&optional prompt)
698 "Like `read-char', but do not allow quitting.
699 Also, if the first character read is an octal digit,
700 we read any number of octal digits and return the
701 specified character code. Any nondigit terminates the sequence.
702 If the terminator is RET, it is discarded;
703 any other terminator is used itself as input.
705 The optional argument PROMPT specifies a string to use to prompt the user.
706 The variable `read-quoted-char-radix' controls which radix to use
707 for numeric input."
708 (let ((message-log-max nil)
709 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
710 help-event-list)))
711 done (first t) (code 0) char translated)
712 (while (not done)
713 (let ((inhibit-quit first)
714 ;; Don't let C-h or other help chars get the help
715 ;; message--only help function keys. See bug#16617.
716 (help-char nil)
717 (help-event-list help-events)
718 (help-form
719 "Type the special character you want to use,
720 or the octal character code.
721 RET terminates the character code and is discarded;
722 any other non-digit terminates the character code and is then used as input."))
723 (setq char (read-event (and prompt (format "%s-" prompt)) t))
724 (if inhibit-quit (setq quit-flag nil)))
725 ;; Translate TAB key into control-I ASCII character, and so on.
726 ;; Note: `read-char' does it using the `ascii-character' property.
727 ;; We tried using read-key instead, but that disables the keystroke
728 ;; echo produced by 'C-q', see bug#24635.
729 (let ((translation (lookup-key local-function-key-map (vector char))))
730 (setq translated (if (arrayp translation)
731 (aref translation 0)
732 char)))
733 (if (integerp translated)
734 (setq translated (char-resolve-modifiers translated)))
735 (cond ((null translated))
736 ((not (integerp translated))
737 (setq unread-command-events (list char)
738 done t))
739 ((/= (logand translated ?\M-\^@) 0)
740 ;; Turn a meta-character into a character with the 0200 bit set.
741 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
742 done t))
743 ((and (<= ?0 translated)
744 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
745 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
746 (and prompt (setq prompt (message "%s %c" prompt translated))))
747 ((and (<= ?a (downcase translated))
748 (< (downcase translated)
749 (+ ?a -10 (min 36 read-quoted-char-radix))))
750 (setq code (+ (* code read-quoted-char-radix)
751 (+ 10 (- (downcase translated) ?a))))
752 (and prompt (setq prompt (message "%s %c" prompt translated))))
753 ((and (not first) (eq translated ?\C-m))
754 (setq done t))
755 ((not first)
756 (setq unread-command-events (list char)
757 done t))
758 (t (setq code translated
759 done t)))
760 (setq first nil))
761 code))
763 (defun quoted-insert (arg)
764 "Read next input character and insert it.
765 This is useful for inserting control characters.
766 With argument, insert ARG copies of the character.
768 If the first character you type after this command is an octal digit,
769 you should type a sequence of octal digits which specify a character code.
770 Any nondigit terminates the sequence. If the terminator is a RET,
771 it is discarded; any other terminator is used itself as input.
772 The variable `read-quoted-char-radix' specifies the radix for this feature;
773 set it to 10 or 16 to use decimal or hex instead of octal.
775 In overwrite mode, this function inserts the character anyway, and
776 does not handle octal digits specially. This means that if you use
777 overwrite as your normal editing mode, you can use this function to
778 insert characters when necessary.
780 In binary overwrite mode, this function does overwrite, and octal
781 digits are interpreted as a character code. This is intended to be
782 useful for editing binary files."
783 (interactive "*p")
784 (let* ((char
785 ;; Avoid "obsolete" warnings for translation-table-for-input.
786 (with-no-warnings
787 (let (translation-table-for-input input-method-function)
788 (if (or (not overwrite-mode)
789 (eq overwrite-mode 'overwrite-mode-binary))
790 (read-quoted-char)
791 (read-char))))))
792 ;; This used to assume character codes 0240 - 0377 stand for
793 ;; characters in some single-byte character set, and converted them
794 ;; to Emacs characters. But in 23.1 this feature is deprecated
795 ;; in favor of inserting the corresponding Unicode characters.
796 ;; (if (and enable-multibyte-characters
797 ;; (>= char ?\240)
798 ;; (<= char ?\377))
799 ;; (setq char (unibyte-char-to-multibyte char)))
800 (unless (characterp char)
801 (user-error "%s is not a valid character"
802 (key-description (vector char))))
803 (if (> arg 0)
804 (if (eq overwrite-mode 'overwrite-mode-binary)
805 (delete-char arg)))
806 (while (> arg 0)
807 (insert-and-inherit char)
808 (setq arg (1- arg)))))
810 (defun forward-to-indentation (&optional arg)
811 "Move forward ARG lines and position at first nonblank character."
812 (interactive "^p")
813 (forward-line (or arg 1))
814 (skip-chars-forward " \t"))
816 (defun backward-to-indentation (&optional arg)
817 "Move backward ARG lines and position at first nonblank character."
818 (interactive "^p")
819 (forward-line (- (or arg 1)))
820 (skip-chars-forward " \t"))
822 (defun back-to-indentation ()
823 "Move point to the first non-whitespace character on this line."
824 (interactive "^")
825 (beginning-of-line 1)
826 (skip-syntax-forward " " (line-end-position))
827 ;; Move back over chars that have whitespace syntax but have the p flag.
828 (backward-prefix-chars))
830 (defun fixup-whitespace ()
831 "Fixup white space between objects around point.
832 Leave one space or none, according to the context."
833 (interactive "*")
834 (save-excursion
835 (delete-horizontal-space)
836 (if (or (looking-at "^\\|$\\|\\s)")
837 (save-excursion (forward-char -1)
838 (looking-at "$\\|\\s(\\|\\s'")))
840 (insert ?\s))))
842 (defun delete-horizontal-space (&optional backward-only)
843 "Delete all spaces and tabs around point.
844 If BACKWARD-ONLY is non-nil, only delete them before point."
845 (interactive "*P")
846 (let ((orig-pos (point)))
847 (delete-region
848 (if backward-only
849 orig-pos
850 (progn
851 (skip-chars-forward " \t")
852 (constrain-to-field nil orig-pos t)))
853 (progn
854 (skip-chars-backward " \t")
855 (constrain-to-field nil orig-pos)))))
857 (defun just-one-space (&optional n)
858 "Delete all spaces and tabs around point, leaving one space (or N spaces).
859 If N is negative, delete newlines as well, leaving -N spaces.
860 See also `cycle-spacing'."
861 (interactive "*p")
862 (cycle-spacing n nil 'single-shot))
864 (defvar cycle-spacing--context nil
865 "Store context used in consecutive calls to `cycle-spacing' command.
866 The first time `cycle-spacing' runs, it saves in this variable:
867 its N argument, the original point position, and the original spacing
868 around point.")
870 (defun cycle-spacing (&optional n preserve-nl-back mode)
871 "Manipulate whitespace around point in a smart way.
872 In interactive use, this function behaves differently in successive
873 consecutive calls.
875 The first call in a sequence acts like `just-one-space'.
876 It deletes all spaces and tabs around point, leaving one space
877 \(or N spaces). N is the prefix argument. If N is negative,
878 it deletes newlines as well, leaving -N spaces.
879 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
881 The second call in a sequence deletes all spaces.
883 The third call in a sequence restores the original whitespace (and point).
885 If MODE is `single-shot', it only performs the first step in the sequence.
886 If MODE is `fast' and the first step would not result in any change
887 \(i.e., there are exactly (abs N) spaces around point),
888 the function goes straight to the second step.
890 Repeatedly calling the function with different values of N starts a
891 new sequence each time."
892 (interactive "*p")
893 (let ((orig-pos (point))
894 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
895 (num (abs (or n 1))))
896 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
897 (constrain-to-field nil orig-pos)
898 (cond
899 ;; Command run for the first time, single-shot mode or different argument
900 ((or (eq 'single-shot mode)
901 (not (equal last-command this-command))
902 (not cycle-spacing--context)
903 (not (eq (car cycle-spacing--context) n)))
904 (let* ((start (point))
905 (num (- num (skip-chars-forward " " (+ num (point)))))
906 (mid (point))
907 (end (progn
908 (skip-chars-forward skip-characters)
909 (constrain-to-field nil orig-pos t))))
910 (setq cycle-spacing--context ;; Save for later.
911 ;; Special handling for case where there was no space at all.
912 (unless (= start end)
913 (cons n (cons orig-pos (buffer-substring start (point))))))
914 ;; If this run causes no change in buffer content, delete all spaces,
915 ;; otherwise delete all excess spaces.
916 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
917 start mid) end)
918 (insert (make-string num ?\s))))
920 ;; Command run for the second time.
921 ((not (equal orig-pos (point)))
922 (delete-region (point) orig-pos))
924 ;; Command run for the third time.
926 (insert (cddr cycle-spacing--context))
927 (goto-char (cadr cycle-spacing--context))
928 (setq cycle-spacing--context nil)))))
930 (defun beginning-of-buffer (&optional arg)
931 "Move point to the beginning of the buffer.
932 With numeric arg N, put point N/10 of the way from the beginning.
933 If the buffer is narrowed, this command uses the beginning of the
934 accessible part of the buffer.
936 Push mark at previous position, unless either a \\[universal-argument] prefix
937 is supplied, or Transient Mark mode is enabled and the mark is active."
938 (declare (interactive-only "use `(goto-char (point-min))' instead."))
939 (interactive "^P")
940 (or (consp arg)
941 (region-active-p)
942 (push-mark))
943 (let ((size (- (point-max) (point-min))))
944 (goto-char (if (and arg (not (consp arg)))
945 (+ (point-min)
946 (if (> size 10000)
947 ;; Avoid overflow for large buffer sizes!
948 (* (prefix-numeric-value arg)
949 (/ size 10))
950 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
951 (point-min))))
952 (if (and arg (not (consp arg))) (forward-line 1)))
954 (defun end-of-buffer (&optional arg)
955 "Move point to the end of the buffer.
956 With numeric arg N, put point N/10 of the way from the end.
957 If the buffer is narrowed, this command uses the end of the
958 accessible part of the buffer.
960 Push mark at previous position, unless either a \\[universal-argument] prefix
961 is supplied, or Transient Mark mode is enabled and the mark is active."
962 (declare (interactive-only "use `(goto-char (point-max))' instead."))
963 (interactive "^P")
964 (or (consp arg) (region-active-p) (push-mark))
965 (let ((size (- (point-max) (point-min))))
966 (goto-char (if (and arg (not (consp arg)))
967 (- (point-max)
968 (if (> size 10000)
969 ;; Avoid overflow for large buffer sizes!
970 (* (prefix-numeric-value arg)
971 (/ size 10))
972 (/ (* size (prefix-numeric-value arg)) 10)))
973 (point-max))))
974 ;; If we went to a place in the middle of the buffer,
975 ;; adjust it to the beginning of a line.
976 (cond ((and arg (not (consp arg))) (forward-line 1))
977 ((and (eq (current-buffer) (window-buffer))
978 (> (point) (window-end nil t)))
979 ;; If the end of the buffer is not already on the screen,
980 ;; then scroll specially to put it near, but not at, the bottom.
981 (overlay-recenter (point))
982 (recenter -3))))
984 (defcustom delete-active-region t
985 "Whether single-char deletion commands delete an active region.
986 This has an effect only if Transient Mark mode is enabled, and
987 affects `delete-forward-char' and `delete-backward-char', though
988 not `delete-char'.
990 If the value is the symbol `kill', the active region is killed
991 instead of deleted."
992 :type '(choice (const :tag "Delete active region" t)
993 (const :tag "Kill active region" kill)
994 (const :tag "Do ordinary deletion" nil))
995 :group 'killing
996 :version "24.1")
998 (defvar region-extract-function
999 (lambda (delete)
1000 (when (region-beginning)
1001 (cond
1002 ((eq delete 'bounds)
1003 (list (cons (region-beginning) (region-end))))
1004 ((eq delete 'delete-only)
1005 (delete-region (region-beginning) (region-end)))
1007 (filter-buffer-substring (region-beginning) (region-end) delete)))))
1008 "Function to get the region's content.
1009 Called with one argument DELETE.
1010 If DELETE is `delete-only', then only delete the region and the return value
1011 is undefined. If DELETE is nil, just return the content as a string.
1012 If DELETE is `bounds', then don't delete, but just return the
1013 boundaries of the region as a list of (START . END) positions.
1014 If anything else, delete the region and return its content as a string,
1015 after filtering it with `filter-buffer-substring'.")
1017 (defvar region-insert-function
1018 (lambda (lines)
1019 (let ((first t))
1020 (while lines
1021 (or first
1022 (insert ?\n))
1023 (insert-for-yank (car lines))
1024 (setq lines (cdr lines)
1025 first nil))))
1026 "Function to insert the region's content.
1027 Called with one argument LINES.
1028 Insert the region as a list of lines.")
1030 (defun delete-backward-char (n &optional killflag)
1031 "Delete the previous N characters (following if N is negative).
1032 If Transient Mark mode is enabled, the mark is active, and N is 1,
1033 delete the text in the region and deactivate the mark instead.
1034 To disable this, set option `delete-active-region' to nil.
1036 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1037 kill ring) instead of delete. Interactively, N is the prefix
1038 arg, and KILLFLAG is set if N is explicitly specified.
1040 When killing, the killed text is filtered by
1041 `filter-buffer-substring' before it is saved in the kill ring, so
1042 the actual saved text might be different from what was killed.
1044 In Overwrite mode, single character backward deletion may replace
1045 tabs with spaces so as to back over columns, unless point is at
1046 the end of the line."
1047 (declare (interactive-only delete-char))
1048 (interactive "p\nP")
1049 (unless (integerp n)
1050 (signal 'wrong-type-argument (list 'integerp n)))
1051 (cond ((and (use-region-p)
1052 delete-active-region
1053 (= n 1))
1054 ;; If a region is active, kill or delete it.
1055 (if (eq delete-active-region 'kill)
1056 (kill-region (region-beginning) (region-end) 'region)
1057 (funcall region-extract-function 'delete-only)))
1058 ;; In Overwrite mode, maybe untabify while deleting
1059 ((null (or (null overwrite-mode)
1060 (<= n 0)
1061 (memq (char-before) '(?\t ?\n))
1062 (eobp)
1063 (eq (char-after) ?\n)))
1064 (let ((ocol (current-column)))
1065 (delete-char (- n) killflag)
1066 (save-excursion
1067 (insert-char ?\s (- ocol (current-column)) nil))))
1068 ;; Otherwise, do simple deletion.
1069 (t (delete-char (- n) killflag))))
1071 (defun delete-forward-char (n &optional killflag)
1072 "Delete the following N characters (previous if N is negative).
1073 If Transient Mark mode is enabled, the mark is active, and N is 1,
1074 delete the text in the region and deactivate the mark instead.
1075 To disable this, set variable `delete-active-region' to nil.
1077 Optional second arg KILLFLAG non-nil means to kill (save in kill
1078 ring) instead of delete. Interactively, N is the prefix arg, and
1079 KILLFLAG is set if N was explicitly specified.
1081 When killing, the killed text is filtered by
1082 `filter-buffer-substring' before it is saved in the kill ring, so
1083 the actual saved text might be different from what was killed."
1084 (declare (interactive-only delete-char))
1085 (interactive "p\nP")
1086 (unless (integerp n)
1087 (signal 'wrong-type-argument (list 'integerp n)))
1088 (cond ((and (use-region-p)
1089 delete-active-region
1090 (= n 1))
1091 ;; If a region is active, kill or delete it.
1092 (if (eq delete-active-region 'kill)
1093 (kill-region (region-beginning) (region-end) 'region)
1094 (funcall region-extract-function 'delete-only)))
1096 ;; Otherwise, do simple deletion.
1097 (t (delete-char n killflag))))
1099 (defun mark-whole-buffer ()
1100 "Put point at beginning and mark at end of buffer.
1101 If narrowing is in effect, only uses the accessible part of the buffer.
1102 You probably should not use this function in Lisp programs;
1103 it is usually a mistake for a Lisp function to use any subroutine
1104 that uses or sets the mark."
1105 (declare (interactive-only t))
1106 (interactive)
1107 (push-mark)
1108 (push-mark (point-max) nil t)
1109 ;; This is really `point-min' in most cases, but if we're in the
1110 ;; minibuffer, this is at the end of the prompt.
1111 (goto-char (minibuffer-prompt-end)))
1114 ;; Counting lines, one way or another.
1116 (defun goto-line (line &optional buffer)
1117 "Go to LINE, counting from line 1 at beginning of buffer.
1118 If called interactively, a numeric prefix argument specifies
1119 LINE; without a numeric prefix argument, read LINE from the
1120 minibuffer.
1122 If optional argument BUFFER is non-nil, switch to that buffer and
1123 move to line LINE there. If called interactively with \\[universal-argument]
1124 as argument, BUFFER is the most recently selected other buffer.
1126 Prior to moving point, this function sets the mark (without
1127 activating it), unless Transient Mark mode is enabled and the
1128 mark is already active.
1130 This function is usually the wrong thing to use in a Lisp program.
1131 What you probably want instead is something like:
1132 (goto-char (point-min))
1133 (forward-line (1- N))
1134 If at all possible, an even better solution is to use char counts
1135 rather than line counts."
1136 (declare (interactive-only forward-line))
1137 (interactive
1138 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1139 (list (prefix-numeric-value current-prefix-arg))
1140 ;; Look for a default, a number in the buffer at point.
1141 (let* ((default
1142 (save-excursion
1143 (skip-chars-backward "0-9")
1144 (if (looking-at "[0-9]")
1145 (string-to-number
1146 (buffer-substring-no-properties
1147 (point)
1148 (progn (skip-chars-forward "0-9")
1149 (point)))))))
1150 ;; Decide if we're switching buffers.
1151 (buffer
1152 (if (consp current-prefix-arg)
1153 (other-buffer (current-buffer) t)))
1154 (buffer-prompt
1155 (if buffer
1156 (concat " in " (buffer-name buffer))
1157 "")))
1158 ;; Read the argument, offering that number (if any) as default.
1159 (list (read-number (format "Goto line%s: " buffer-prompt)
1160 (list default (line-number-at-pos)))
1161 buffer))))
1162 ;; Switch to the desired buffer, one way or another.
1163 (if buffer
1164 (let ((window (get-buffer-window buffer)))
1165 (if window (select-window window)
1166 (switch-to-buffer-other-window buffer))))
1167 ;; Leave mark at previous position
1168 (or (region-active-p) (push-mark))
1169 ;; Move to the specified line number in that buffer.
1170 (save-restriction
1171 (widen)
1172 (goto-char (point-min))
1173 (if (eq selective-display t)
1174 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1175 (forward-line (1- line)))))
1177 (defun count-words-region (start end &optional arg)
1178 "Count the number of words in the region.
1179 If called interactively, print a message reporting the number of
1180 lines, words, and characters in the region (whether or not the
1181 region is active); with prefix ARG, report for the entire buffer
1182 rather than the region.
1184 If called from Lisp, return the number of words between positions
1185 START and END."
1186 (interactive (if current-prefix-arg
1187 (list nil nil current-prefix-arg)
1188 (list (region-beginning) (region-end) nil)))
1189 (cond ((not (called-interactively-p 'any))
1190 (count-words start end))
1191 (arg
1192 (count-words--buffer-message))
1194 (count-words--message "Region" start end))))
1196 (defun count-words (start end)
1197 "Count words between START and END.
1198 If called interactively, START and END are normally the start and
1199 end of the buffer; but if the region is active, START and END are
1200 the start and end of the region. Print a message reporting the
1201 number of lines, words, and chars.
1203 If called from Lisp, return the number of words between START and
1204 END, without printing any message."
1205 (interactive (list nil nil))
1206 (cond ((not (called-interactively-p 'any))
1207 (let ((words 0))
1208 (save-excursion
1209 (save-restriction
1210 (narrow-to-region start end)
1211 (goto-char (point-min))
1212 (while (forward-word-strictly 1)
1213 (setq words (1+ words)))))
1214 words))
1215 ((use-region-p)
1216 (call-interactively 'count-words-region))
1218 (count-words--buffer-message))))
1220 (defun count-words--buffer-message ()
1221 (count-words--message
1222 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1223 (point-min) (point-max)))
1225 (defun count-words--message (str start end)
1226 (let ((lines (count-lines start end))
1227 (words (count-words start end))
1228 (chars (- end start)))
1229 (message "%s has %d line%s, %d word%s, and %d character%s."
1231 lines (if (= lines 1) "" "s")
1232 words (if (= words 1) "" "s")
1233 chars (if (= chars 1) "" "s"))))
1235 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1237 (defun what-line ()
1238 "Print the current buffer line number and narrowed line number of point."
1239 (interactive)
1240 (let ((start (point-min))
1241 (n (line-number-at-pos)))
1242 (if (= start 1)
1243 (message "Line %d" n)
1244 (save-excursion
1245 (save-restriction
1246 (widen)
1247 (message "line %d (narrowed line %d)"
1248 (+ n (line-number-at-pos start) -1) n))))))
1250 (defun count-lines (start end)
1251 "Return number of lines between START and END.
1252 This is usually the number of newlines between them,
1253 but can be one more if START is not equal to END
1254 and the greater of them is not at the start of a line."
1255 (save-excursion
1256 (save-restriction
1257 (narrow-to-region start end)
1258 (goto-char (point-min))
1259 (if (eq selective-display t)
1260 (save-match-data
1261 (let ((done 0))
1262 (while (re-search-forward "[\n\C-m]" nil t 40)
1263 (setq done (+ 40 done)))
1264 (while (re-search-forward "[\n\C-m]" nil t 1)
1265 (setq done (+ 1 done)))
1266 (goto-char (point-max))
1267 (if (and (/= start end)
1268 (not (bolp)))
1269 (1+ done)
1270 done)))
1271 (- (buffer-size) (forward-line (buffer-size)))))))
1273 (defun line-number-at-pos (&optional pos)
1274 "Return (narrowed) buffer line number at position POS.
1275 If POS is nil, use current buffer location.
1276 Counting starts at (point-min), so the value refers
1277 to the contents of the accessible portion of the buffer."
1278 (let ((opoint (or pos (point))) start)
1279 (save-excursion
1280 (goto-char (point-min))
1281 (setq start (point))
1282 (goto-char opoint)
1283 (forward-line 0)
1284 (1+ (count-lines start (point))))))
1286 (defun what-cursor-position (&optional detail)
1287 "Print info on cursor position (on screen and within buffer).
1288 Also describe the character after point, and give its character code
1289 in octal, decimal and hex.
1291 For a non-ASCII multibyte character, also give its encoding in the
1292 buffer's selected coding system if the coding system encodes the
1293 character safely. If the character is encoded into one byte, that
1294 code is shown in hex. If the character is encoded into more than one
1295 byte, just \"...\" is shown.
1297 In addition, with prefix argument, show details about that character
1298 in *Help* buffer. See also the command `describe-char'."
1299 (interactive "P")
1300 (let* ((char (following-char))
1301 (bidi-fixer
1302 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1303 ;; start a directional embedding, which could completely
1304 ;; disrupt the rest of the line (e.g., RLO will display the
1305 ;; rest of the line right-to-left). So we put an invisible
1306 ;; PDF character after these characters, to end the
1307 ;; embedding, which eliminates any effects on the rest of
1308 ;; the line. For RLE and RLO we also append an invisible
1309 ;; LRM, to avoid reordering the following numerical
1310 ;; characters. For LRI/RLI/FSI we append a PDI.
1311 (cond ((memq char '(?\x202a ?\x202d))
1312 (propertize (string ?\x202c) 'invisible t))
1313 ((memq char '(?\x202b ?\x202e))
1314 (propertize (string ?\x202c ?\x200e) 'invisible t))
1315 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1316 (propertize (string ?\x2069) 'invisible t))
1317 ;; Strong right-to-left characters cause reordering of
1318 ;; the following numerical characters which show the
1319 ;; codepoint, so append LRM to countermand that.
1320 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1321 (propertize (string ?\x200e) 'invisible t))
1323 "")))
1324 (beg (point-min))
1325 (end (point-max))
1326 (pos (point))
1327 (total (buffer-size))
1328 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1329 (hscroll (if (= (window-hscroll) 0)
1331 (format " Hscroll=%d" (window-hscroll))))
1332 (col (current-column)))
1333 (if (= pos end)
1334 (if (or (/= beg 1) (/= end (1+ total)))
1335 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1336 pos total percent beg end col hscroll)
1337 (message "point=%d of %d (EOB) column=%d%s"
1338 pos total col hscroll))
1339 (let ((coding buffer-file-coding-system)
1340 encoded encoding-msg display-prop under-display)
1341 (if (or (not coding)
1342 (eq (coding-system-type coding) t))
1343 (setq coding (default-value 'buffer-file-coding-system)))
1344 (if (eq (char-charset char) 'eight-bit)
1345 (setq encoding-msg
1346 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1347 ;; Check if the character is displayed with some `display'
1348 ;; text property. In that case, set under-display to the
1349 ;; buffer substring covered by that property.
1350 (setq display-prop (get-char-property pos 'display))
1351 (if display-prop
1352 (let ((to (or (next-single-char-property-change pos 'display)
1353 (point-max))))
1354 (if (< to (+ pos 4))
1355 (setq under-display "")
1356 (setq under-display "..."
1357 to (+ pos 4)))
1358 (setq under-display
1359 (concat (buffer-substring-no-properties pos to)
1360 under-display)))
1361 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1362 (setq encoding-msg
1363 (if display-prop
1364 (if (not (stringp display-prop))
1365 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1366 char char char under-display)
1367 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1368 char char char under-display display-prop))
1369 (if encoded
1370 (format "(%d, #o%o, #x%x, file %s)"
1371 char char char
1372 (if (> (length encoded) 1)
1373 "..."
1374 (encoded-string-description encoded coding)))
1375 (format "(%d, #o%o, #x%x)" char char char)))))
1376 (if detail
1377 ;; We show the detailed information about CHAR.
1378 (describe-char (point)))
1379 (if (or (/= beg 1) (/= end (1+ total)))
1380 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1381 (if (< char 256)
1382 (single-key-description char)
1383 (buffer-substring-no-properties (point) (1+ (point))))
1384 bidi-fixer
1385 encoding-msg pos total percent beg end col hscroll)
1386 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1387 (if enable-multibyte-characters
1388 (if (< char 128)
1389 (single-key-description char)
1390 (buffer-substring-no-properties (point) (1+ (point))))
1391 (single-key-description char))
1392 bidi-fixer encoding-msg pos total percent col hscroll))))))
1394 ;; Initialize read-expression-map. It is defined at C level.
1395 (defvar read-expression-map
1396 (let ((m (make-sparse-keymap)))
1397 (define-key m "\M-\t" 'completion-at-point)
1398 ;; Might as well bind TAB to completion, since inserting a TAB char is
1399 ;; much too rarely useful.
1400 (define-key m "\t" 'completion-at-point)
1401 (set-keymap-parent m minibuffer-local-map)
1404 (defun read-minibuffer (prompt &optional initial-contents)
1405 "Return a Lisp object read using the minibuffer, unevaluated.
1406 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1407 is a string to insert in the minibuffer before reading.
1408 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1409 Such arguments are used as in `read-from-minibuffer'.)"
1410 ;; Used for interactive spec `x'.
1411 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1412 t 'minibuffer-history))
1414 (defun eval-minibuffer (prompt &optional initial-contents)
1415 "Return value of Lisp expression read using the minibuffer.
1416 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1417 is a string to insert in the minibuffer before reading.
1418 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1419 Such arguments are used as in `read-from-minibuffer'.)"
1420 ;; Used for interactive spec `X'.
1421 (eval (read--expression prompt initial-contents)))
1423 (defvar minibuffer-completing-symbol nil
1424 "Non-nil means completing a Lisp symbol in the minibuffer.")
1425 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1427 (defvar minibuffer-default nil
1428 "The current default value or list of default values in the minibuffer.
1429 The functions `read-from-minibuffer' and `completing-read' bind
1430 this variable locally.")
1432 (defcustom eval-expression-print-level 4
1433 "Value for `print-level' while printing value in `eval-expression'.
1434 A value of nil means no limit."
1435 :group 'lisp
1436 :type '(choice (const :tag "No Limit" nil) integer)
1437 :version "21.1")
1439 (defcustom eval-expression-print-length 12
1440 "Value for `print-length' while printing value in `eval-expression'.
1441 A value of nil means no limit."
1442 :group 'lisp
1443 :type '(choice (const :tag "No Limit" nil) integer)
1444 :version "21.1")
1446 (defcustom eval-expression-debug-on-error t
1447 "If non-nil set `debug-on-error' to t in `eval-expression'.
1448 If nil, don't change the value of `debug-on-error'."
1449 :group 'lisp
1450 :type 'boolean
1451 :version "21.1")
1453 (defcustom eval-expression-print-maximum-character 127
1454 "The largest integer that will be displayed as a character.
1455 This affects printing by `eval-expression' (via
1456 `eval-expression-print-format')."
1457 :group 'lisp
1458 :type 'integer
1459 :version "26.1")
1461 (defun eval-expression-print-format (value)
1462 "If VALUE in an integer, return a specially formatted string.
1463 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1464 If VALUE is not an integer, nil is returned.
1465 This function is used by commands like `eval-expression' that
1466 display the result of expression evaluation."
1467 (when (integerp value)
1468 (let ((char-string
1469 (and (characterp value)
1470 (<= value eval-expression-print-maximum-character)
1471 (char-displayable-p value)
1472 (prin1-char value))))
1473 (if char-string
1474 (format " (#o%o, #x%x, %s)" value value char-string)
1475 (format " (#o%o, #x%x)" value value)))))
1477 (defvar eval-expression-minibuffer-setup-hook nil
1478 "Hook run by `eval-expression' when entering the minibuffer.")
1480 (defun read--expression (prompt &optional initial-contents)
1481 (let ((minibuffer-completing-symbol t))
1482 (minibuffer-with-setup-hook
1483 (lambda ()
1484 ;; FIXME: call emacs-lisp-mode?
1485 (add-function :before-until (local 'eldoc-documentation-function)
1486 #'elisp-eldoc-documentation-function)
1487 (eldoc-mode 1)
1488 (add-hook 'completion-at-point-functions
1489 #'elisp-completion-at-point nil t)
1490 (run-hooks 'eval-expression-minibuffer-setup-hook))
1491 (read-from-minibuffer prompt initial-contents
1492 read-expression-map t
1493 'read-expression-history))))
1495 (defun eval-expression-get-print-arguments (prefix-argument)
1496 "Get arguments for commands that print an expression result.
1497 Returns a list (INSERT-VALUE NO-TRUNCATE CHAR-PRINT-LIMIT)
1498 based on PREFIX-ARG. This function determines the interpretation
1499 of the prefix argument for `eval-expression' and
1500 `eval-last-sexp'."
1501 (let ((num (prefix-numeric-value prefix-argument)))
1502 (list (not (memq prefix-argument '(- nil)))
1503 (= num 0)
1504 (cond ((not (memq prefix-argument '(0 -1 - nil))) nil)
1505 ((= num -1) most-positive-fixnum)
1506 (t eval-expression-print-maximum-character)))))
1508 ;; We define this, rather than making `eval' interactive,
1509 ;; for the sake of completion of names like eval-region, eval-buffer.
1510 (defun eval-expression (exp &optional insert-value no-truncate char-print-limit)
1511 "Evaluate EXP and print value in the echo area.
1512 When called interactively, read an Emacs Lisp expression and
1513 evaluate it. Value is also consed on to front of the variable
1514 `values'. Optional argument INSERT-VALUE non-nil (interactively,
1515 with a non `-' prefix argument) means insert the result into the
1516 current buffer instead of printing it in the echo area.
1518 Normally, this function truncates long output according to the
1519 value of the variables `eval-expression-print-length' and
1520 `eval-expression-print-level'. When NO-TRUNCATE is
1521 non-nil (interactively, with a prefix argument of zero), however,
1522 there is no such truncation.
1524 If the resulting value is an integer, and CHAR-PRINT-LIMIT is
1525 non-nil (interactively, unless given a positive prefix argument)
1526 it will be printed in several additional formats (octal,
1527 hexadecimal, and character). The character format is only used
1528 if the value is below CHAR-PRINT-LIMIT (interactively, if the
1529 prefix argument is -1 or the value is below
1530 `eval-expression-print-maximum-character').
1532 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1533 minibuffer.
1535 If `eval-expression-debug-on-error' is non-nil, which is the default,
1536 this command arranges for all errors to enter the debugger."
1537 (interactive
1538 (cons (read--expression "Eval: ")
1539 (eval-expression-get-print-arguments current-prefix-arg)))
1541 (if (null eval-expression-debug-on-error)
1542 (push (eval exp lexical-binding) values)
1543 (let ((old-value (make-symbol "t")) new-value)
1544 ;; Bind debug-on-error to something unique so that we can
1545 ;; detect when evalled code changes it.
1546 (let ((debug-on-error old-value))
1547 (push (eval (macroexpand-all exp) lexical-binding) values)
1548 (setq new-value debug-on-error))
1549 ;; If evalled code has changed the value of debug-on-error,
1550 ;; propagate that change to the global binding.
1551 (unless (eq old-value new-value)
1552 (setq debug-on-error new-value))))
1554 (let ((print-length (unless no-truncate eval-expression-print-length))
1555 (print-level (unless no-truncate eval-expression-print-level))
1556 (eval-expression-print-maximum-character char-print-limit)
1557 (deactivate-mark))
1558 (let ((out (if insert-value (current-buffer) t)))
1559 (prog1
1560 (prin1 (car values) out)
1561 (let ((str (and char-print-limit
1562 (eval-expression-print-format (car values)))))
1563 (when str (princ str out)))))))
1565 (defun edit-and-eval-command (prompt command)
1566 "Prompting with PROMPT, let user edit COMMAND and eval result.
1567 COMMAND is a Lisp expression. Let user edit that expression in
1568 the minibuffer, then read and evaluate the result."
1569 (let ((command
1570 (let ((print-level nil)
1571 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1572 (unwind-protect
1573 (read-from-minibuffer prompt
1574 (prin1-to-string command)
1575 read-expression-map t
1576 'command-history)
1577 ;; If command was added to command-history as a string,
1578 ;; get rid of that. We want only evaluable expressions there.
1579 (if (stringp (car command-history))
1580 (setq command-history (cdr command-history)))))))
1582 ;; If command to be redone does not match front of history,
1583 ;; add it to the history.
1584 (or (equal command (car command-history))
1585 (setq command-history (cons command command-history)))
1586 (eval command)))
1588 (defun repeat-complex-command (arg)
1589 "Edit and re-evaluate last complex command, or ARGth from last.
1590 A complex command is one which used the minibuffer.
1591 The command is placed in the minibuffer as a Lisp form for editing.
1592 The result is executed, repeating the command as changed.
1593 If the command has been changed or is not the most recent previous
1594 command it is added to the front of the command history.
1595 You can use the minibuffer history commands \
1596 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1597 to get different commands to edit and resubmit."
1598 (interactive "p")
1599 (let ((elt (nth (1- arg) command-history))
1600 newcmd)
1601 (if elt
1602 (progn
1603 (setq newcmd
1604 (let ((print-level nil)
1605 (minibuffer-history-position arg)
1606 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1607 (unwind-protect
1608 (read-from-minibuffer
1609 "Redo: " (prin1-to-string elt) read-expression-map t
1610 (cons 'command-history arg))
1612 ;; If command was added to command-history as a
1613 ;; string, get rid of that. We want only
1614 ;; evaluable expressions there.
1615 (if (stringp (car command-history))
1616 (setq command-history (cdr command-history))))))
1618 ;; If command to be redone does not match front of history,
1619 ;; add it to the history.
1620 (or (equal newcmd (car command-history))
1621 (setq command-history (cons newcmd command-history)))
1622 (apply #'funcall-interactively
1623 (car newcmd)
1624 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1625 (if command-history
1626 (error "Argument %d is beyond length of command history" arg)
1627 (error "There are no previous complex commands to repeat")))))
1630 (defvar extended-command-history nil)
1631 (defvar execute-extended-command--last-typed nil)
1633 (defun read-extended-command ()
1634 "Read command name to invoke in `execute-extended-command'."
1635 (minibuffer-with-setup-hook
1636 (lambda ()
1637 (add-hook 'post-self-insert-hook
1638 (lambda ()
1639 (setq execute-extended-command--last-typed
1640 (minibuffer-contents)))
1641 nil 'local)
1642 (set (make-local-variable 'minibuffer-default-add-function)
1643 (lambda ()
1644 ;; Get a command name at point in the original buffer
1645 ;; to propose it after M-n.
1646 (with-current-buffer (window-buffer (minibuffer-selected-window))
1647 (and (commandp (function-called-at-point))
1648 (format "%S" (function-called-at-point)))))))
1649 ;; Read a string, completing from and restricting to the set of
1650 ;; all defined commands. Don't provide any initial input.
1651 ;; Save the command read on the extended-command history list.
1652 (completing-read
1653 (concat (cond
1654 ((eq current-prefix-arg '-) "- ")
1655 ((and (consp current-prefix-arg)
1656 (eq (car current-prefix-arg) 4)) "C-u ")
1657 ((and (consp current-prefix-arg)
1658 (integerp (car current-prefix-arg)))
1659 (format "%d " (car current-prefix-arg)))
1660 ((integerp current-prefix-arg)
1661 (format "%d " current-prefix-arg)))
1662 ;; This isn't strictly correct if `execute-extended-command'
1663 ;; is bound to anything else (e.g. [menu]).
1664 ;; It could use (key-description (this-single-command-keys)),
1665 ;; but actually a prompt other than "M-x" would be confusing,
1666 ;; because "M-x" is a well-known prompt to read a command
1667 ;; and it serves as a shorthand for "Extended command: ".
1668 "M-x ")
1669 (lambda (string pred action)
1670 (let ((pred
1671 (if (memq action '(nil t))
1672 ;; Exclude obsolete commands from completions.
1673 (lambda (sym)
1674 (and (funcall pred sym)
1675 (or (equal string (symbol-name sym))
1676 (not (get sym 'byte-obsolete-info)))))
1677 pred)))
1678 (complete-with-action action obarray string pred)))
1679 #'commandp t nil 'extended-command-history)))
1681 (defcustom suggest-key-bindings t
1682 "Non-nil means show the equivalent key-binding when M-x command has one.
1683 The value can be a length of time to show the message for.
1684 If the value is non-nil and not a number, we wait 2 seconds."
1685 :group 'keyboard
1686 :type '(choice (const :tag "off" nil)
1687 (integer :tag "time" 2)
1688 (other :tag "on")))
1690 (defcustom extended-command-suggest-shorter t
1691 "If non-nil, show a shorter M-x invocation when there is one."
1692 :group 'keyboard
1693 :type 'boolean
1694 :version "26.1")
1696 (defun execute-extended-command--shorter-1 (name length)
1697 (cond
1698 ((zerop length) (list ""))
1699 ((equal name "") nil)
1701 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1702 (execute-extended-command--shorter-1
1703 (substring name 1) (1- length)))
1704 (when (string-match "\\`\\(-\\)?[^-]*" name)
1705 (execute-extended-command--shorter-1
1706 (substring name (match-end 0)) length))))))
1708 (defun execute-extended-command--shorter (name typed)
1709 (let ((candidates '())
1710 (max (length typed))
1711 (len 1)
1712 binding)
1713 (while (and (not binding)
1714 (progn
1715 (unless candidates
1716 (setq len (1+ len))
1717 (setq candidates (execute-extended-command--shorter-1
1718 name len)))
1719 ;; Don't show the help message if the binding isn't
1720 ;; significantly shorter than the M-x command the user typed.
1721 (< len (- max 5))))
1722 (input-pending-p) ;Dummy call to trigger input-processing, bug#23002.
1723 (let ((candidate (pop candidates)))
1724 (when (equal name
1725 (car-safe (completion-try-completion
1726 candidate obarray 'commandp len)))
1727 (setq binding candidate))))
1728 binding))
1730 (defun execute-extended-command (prefixarg &optional command-name typed)
1731 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1732 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1733 "Read a command name, then read the arguments and call the command.
1734 To pass a prefix argument to the command you are
1735 invoking, give a prefix argument to `execute-extended-command'."
1736 (declare (interactive-only command-execute))
1737 ;; FIXME: Remember the actual text typed by the user before completion,
1738 ;; so that we don't later on suggest the same shortening.
1739 (interactive
1740 (let ((execute-extended-command--last-typed nil))
1741 (list current-prefix-arg
1742 (read-extended-command)
1743 execute-extended-command--last-typed)))
1744 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1745 (unless command-name
1746 (let ((current-prefix-arg prefixarg) ; for prompt
1747 (execute-extended-command--last-typed nil))
1748 (setq command-name (read-extended-command))
1749 (setq typed execute-extended-command--last-typed)))
1750 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1751 (binding (and suggest-key-bindings
1752 (not executing-kbd-macro)
1753 (where-is-internal function overriding-local-map t))))
1754 (unless (commandp function)
1755 (error "`%s' is not a valid command name" command-name))
1756 ;; Some features, such as novice.el, rely on this-command-keys
1757 ;; including M-x COMMAND-NAME RET.
1758 (set--this-command-keys (concat "\M-x" (symbol-name function) "\r"))
1759 (setq this-command function)
1760 ;; Normally `real-this-command' should never be changed, but here we really
1761 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1762 ;; binding" for <cmd>, so the command the user really wanted to run is
1763 ;; `function' and not `execute-extended-command'. The difference is
1764 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1765 (setq real-this-command function)
1766 (let ((prefix-arg prefixarg))
1767 (command-execute function 'record))
1768 ;; If enabled, show which key runs this command.
1769 ;; But first wait, and skip the message if there is input.
1770 (let* ((waited
1771 ;; If this command displayed something in the echo area;
1772 ;; wait a few seconds, then display our suggestion message.
1773 ;; FIXME: Wait *after* running post-command-hook!
1774 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1775 ;; find a better answer anyway!
1776 (when suggest-key-bindings
1777 (sit-for (cond
1778 ((zerop (length (current-message))) 0)
1779 ((numberp suggest-key-bindings) suggest-key-bindings)
1780 (t 2))))))
1781 (when (and waited (not (consp unread-command-events)))
1782 (unless (or (not extended-command-suggest-shorter)
1783 binding executing-kbd-macro (not (symbolp function))
1784 (<= (length (symbol-name function)) 2))
1785 ;; There's no binding for CMD. Let's try and find the shortest
1786 ;; string to use in M-x.
1787 ;; FIXME: Can be slow. Cache it maybe?
1788 (while-no-input
1789 (setq binding (execute-extended-command--shorter
1790 (symbol-name function) typed))))
1791 (when binding
1792 (with-temp-message
1793 (format-message "You can run the command `%s' with %s"
1794 function
1795 (if (stringp binding)
1796 (concat "M-x " binding " RET")
1797 (key-description binding)))
1798 (sit-for (if (numberp suggest-key-bindings)
1799 suggest-key-bindings
1800 2))))))))
1802 (defun command-execute (cmd &optional record-flag keys special)
1803 ;; BEWARE: Called directly from the C code.
1804 "Execute CMD as an editor command.
1805 CMD must be a symbol that satisfies the `commandp' predicate.
1806 Optional second arg RECORD-FLAG non-nil
1807 means unconditionally put this command in the variable `command-history'.
1808 Otherwise, that is done only if an arg is read using the minibuffer.
1809 The argument KEYS specifies the value to use instead of (this-command-keys)
1810 when reading the arguments; if it is nil, (this-command-keys) is used.
1811 The argument SPECIAL, if non-nil, means that this command is executing
1812 a special event, so ignore the prefix argument and don't clear it."
1813 (setq debug-on-next-call nil)
1814 (let ((prefixarg (unless special
1815 ;; FIXME: This should probably be done around
1816 ;; pre-command-hook rather than here!
1817 (prog1 prefix-arg
1818 (setq current-prefix-arg prefix-arg)
1819 (setq prefix-arg nil)
1820 (when current-prefix-arg
1821 (prefix-command-update))))))
1822 (if (and (symbolp cmd)
1823 (get cmd 'disabled)
1824 disabled-command-function)
1825 ;; FIXME: Weird calling convention!
1826 (run-hooks 'disabled-command-function)
1827 (let ((final cmd))
1828 (while
1829 (progn
1830 (setq final (indirect-function final))
1831 (if (autoloadp final)
1832 (setq final (autoload-do-load final cmd)))))
1833 (cond
1834 ((arrayp final)
1835 ;; If requested, place the macro in the command history. For
1836 ;; other sorts of commands, call-interactively takes care of this.
1837 (when record-flag
1838 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1839 ;; Don't keep command history around forever.
1840 (when (and (numberp history-length) (> history-length 0))
1841 (let ((cell (nthcdr history-length command-history)))
1842 (if (consp cell) (setcdr cell nil)))))
1843 (execute-kbd-macro final prefixarg))
1845 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1846 (prog1 (call-interactively cmd record-flag keys)
1847 (when (and (symbolp cmd)
1848 (get cmd 'byte-obsolete-info)
1849 (not (get cmd 'command-execute-obsolete-warned)))
1850 (put cmd 'command-execute-obsolete-warned t)
1851 (message "%s" (macroexp--obsolete-warning
1852 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1854 (defvar minibuffer-history nil
1855 "Default minibuffer history list.
1856 This is used for all minibuffer input
1857 except when an alternate history list is specified.
1859 Maximum length of the history list is determined by the value
1860 of `history-length', which see.")
1861 (defvar minibuffer-history-sexp-flag nil
1862 "Control whether history list elements are expressions or strings.
1863 If the value of this variable equals current minibuffer depth,
1864 they are expressions; otherwise they are strings.
1865 \(That convention is designed to do the right thing for
1866 recursive uses of the minibuffer.)")
1867 (setq minibuffer-history-variable 'minibuffer-history)
1868 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1869 (defvar minibuffer-history-search-history nil)
1871 (defvar minibuffer-text-before-history nil
1872 "Text that was in this minibuffer before any history commands.
1873 This is nil if there have not yet been any history commands
1874 in this use of the minibuffer.")
1876 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1878 (defun minibuffer-history-initialize ()
1879 (setq minibuffer-text-before-history nil))
1881 (defun minibuffer-avoid-prompt (_new _old)
1882 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1883 (declare (obsolete cursor-intangible-mode "25.1"))
1884 (constrain-to-field nil (point-max)))
1886 (defcustom minibuffer-history-case-insensitive-variables nil
1887 "Minibuffer history variables for which matching should ignore case.
1888 If a history variable is a member of this list, then the
1889 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1890 commands ignore case when searching it, regardless of `case-fold-search'."
1891 :type '(repeat variable)
1892 :group 'minibuffer)
1894 (defun previous-matching-history-element (regexp n)
1895 "Find the previous history element that matches REGEXP.
1896 \(Previous history elements refer to earlier actions.)
1897 With prefix argument N, search for Nth previous match.
1898 If N is negative, find the next or Nth next match.
1899 Normally, history elements are matched case-insensitively if
1900 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1901 makes the search case-sensitive.
1902 See also `minibuffer-history-case-insensitive-variables'."
1903 (interactive
1904 (let* ((enable-recursive-minibuffers t)
1905 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1907 minibuffer-local-map
1909 'minibuffer-history-search-history
1910 (car minibuffer-history-search-history))))
1911 ;; Use the last regexp specified, by default, if input is empty.
1912 (list (if (string= regexp "")
1913 (if minibuffer-history-search-history
1914 (car minibuffer-history-search-history)
1915 (user-error "No previous history search regexp"))
1916 regexp)
1917 (prefix-numeric-value current-prefix-arg))))
1918 (unless (zerop n)
1919 (if (and (zerop minibuffer-history-position)
1920 (null minibuffer-text-before-history))
1921 (setq minibuffer-text-before-history
1922 (minibuffer-contents-no-properties)))
1923 (let ((history (symbol-value minibuffer-history-variable))
1924 (case-fold-search
1925 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1926 ;; On some systems, ignore case for file names.
1927 (if (memq minibuffer-history-variable
1928 minibuffer-history-case-insensitive-variables)
1930 ;; Respect the user's setting for case-fold-search:
1931 case-fold-search)
1932 nil))
1933 prevpos
1934 match-string
1935 match-offset
1936 (pos minibuffer-history-position))
1937 (while (/= n 0)
1938 (setq prevpos pos)
1939 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1940 (when (= pos prevpos)
1941 (user-error (if (= pos 1)
1942 "No later matching history item"
1943 "No earlier matching history item")))
1944 (setq match-string
1945 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1946 (let ((print-level nil))
1947 (prin1-to-string (nth (1- pos) history)))
1948 (nth (1- pos) history)))
1949 (setq match-offset
1950 (if (< n 0)
1951 (and (string-match regexp match-string)
1952 (match-end 0))
1953 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1954 (match-beginning 1))))
1955 (when match-offset
1956 (setq n (+ n (if (< n 0) 1 -1)))))
1957 (setq minibuffer-history-position pos)
1958 (goto-char (point-max))
1959 (delete-minibuffer-contents)
1960 (insert match-string)
1961 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1962 (if (memq (car (car command-history)) '(previous-matching-history-element
1963 next-matching-history-element))
1964 (setq command-history (cdr command-history))))
1966 (defun next-matching-history-element (regexp n)
1967 "Find the next history element that matches REGEXP.
1968 \(The next history element refers to a more recent action.)
1969 With prefix argument N, search for Nth next match.
1970 If N is negative, find the previous or Nth previous match.
1971 Normally, history elements are matched case-insensitively if
1972 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1973 makes the search case-sensitive."
1974 (interactive
1975 (let* ((enable-recursive-minibuffers t)
1976 (regexp (read-from-minibuffer "Next element matching (regexp): "
1978 minibuffer-local-map
1980 'minibuffer-history-search-history
1981 (car minibuffer-history-search-history))))
1982 ;; Use the last regexp specified, by default, if input is empty.
1983 (list (if (string= regexp "")
1984 (if minibuffer-history-search-history
1985 (car minibuffer-history-search-history)
1986 (user-error "No previous history search regexp"))
1987 regexp)
1988 (prefix-numeric-value current-prefix-arg))))
1989 (previous-matching-history-element regexp (- n)))
1991 (defvar minibuffer-temporary-goal-position nil)
1993 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1994 "Function run by `goto-history-element' before consuming default values.
1995 This is useful to dynamically add more elements to the list of default values
1996 when `goto-history-element' reaches the end of this list.
1997 Before calling this function `goto-history-element' sets the variable
1998 `minibuffer-default-add-done' to t, so it will call this function only
1999 once. In special cases, when this function needs to be called more
2000 than once, it can set `minibuffer-default-add-done' to nil explicitly,
2001 overriding the setting of this variable to t in `goto-history-element'.")
2003 (defvar minibuffer-default-add-done nil
2004 "When nil, add more elements to the end of the list of default values.
2005 The value nil causes `goto-history-element' to add more elements to
2006 the list of defaults when it reaches the end of this list. It does
2007 this by calling a function defined by `minibuffer-default-add-function'.")
2009 (make-variable-buffer-local 'minibuffer-default-add-done)
2011 (defun minibuffer-default-add-completions ()
2012 "Return a list of all completions without the default value.
2013 This function is used to add all elements of the completion table to
2014 the end of the list of defaults just after the default value."
2015 (let ((def minibuffer-default)
2016 (all (all-completions ""
2017 minibuffer-completion-table
2018 minibuffer-completion-predicate)))
2019 (if (listp def)
2020 (append def all)
2021 (cons def (delete def all)))))
2023 (defun goto-history-element (nabs)
2024 "Puts element of the minibuffer history in the minibuffer.
2025 The argument NABS specifies the absolute history position."
2026 (interactive "p")
2027 (when (and (not minibuffer-default-add-done)
2028 (functionp minibuffer-default-add-function)
2029 (< nabs (- (if (listp minibuffer-default)
2030 (length minibuffer-default)
2031 1))))
2032 (setq minibuffer-default-add-done t
2033 minibuffer-default (funcall minibuffer-default-add-function)))
2034 (let ((minimum (if minibuffer-default
2035 (- (if (listp minibuffer-default)
2036 (length minibuffer-default)
2039 elt minibuffer-returned-to-present)
2040 (if (and (zerop minibuffer-history-position)
2041 (null minibuffer-text-before-history))
2042 (setq minibuffer-text-before-history
2043 (minibuffer-contents-no-properties)))
2044 (if (< nabs minimum)
2045 (user-error (if minibuffer-default
2046 "End of defaults; no next item"
2047 "End of history; no default available")))
2048 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
2049 (length (symbol-value minibuffer-history-variable))
2051 (user-error "Beginning of history; no preceding item"))
2052 (unless (memq last-command '(next-history-element
2053 previous-history-element))
2054 (let ((prompt-end (minibuffer-prompt-end)))
2055 (set (make-local-variable 'minibuffer-temporary-goal-position)
2056 (cond ((<= (point) prompt-end) prompt-end)
2057 ((eobp) nil)
2058 (t (point))))))
2059 (goto-char (point-max))
2060 (delete-minibuffer-contents)
2061 (setq minibuffer-history-position nabs)
2062 (cond ((< nabs 0)
2063 (setq elt (if (listp minibuffer-default)
2064 (nth (1- (abs nabs)) minibuffer-default)
2065 minibuffer-default)))
2066 ((= nabs 0)
2067 (setq elt (or minibuffer-text-before-history ""))
2068 (setq minibuffer-returned-to-present t)
2069 (setq minibuffer-text-before-history nil))
2070 (t (setq elt (nth (1- minibuffer-history-position)
2071 (symbol-value minibuffer-history-variable)))))
2072 (insert
2073 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2074 (not minibuffer-returned-to-present))
2075 (let ((print-level nil))
2076 (prin1-to-string elt))
2077 elt))
2078 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2080 (defun next-history-element (n)
2081 "Puts next element of the minibuffer history in the minibuffer.
2082 With argument N, it uses the Nth following element."
2083 (interactive "p")
2084 (or (zerop n)
2085 (goto-history-element (- minibuffer-history-position n))))
2087 (defun previous-history-element (n)
2088 "Puts previous element of the minibuffer history in the minibuffer.
2089 With argument N, it uses the Nth previous element."
2090 (interactive "p")
2091 (or (zerop n)
2092 (goto-history-element (+ minibuffer-history-position n))))
2094 (defun next-line-or-history-element (&optional arg)
2095 "Move cursor vertically down ARG lines, or to the next history element.
2096 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2097 next element of the minibuffer history in the minibuffer."
2098 (interactive "^p")
2099 (or arg (setq arg 1))
2100 (let* ((old-point (point))
2101 ;; Remember the original goal column of possibly multi-line input
2102 ;; excluding the length of the prompt on the first line.
2103 (prompt-end (minibuffer-prompt-end))
2104 (old-column (unless (and (eolp) (> (point) prompt-end))
2105 (if (= (line-number-at-pos) 1)
2106 (max (- (current-column) (1- prompt-end)) 0)
2107 (current-column)))))
2108 (condition-case nil
2109 (with-no-warnings
2110 (next-line arg))
2111 (end-of-buffer
2112 ;; Restore old position since `line-move-visual' moves point to
2113 ;; the end of the line when it fails to go to the next line.
2114 (goto-char old-point)
2115 (next-history-element arg)
2116 ;; Reset `temporary-goal-column' because a correct value is not
2117 ;; calculated when `next-line' above fails by bumping against
2118 ;; the bottom of the minibuffer (bug#22544).
2119 (setq temporary-goal-column 0)
2120 ;; Restore the original goal column on the last line
2121 ;; of possibly multi-line input.
2122 (goto-char (point-max))
2123 (when old-column
2124 (if (= (line-number-at-pos) 1)
2125 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2126 (move-to-column old-column)))))))
2128 (defun previous-line-or-history-element (&optional arg)
2129 "Move cursor vertically up ARG lines, or to the previous history element.
2130 When point moves over the top line of multi-line minibuffer, puts ARGth
2131 previous element of the minibuffer history in the minibuffer."
2132 (interactive "^p")
2133 (or arg (setq arg 1))
2134 (let* ((old-point (point))
2135 ;; Remember the original goal column of possibly multi-line input
2136 ;; excluding the length of the prompt on the first line.
2137 (prompt-end (minibuffer-prompt-end))
2138 (old-column (unless (and (eolp) (> (point) prompt-end))
2139 (if (= (line-number-at-pos) 1)
2140 (max (- (current-column) (1- prompt-end)) 0)
2141 (current-column)))))
2142 (condition-case nil
2143 (with-no-warnings
2144 (previous-line arg))
2145 (beginning-of-buffer
2146 ;; Restore old position since `line-move-visual' moves point to
2147 ;; the beginning of the line when it fails to go to the previous line.
2148 (goto-char old-point)
2149 (previous-history-element arg)
2150 ;; Reset `temporary-goal-column' because a correct value is not
2151 ;; calculated when `previous-line' above fails by bumping against
2152 ;; the top of the minibuffer (bug#22544).
2153 (setq temporary-goal-column 0)
2154 ;; Restore the original goal column on the first line
2155 ;; of possibly multi-line input.
2156 (goto-char (minibuffer-prompt-end))
2157 (if old-column
2158 (if (= (line-number-at-pos) 1)
2159 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2160 (move-to-column old-column))
2161 ;; Put the cursor at the end of the visual line instead of the
2162 ;; logical line, so the next `previous-line-or-history-element'
2163 ;; would move to the previous history element, not to a possible upper
2164 ;; visual line from the end of logical line in `line-move-visual' mode.
2165 (end-of-visual-line)
2166 ;; Since `end-of-visual-line' puts the cursor at the beginning
2167 ;; of the next visual line, move it one char back to the end
2168 ;; of the first visual line (bug#22544).
2169 (unless (eolp) (backward-char 1)))))))
2171 (defun next-complete-history-element (n)
2172 "Get next history element which completes the minibuffer before the point.
2173 The contents of the minibuffer after the point are deleted, and replaced
2174 by the new completion."
2175 (interactive "p")
2176 (let ((point-at-start (point)))
2177 (next-matching-history-element
2178 (concat
2179 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2181 ;; next-matching-history-element always puts us at (point-min).
2182 ;; Move to the position we were at before changing the buffer contents.
2183 ;; This is still sensible, because the text before point has not changed.
2184 (goto-char point-at-start)))
2186 (defun previous-complete-history-element (n)
2188 Get previous history element which completes the minibuffer before the point.
2189 The contents of the minibuffer after the point are deleted, and replaced
2190 by the new completion."
2191 (interactive "p")
2192 (next-complete-history-element (- n)))
2194 ;; For compatibility with the old subr of the same name.
2195 (defun minibuffer-prompt-width ()
2196 "Return the display width of the minibuffer prompt.
2197 Return 0 if current buffer is not a minibuffer."
2198 ;; Return the width of everything before the field at the end of
2199 ;; the buffer; this should be 0 for normal buffers.
2200 (1- (minibuffer-prompt-end)))
2202 ;; isearch minibuffer history
2203 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2205 (defvar minibuffer-history-isearch-message-overlay)
2206 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2208 (defun minibuffer-history-isearch-setup ()
2209 "Set up a minibuffer for using isearch to search the minibuffer history.
2210 Intended to be added to `minibuffer-setup-hook'."
2211 (set (make-local-variable 'isearch-search-fun-function)
2212 'minibuffer-history-isearch-search)
2213 (set (make-local-variable 'isearch-message-function)
2214 'minibuffer-history-isearch-message)
2215 (set (make-local-variable 'isearch-wrap-function)
2216 'minibuffer-history-isearch-wrap)
2217 (set (make-local-variable 'isearch-push-state-function)
2218 'minibuffer-history-isearch-push-state)
2219 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2221 (defun minibuffer-history-isearch-end ()
2222 "Clean up the minibuffer after terminating isearch in the minibuffer."
2223 (if minibuffer-history-isearch-message-overlay
2224 (delete-overlay minibuffer-history-isearch-message-overlay)))
2226 (defun minibuffer-history-isearch-search ()
2227 "Return the proper search function, for isearch in minibuffer history."
2228 (lambda (string bound noerror)
2229 (let ((search-fun
2230 ;; Use standard functions to search within minibuffer text
2231 (isearch-search-fun-default))
2232 found)
2233 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2234 ;; searching forward. Lazy-highlight calls this lambda with the
2235 ;; bound arg, so skip the minibuffer prompt.
2236 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2237 (goto-char (minibuffer-prompt-end)))
2239 ;; 1. First try searching in the initial minibuffer text
2240 (funcall search-fun string
2241 (if isearch-forward bound (minibuffer-prompt-end))
2242 noerror)
2243 ;; 2. If the above search fails, start putting next/prev history
2244 ;; elements in the minibuffer successively, and search the string
2245 ;; in them. Do this only when bound is nil (i.e. not while
2246 ;; lazy-highlighting search strings in the current minibuffer text).
2247 (unless bound
2248 (condition-case nil
2249 (progn
2250 (while (not found)
2251 (cond (isearch-forward
2252 (next-history-element 1)
2253 (goto-char (minibuffer-prompt-end)))
2255 (previous-history-element 1)
2256 (goto-char (point-max))))
2257 (setq isearch-barrier (point) isearch-opoint (point))
2258 ;; After putting the next/prev history element, search
2259 ;; the string in them again, until next-history-element
2260 ;; or previous-history-element raises an error at the
2261 ;; beginning/end of history.
2262 (setq found (funcall search-fun string
2263 (unless isearch-forward
2264 ;; For backward search, don't search
2265 ;; in the minibuffer prompt
2266 (minibuffer-prompt-end))
2267 noerror)))
2268 ;; Return point of the new search result
2269 (point))
2270 ;; Return nil when next(prev)-history-element fails
2271 (error nil)))))))
2273 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2274 "Display the minibuffer history search prompt.
2275 If there are no search errors, this function displays an overlay with
2276 the isearch prompt which replaces the original minibuffer prompt.
2277 Otherwise, it displays the standard isearch message returned from
2278 the function `isearch-message'."
2279 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2280 ;; Use standard function `isearch-message' when not in the minibuffer,
2281 ;; or search fails, or has an error (like incomplete regexp).
2282 ;; This function overwrites minibuffer text with isearch message,
2283 ;; so it's possible to see what is wrong in the search string.
2284 (isearch-message c-q-hack ellipsis)
2285 ;; Otherwise, put the overlay with the standard isearch prompt over
2286 ;; the initial minibuffer prompt.
2287 (if (overlayp minibuffer-history-isearch-message-overlay)
2288 (move-overlay minibuffer-history-isearch-message-overlay
2289 (point-min) (minibuffer-prompt-end))
2290 (setq minibuffer-history-isearch-message-overlay
2291 (make-overlay (point-min) (minibuffer-prompt-end)))
2292 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2293 (overlay-put minibuffer-history-isearch-message-overlay
2294 'display (isearch-message-prefix c-q-hack ellipsis))
2295 ;; And clear any previous isearch message.
2296 (message "")))
2298 (defun minibuffer-history-isearch-wrap ()
2299 "Wrap the minibuffer history search when search fails.
2300 Move point to the first history element for a forward search,
2301 or to the last history element for a backward search."
2302 ;; When `minibuffer-history-isearch-search' fails on reaching the
2303 ;; beginning/end of the history, wrap the search to the first/last
2304 ;; minibuffer history element.
2305 (if isearch-forward
2306 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2307 (goto-history-element 0))
2308 (setq isearch-success t)
2309 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2311 (defun minibuffer-history-isearch-push-state ()
2312 "Save a function restoring the state of minibuffer history search.
2313 Save `minibuffer-history-position' to the additional state parameter
2314 in the search status stack."
2315 (let ((pos minibuffer-history-position))
2316 (lambda (cmd)
2317 (minibuffer-history-isearch-pop-state cmd pos))))
2319 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2320 "Restore the minibuffer history search state.
2321 Go to the history element by the absolute history position HIST-POS."
2322 (goto-history-element hist-pos))
2325 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2326 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2328 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2329 "Table mapping redo records to the corresponding undo one.
2330 A redo record for undo-in-region maps to t.
2331 A redo record for ordinary undo maps to the following (earlier) undo.")
2333 (defvar undo-in-region nil
2334 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2336 (defvar undo-no-redo nil
2337 "If t, `undo' doesn't go through redo entries.")
2339 (defvar pending-undo-list nil
2340 "Within a run of consecutive undo commands, list remaining to be undone.
2341 If t, we undid all the way to the end of it.")
2343 (defun undo (&optional arg)
2344 "Undo some previous changes.
2345 Repeat this command to undo more changes.
2346 A numeric ARG serves as a repeat count.
2348 In Transient Mark mode when the mark is active, only undo changes within
2349 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2350 as an argument limits undo to changes within the current region."
2351 (interactive "*P")
2352 ;; Make last-command indicate for the next command that this was an undo.
2353 ;; That way, another undo will undo more.
2354 ;; If we get to the end of the undo history and get an error,
2355 ;; another undo command will find the undo history empty
2356 ;; and will get another error. To begin undoing the undos,
2357 ;; you must type some other command.
2358 (let* ((modified (buffer-modified-p))
2359 ;; For an indirect buffer, look in the base buffer for the
2360 ;; auto-save data.
2361 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2362 (recent-save (with-current-buffer base-buffer
2363 (recent-auto-save-p)))
2364 message)
2365 ;; If we get an error in undo-start,
2366 ;; the next command should not be a "consecutive undo".
2367 ;; So set `this-command' to something other than `undo'.
2368 (setq this-command 'undo-start)
2370 (unless (and (eq last-command 'undo)
2371 (or (eq pending-undo-list t)
2372 ;; If something (a timer or filter?) changed the buffer
2373 ;; since the previous command, don't continue the undo seq.
2374 (let ((list buffer-undo-list))
2375 (while (eq (car list) nil)
2376 (setq list (cdr list)))
2377 ;; If the last undo record made was made by undo
2378 ;; it shows nothing else happened in between.
2379 (gethash list undo-equiv-table))))
2380 (setq undo-in-region
2381 (or (region-active-p) (and arg (not (numberp arg)))))
2382 (if undo-in-region
2383 (undo-start (region-beginning) (region-end))
2384 (undo-start))
2385 ;; get rid of initial undo boundary
2386 (undo-more 1))
2387 ;; If we got this far, the next command should be a consecutive undo.
2388 (setq this-command 'undo)
2389 ;; Check to see whether we're hitting a redo record, and if
2390 ;; so, ask the user whether she wants to skip the redo/undo pair.
2391 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2392 (or (eq (selected-window) (minibuffer-window))
2393 (setq message (format "%s%s!"
2394 (if (or undo-no-redo (not equiv))
2395 "Undo" "Redo")
2396 (if undo-in-region " in region" ""))))
2397 (when (and (consp equiv) undo-no-redo)
2398 ;; The equiv entry might point to another redo record if we have done
2399 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2400 (while (let ((next (gethash equiv undo-equiv-table)))
2401 (if next (setq equiv next))))
2402 (setq pending-undo-list equiv)))
2403 (undo-more
2404 (if (numberp arg)
2405 (prefix-numeric-value arg)
2407 ;; Record the fact that the just-generated undo records come from an
2408 ;; undo operation--that is, they are redo records.
2409 ;; In the ordinary case (not within a region), map the redo
2410 ;; record to the following undos.
2411 ;; I don't know how to do that in the undo-in-region case.
2412 (let ((list buffer-undo-list))
2413 ;; Strip any leading undo boundaries there might be, like we do
2414 ;; above when checking.
2415 (while (eq (car list) nil)
2416 (setq list (cdr list)))
2417 (puthash list
2418 ;; Prevent identity mapping. This can happen if
2419 ;; consecutive nils are erroneously in undo list.
2420 (if (or undo-in-region (eq list pending-undo-list))
2422 pending-undo-list)
2423 undo-equiv-table))
2424 ;; Don't specify a position in the undo record for the undo command.
2425 ;; Instead, undoing this should move point to where the change is.
2426 (let ((tail buffer-undo-list)
2427 (prev nil))
2428 (while (car tail)
2429 (when (integerp (car tail))
2430 (let ((pos (car tail)))
2431 (if prev
2432 (setcdr prev (cdr tail))
2433 (setq buffer-undo-list (cdr tail)))
2434 (setq tail (cdr tail))
2435 (while (car tail)
2436 (if (eq pos (car tail))
2437 (if prev
2438 (setcdr prev (cdr tail))
2439 (setq buffer-undo-list (cdr tail)))
2440 (setq prev tail))
2441 (setq tail (cdr tail)))
2442 (setq tail nil)))
2443 (setq prev tail tail (cdr tail))))
2444 ;; Record what the current undo list says,
2445 ;; so the next command can tell if the buffer was modified in between.
2446 (and modified (not (buffer-modified-p))
2447 (with-current-buffer base-buffer
2448 (delete-auto-save-file-if-necessary recent-save)))
2449 ;; Display a message announcing success.
2450 (if message
2451 (message "%s" message))))
2453 (defun buffer-disable-undo (&optional buffer)
2454 "Make BUFFER stop keeping undo information.
2455 No argument or nil as argument means do this for the current buffer."
2456 (interactive)
2457 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2458 (setq buffer-undo-list t)))
2460 (defun undo-only (&optional arg)
2461 "Undo some previous changes.
2462 Repeat this command to undo more changes.
2463 A numeric ARG serves as a repeat count.
2464 Contrary to `undo', this will not redo a previous undo."
2465 (interactive "*p")
2466 (let ((undo-no-redo t)) (undo arg)))
2468 (defvar undo-in-progress nil
2469 "Non-nil while performing an undo.
2470 Some change-hooks test this variable to do something different.")
2472 (defun undo-more (n)
2473 "Undo back N undo-boundaries beyond what was already undone recently.
2474 Call `undo-start' to get ready to undo recent changes,
2475 then call `undo-more' one or more times to undo them."
2476 (or (listp pending-undo-list)
2477 (user-error (concat "No further undo information"
2478 (and undo-in-region " for region"))))
2479 (let ((undo-in-progress t))
2480 ;; Note: The following, while pulling elements off
2481 ;; `pending-undo-list' will call primitive change functions which
2482 ;; will push more elements onto `buffer-undo-list'.
2483 (setq pending-undo-list (primitive-undo n pending-undo-list))
2484 (if (null pending-undo-list)
2485 (setq pending-undo-list t))))
2487 (defun primitive-undo (n list)
2488 "Undo N records from the front of the list LIST.
2489 Return what remains of the list."
2491 ;; This is a good feature, but would make undo-start
2492 ;; unable to do what is expected.
2493 ;;(when (null (car (list)))
2494 ;; ;; If the head of the list is a boundary, it is the boundary
2495 ;; ;; preceding this command. Get rid of it and don't count it.
2496 ;; (setq list (cdr list))))
2498 (let ((arg n)
2499 ;; In a writable buffer, enable undoing read-only text that is
2500 ;; so because of text properties.
2501 (inhibit-read-only t)
2502 ;; Don't let `intangible' properties interfere with undo.
2503 (inhibit-point-motion-hooks t)
2504 ;; We use oldlist only to check for EQ. ++kfs
2505 (oldlist buffer-undo-list)
2506 (did-apply nil)
2507 (next nil))
2508 (while (> arg 0)
2509 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2510 ;; Handle an integer by setting point to that value.
2511 (pcase next
2512 ((pred integerp) (goto-char next))
2513 ;; Element (t . TIME) records previous modtime.
2514 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2515 ;; UNKNOWN_MODTIME_NSECS.
2516 (`(t . ,time)
2517 ;; If this records an obsolete save
2518 ;; (not matching the actual disk file)
2519 ;; then don't mark unmodified.
2520 (when (or (equal time (visited-file-modtime))
2521 (and (consp time)
2522 (equal (list (car time) (cdr time))
2523 (visited-file-modtime))))
2524 (when (fboundp 'unlock-buffer)
2525 (unlock-buffer))
2526 (set-buffer-modified-p nil)))
2527 ;; Element (nil PROP VAL BEG . END) is property change.
2528 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2529 (when (or (> (point-min) beg) (< (point-max) end))
2530 (error "Changes to be undone are outside visible portion of buffer"))
2531 (put-text-property beg end prop val))
2532 ;; Element (BEG . END) means range was inserted.
2533 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2534 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2535 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2536 (when (or (> (point-min) beg) (< (point-max) end))
2537 (error "Changes to be undone are outside visible portion of buffer"))
2538 ;; Set point first thing, so that undoing this undo
2539 ;; does not send point back to where it is now.
2540 (goto-char beg)
2541 (delete-region beg end))
2542 ;; Element (apply FUN . ARGS) means call FUN to undo.
2543 (`(apply . ,fun-args)
2544 (let ((currbuff (current-buffer)))
2545 (if (integerp (car fun-args))
2546 ;; Long format: (apply DELTA START END FUN . ARGS).
2547 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2548 (start-mark (copy-marker start nil))
2549 (end-mark (copy-marker end t)))
2550 (when (or (> (point-min) start) (< (point-max) end))
2551 (error "Changes to be undone are outside visible portion of buffer"))
2552 (apply fun args) ;; Use `save-current-buffer'?
2553 ;; Check that the function did what the entry
2554 ;; said it would do.
2555 (unless (and (= start start-mark)
2556 (= (+ delta end) end-mark))
2557 (error "Changes to be undone by function different than announced"))
2558 (set-marker start-mark nil)
2559 (set-marker end-mark nil))
2560 (apply fun-args))
2561 (unless (eq currbuff (current-buffer))
2562 (error "Undo function switched buffer"))
2563 (setq did-apply t)))
2564 ;; Element (STRING . POS) means STRING was deleted.
2565 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2566 (when (let ((apos (abs pos)))
2567 (or (< apos (point-min)) (> apos (point-max))))
2568 (error "Changes to be undone are outside visible portion of buffer"))
2569 (let (valid-marker-adjustments)
2570 ;; Check that marker adjustments which were recorded
2571 ;; with the (STRING . POS) record are still valid, ie
2572 ;; the markers haven't moved. We check their validity
2573 ;; before reinserting the string so as we don't need to
2574 ;; mind marker insertion-type.
2575 (while (and (markerp (car-safe (car list)))
2576 (integerp (cdr-safe (car list))))
2577 (let* ((marker-adj (pop list))
2578 (m (car marker-adj)))
2579 (and (eq (marker-buffer m) (current-buffer))
2580 (= pos m)
2581 (push marker-adj valid-marker-adjustments))))
2582 ;; Insert string and adjust point
2583 (if (< pos 0)
2584 (progn
2585 (goto-char (- pos))
2586 (insert string))
2587 (goto-char pos)
2588 (insert string)
2589 (goto-char pos))
2590 ;; Adjust the valid marker adjustments
2591 (dolist (adj valid-marker-adjustments)
2592 (set-marker (car adj)
2593 (- (car adj) (cdr adj))))))
2594 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2595 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2596 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2597 next)
2598 ;; Even though these elements are not expected in the undo
2599 ;; list, adjust them to be conservative for the 24.4
2600 ;; release. (Bug#16818)
2601 (when (marker-buffer marker)
2602 (set-marker marker
2603 (- marker offset)
2604 (marker-buffer marker))))
2605 (_ (error "Unrecognized entry in undo list %S" next))))
2606 (setq arg (1- arg)))
2607 ;; Make sure an apply entry produces at least one undo entry,
2608 ;; so the test in `undo' for continuing an undo series
2609 ;; will work right.
2610 (if (and did-apply
2611 (eq oldlist buffer-undo-list))
2612 (setq buffer-undo-list
2613 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2614 list)
2616 ;; Deep copy of a list
2617 (defun undo-copy-list (list)
2618 "Make a copy of undo list LIST."
2619 (mapcar 'undo-copy-list-1 list))
2621 (defun undo-copy-list-1 (elt)
2622 (if (consp elt)
2623 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2624 elt))
2626 (defun undo-start (&optional beg end)
2627 "Set `pending-undo-list' to the front of the undo list.
2628 The next call to `undo-more' will undo the most recently made change.
2629 If BEG and END are specified, then only undo elements
2630 that apply to text between BEG and END are used; other undo elements
2631 are ignored. If BEG and END are nil, all undo elements are used."
2632 (if (eq buffer-undo-list t)
2633 (user-error "No undo information in this buffer"))
2634 (setq pending-undo-list
2635 (if (and beg end (not (= beg end)))
2636 (undo-make-selective-list (min beg end) (max beg end))
2637 buffer-undo-list)))
2639 ;; The positions given in elements of the undo list are the positions
2640 ;; as of the time that element was recorded to undo history. In
2641 ;; general, subsequent buffer edits render those positions invalid in
2642 ;; the current buffer, unless adjusted according to the intervening
2643 ;; undo elements.
2645 ;; Undo in region is a use case that requires adjustments to undo
2646 ;; elements. It must adjust positions of elements in the region based
2647 ;; on newer elements not in the region so as they may be correctly
2648 ;; applied in the current buffer. undo-make-selective-list
2649 ;; accomplishes this with its undo-deltas list of adjustments. An
2650 ;; example undo history from oldest to newest:
2652 ;; buf pos:
2653 ;; 123456789 buffer-undo-list undo-deltas
2654 ;; --------- ---------------- -----------
2655 ;; aaa (1 . 4) (1 . -3)
2656 ;; aaba (3 . 4) N/A (in region)
2657 ;; ccaaba (1 . 3) (1 . -2)
2658 ;; ccaabaddd (7 . 10) (7 . -3)
2659 ;; ccaabdd ("ad" . 6) (6 . 2)
2660 ;; ccaabaddd (6 . 8) (6 . -2)
2661 ;; | |<-- region: "caab", from 2 to 6
2663 ;; When the user starts a run of undos in region,
2664 ;; undo-make-selective-list is called to create the full list of in
2665 ;; region elements. Each element is adjusted forward chronologically
2666 ;; through undo-deltas to determine if it is in the region.
2668 ;; In the above example, the insertion of "b" is (3 . 4) in the
2669 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2670 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2671 ;; . 6) is assessed as in the region and placed in the selective list.
2672 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2673 ;; due to the selected element. The "b" insertion is the only element
2674 ;; fully in the region, so in this example undo-make-selective-list
2675 ;; returns (nil (5 . 6)).
2677 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2678 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2679 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2680 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2681 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2683 ;; More interesting is how to adjust the "ddd" insertion due to the
2684 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2685 ;; If the reinsertion was a manual retyping of "ad", then the total
2686 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2687 ;; the reinsertion was due to undo, one might expect the first "d"
2688 ;; character would again be a part of the "ddd" text, meaning its
2689 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2691 ;; undo-make-selective-list assumes in this situation that "ad" was a
2692 ;; new edit, even if it was inserted because of an undo.
2693 ;; Consequently, if the user undos in region "8 to 10" of the
2694 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2695 ;; "ccaabad", as though the first "d" became detached from the
2696 ;; original "ddd" insertion. This quirk is a FIXME.
2698 (defun undo-make-selective-list (start end)
2699 "Return a list of undo elements for the region START to END.
2700 The elements come from `buffer-undo-list', but we keep only the
2701 elements inside this region, and discard those outside this
2702 region. The elements' positions are adjusted so as the returned
2703 list can be applied to the current buffer."
2704 (let ((ulist buffer-undo-list)
2705 ;; A list of position adjusted undo elements in the region.
2706 (selective-list (list nil))
2707 ;; A list of undo-deltas for out of region undo elements.
2708 undo-deltas
2709 undo-elt)
2710 (while ulist
2711 (when undo-no-redo
2712 (while (gethash ulist undo-equiv-table)
2713 (setq ulist (gethash ulist undo-equiv-table))))
2714 (setq undo-elt (car ulist))
2715 (cond
2716 ((null undo-elt)
2717 ;; Don't put two nils together in the list
2718 (when (car selective-list)
2719 (push nil selective-list)))
2720 ((and (consp undo-elt) (eq (car undo-elt) t))
2721 ;; This is a "was unmodified" element. Keep it
2722 ;; if we have kept everything thus far.
2723 (when (not undo-deltas)
2724 (push undo-elt selective-list)))
2725 ;; Skip over marker adjustments, instead relying
2726 ;; on finding them after (TEXT . POS) elements
2727 ((markerp (car-safe undo-elt))
2728 nil)
2730 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2731 undo-deltas)))
2732 (if (undo-elt-in-region adjusted-undo-elt start end)
2733 (progn
2734 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2735 (push adjusted-undo-elt selective-list)
2736 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2737 ;; kept. primitive-undo may discard them later.
2738 (when (and (stringp (car-safe adjusted-undo-elt))
2739 (integerp (cdr-safe adjusted-undo-elt)))
2740 (let ((list-i (cdr ulist)))
2741 (while (markerp (car-safe (car list-i)))
2742 (push (pop list-i) selective-list)))))
2743 (let ((delta (undo-delta undo-elt)))
2744 (when (/= 0 (cdr delta))
2745 (push delta undo-deltas)))))))
2746 (pop ulist))
2747 (nreverse selective-list)))
2749 (defun undo-elt-in-region (undo-elt start end)
2750 "Determine whether UNDO-ELT falls inside the region START ... END.
2751 If it crosses the edge, we return nil.
2753 Generally this function is not useful for determining
2754 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2755 because markers can be arbitrarily relocated. Instead, pass the
2756 marker adjustment's corresponding (TEXT . POS) element."
2757 (cond ((integerp undo-elt)
2758 (and (>= undo-elt start)
2759 (<= undo-elt end)))
2760 ((eq undo-elt nil)
2762 ((atom undo-elt)
2763 nil)
2764 ((stringp (car undo-elt))
2765 ;; (TEXT . POSITION)
2766 (and (>= (abs (cdr undo-elt)) start)
2767 (<= (abs (cdr undo-elt)) end)))
2768 ((and (consp undo-elt) (markerp (car undo-elt)))
2769 ;; (MARKER . ADJUSTMENT)
2770 (<= start (car undo-elt) end))
2771 ((null (car undo-elt))
2772 ;; (nil PROPERTY VALUE BEG . END)
2773 (let ((tail (nthcdr 3 undo-elt)))
2774 (and (>= (car tail) start)
2775 (<= (cdr tail) end))))
2776 ((integerp (car undo-elt))
2777 ;; (BEGIN . END)
2778 (and (>= (car undo-elt) start)
2779 (<= (cdr undo-elt) end)))))
2781 (defun undo-elt-crosses-region (undo-elt start end)
2782 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2783 This assumes we have already decided that UNDO-ELT
2784 is not *inside* the region START...END."
2785 (declare (obsolete nil "25.1"))
2786 (cond ((atom undo-elt) nil)
2787 ((null (car undo-elt))
2788 ;; (nil PROPERTY VALUE BEG . END)
2789 (let ((tail (nthcdr 3 undo-elt)))
2790 (and (< (car tail) end)
2791 (> (cdr tail) start))))
2792 ((integerp (car undo-elt))
2793 ;; (BEGIN . END)
2794 (and (< (car undo-elt) end)
2795 (> (cdr undo-elt) start)))))
2797 (defun undo-adjust-elt (elt deltas)
2798 "Return adjustment of undo element ELT by the undo DELTAS
2799 list."
2800 (pcase elt
2801 ;; POSITION
2802 ((pred integerp)
2803 (undo-adjust-pos elt deltas))
2804 ;; (BEG . END)
2805 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2806 (undo-adjust-beg-end beg end deltas))
2807 ;; (TEXT . POSITION)
2808 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2809 (cons text (* (if (< pos 0) -1 1)
2810 (undo-adjust-pos (abs pos) deltas))))
2811 ;; (nil PROPERTY VALUE BEG . END)
2812 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2813 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2814 ;; (apply DELTA START END FUN . ARGS)
2815 ;; FIXME
2816 ;; All others return same elt
2817 (_ elt)))
2819 ;; (BEG . END) can adjust to the same positions, commonly when an
2820 ;; insertion was undone and they are out of region, for example:
2822 ;; buf pos:
2823 ;; 123456789 buffer-undo-list undo-deltas
2824 ;; --------- ---------------- -----------
2825 ;; [...]
2826 ;; abbaa (2 . 4) (2 . -2)
2827 ;; aaa ("bb" . 2) (2 . 2)
2828 ;; [...]
2830 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2831 ;; undo. Further adjustments to such an element should be the same as
2832 ;; for (TEXT . POSITION) elements. The options are:
2834 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2835 ;; analogous to marker insertion-type t.
2837 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2838 ;; marker insertion-type nil.
2840 ;; There was no strong reason to prefer one or the other, except that
2841 ;; the first is more consistent with prior undo in region behavior.
2842 (defun undo-adjust-beg-end (beg end deltas)
2843 "Return cons of adjustments to BEG and END by the undo DELTAS
2844 list."
2845 (let ((adj-beg (undo-adjust-pos beg deltas)))
2846 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2847 (cons adj-beg
2848 (max adj-beg (undo-adjust-pos end deltas t)))))
2850 (defun undo-adjust-pos (pos deltas &optional use-<)
2851 "Return adjustment of POS by the undo DELTAS list, comparing
2852 with < or <= based on USE-<."
2853 (dolist (d deltas pos)
2854 (when (if use-<
2855 (< (car d) pos)
2856 (<= (car d) pos))
2857 (setq pos
2858 ;; Don't allow pos to become less than the undo-delta
2859 ;; position. This edge case is described in the overview
2860 ;; comments.
2861 (max (car d) (- pos (cdr d)))))))
2863 ;; Return the first affected buffer position and the delta for an undo element
2864 ;; delta is defined as the change in subsequent buffer positions if we *did*
2865 ;; the undo.
2866 (defun undo-delta (undo-elt)
2867 (if (consp undo-elt)
2868 (cond ((stringp (car undo-elt))
2869 ;; (TEXT . POSITION)
2870 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2871 ((integerp (car undo-elt))
2872 ;; (BEGIN . END)
2873 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2875 '(0 . 0)))
2876 '(0 . 0)))
2878 ;;; Default undo-boundary addition
2880 ;; This section adds a new undo-boundary at either after a command is
2881 ;; called or in some cases on a timer called after a change is made in
2882 ;; any buffer.
2883 (defvar-local undo-auto--last-boundary-cause nil
2884 "Describe the cause of the last undo-boundary.
2886 If `explicit', the last boundary was caused by an explicit call to
2887 `undo-boundary', that is one not called by the code in this
2888 section.
2890 If it is equal to `timer', then the last boundary was inserted
2891 by `undo-auto--boundary-timer'.
2893 If it is equal to `command', then the last boundary was inserted
2894 automatically after a command, that is by the code defined in
2895 this section.
2897 If it is equal to a list, then the last boundary was inserted by
2898 an amalgamating command. The car of the list is the number of
2899 times an amalgamating command has been called, and the cdr are the
2900 buffers that were changed during the last command.")
2902 (defvar undo-auto-current-boundary-timer nil
2903 "Current timer which will run `undo-auto--boundary-timer' or nil.
2905 If set to non-nil, this will effectively disable the timer.")
2907 (defvar undo-auto--this-command-amalgamating nil
2908 "Non-nil if `this-command' should be amalgamated.
2909 This variable is set to nil by `undo-auto--boundaries' and is set
2910 by `undo-auto-amalgamate'." )
2912 (defun undo-auto--needs-boundary-p ()
2913 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2914 (car-safe buffer-undo-list))
2916 (defun undo-auto--last-boundary-amalgamating-number ()
2917 "Return the number of amalgamating last commands or nil.
2918 Amalgamating commands are, by default, either
2919 `self-insert-command' and `delete-char', but can be any command
2920 that calls `undo-auto-amalgamate'."
2921 (car-safe undo-auto--last-boundary-cause))
2923 (defun undo-auto--ensure-boundary (cause)
2924 "Add an `undo-boundary' to the current buffer if needed.
2925 REASON describes the reason that the boundary is being added; see
2926 `undo-auto--last-boundary' for more information."
2927 (when (and
2928 (undo-auto--needs-boundary-p))
2929 (let ((last-amalgamating
2930 (undo-auto--last-boundary-amalgamating-number)))
2931 (undo-boundary)
2932 (setq undo-auto--last-boundary-cause
2933 (if (eq 'amalgamate cause)
2934 (cons
2935 (if last-amalgamating (1+ last-amalgamating) 0)
2936 undo-auto--undoably-changed-buffers)
2937 cause)))))
2939 (defun undo-auto--boundaries (cause)
2940 "Check recently changed buffers and add a boundary if necessary.
2941 REASON describes the reason that the boundary is being added; see
2942 `undo-last-boundary' for more information."
2943 ;; (Bug #23785) All commands should ensure that there is an undo
2944 ;; boundary whether they have changed the current buffer or not.
2945 (when (eq cause 'command)
2946 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2947 (dolist (b undo-auto--undoably-changed-buffers)
2948 (when (buffer-live-p b)
2949 (with-current-buffer b
2950 (undo-auto--ensure-boundary cause))))
2951 (setq undo-auto--undoably-changed-buffers nil))
2953 (defun undo-auto--boundary-timer ()
2954 "Timer which will run `undo--auto-boundary-timer'."
2955 (setq undo-auto-current-boundary-timer nil)
2956 (undo-auto--boundaries 'timer))
2958 (defun undo-auto--boundary-ensure-timer ()
2959 "Ensure that the `undo-auto-boundary-timer' is set."
2960 (unless undo-auto-current-boundary-timer
2961 (setq undo-auto-current-boundary-timer
2962 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2964 (defvar undo-auto--undoably-changed-buffers nil
2965 "List of buffers that have changed recently.
2967 This list is maintained by `undo-auto--undoable-change' and
2968 `undo-auto--boundaries' and can be affected by changes to their
2969 default values.")
2971 (defun undo-auto--add-boundary ()
2972 "Add an `undo-boundary' in appropriate buffers."
2973 (undo-auto--boundaries
2974 (let ((amal undo-auto--this-command-amalgamating))
2975 (setq undo-auto--this-command-amalgamating nil)
2976 (if amal
2977 'amalgamate
2978 'command))))
2980 (defun undo-auto-amalgamate ()
2981 "Amalgamate undo if necessary.
2982 This function can be called before an amalgamating command. It
2983 removes the previous `undo-boundary' if a series of such calls
2984 have been made. By default `self-insert-command' and
2985 `delete-char' are the only amalgamating commands, although this
2986 function could be called by any command wishing to have this
2987 behavior."
2988 (let ((last-amalgamating-count
2989 (undo-auto--last-boundary-amalgamating-number)))
2990 (setq undo-auto--this-command-amalgamating t)
2991 (when
2992 last-amalgamating-count
2994 (and
2995 (< last-amalgamating-count 20)
2996 (eq this-command last-command))
2997 ;; Amalgamate all buffers that have changed.
2998 (dolist (b (cdr undo-auto--last-boundary-cause))
2999 (when (buffer-live-p b)
3000 (with-current-buffer
3002 (when
3003 ;; The head of `buffer-undo-list' is nil.
3004 ;; `car-safe' doesn't work because
3005 ;; `buffer-undo-list' need not be a list!
3006 (and (listp buffer-undo-list)
3007 (not (car buffer-undo-list)))
3008 (setq buffer-undo-list
3009 (cdr buffer-undo-list))))))
3010 (setq undo-auto--last-boundary-cause 0)))))
3012 (defun undo-auto--undoable-change ()
3013 "Called after every undoable buffer change."
3014 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
3015 (undo-auto--boundary-ensure-timer))
3016 ;; End auto-boundary section
3018 (defun undo-amalgamate-change-group (handle)
3019 "Amalgamate changes in change-group since HANDLE.
3020 Remove all undo boundaries between the state of HANDLE and now.
3021 HANDLE is as returned by `prepare-change-group'."
3022 (dolist (elt handle)
3023 (with-current-buffer (car elt)
3024 (setq elt (cdr elt))
3025 (when (consp buffer-undo-list)
3026 (let ((old-car (car-safe elt))
3027 (old-cdr (cdr-safe elt)))
3028 (unwind-protect
3029 (progn
3030 ;; Temporarily truncate the undo log at ELT.
3031 (when (consp elt)
3032 (setcar elt t) (setcdr elt nil))
3033 (when
3034 (or (null elt) ;The undo-log was empty.
3035 ;; `elt' is still in the log: normal case.
3036 (eq elt (last buffer-undo-list))
3037 ;; `elt' is not in the log any more, but that's because
3038 ;; the log is "all new", so we should remove all
3039 ;; boundaries from it.
3040 (not (eq (last buffer-undo-list) (last old-cdr))))
3041 (cl-callf (lambda (x) (delq nil x))
3042 (if (car buffer-undo-list)
3043 buffer-undo-list
3044 ;; Preserve the undo-boundaries at either ends of the
3045 ;; change-groups.
3046 (cdr buffer-undo-list)))))
3047 ;; Reset the modified cons cell ELT to its original content.
3048 (when (consp elt)
3049 (setcar elt old-car)
3050 (setcdr elt old-cdr))))))))
3053 (defcustom undo-ask-before-discard nil
3054 "If non-nil ask about discarding undo info for the current command.
3055 Normally, Emacs discards the undo info for the current command if
3056 it exceeds `undo-outer-limit'. But if you set this option
3057 non-nil, it asks in the echo area whether to discard the info.
3058 If you answer no, there is a slight risk that Emacs might crash, so
3059 only do it if you really want to undo the command.
3061 This option is mainly intended for debugging. You have to be
3062 careful if you use it for other purposes. Garbage collection is
3063 inhibited while the question is asked, meaning that Emacs might
3064 leak memory. So you should make sure that you do not wait
3065 excessively long before answering the question."
3066 :type 'boolean
3067 :group 'undo
3068 :version "22.1")
3070 (defvar undo-extra-outer-limit nil
3071 "If non-nil, an extra level of size that's ok in an undo item.
3072 We don't ask the user about truncating the undo list until the
3073 current item gets bigger than this amount.
3075 This variable only matters if `undo-ask-before-discard' is non-nil.")
3076 (make-variable-buffer-local 'undo-extra-outer-limit)
3078 ;; When the first undo batch in an undo list is longer than
3079 ;; undo-outer-limit, this function gets called to warn the user that
3080 ;; the undo info for the current command was discarded. Garbage
3081 ;; collection is inhibited around the call, so it had better not do a
3082 ;; lot of consing.
3083 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3084 (defun undo-outer-limit-truncate (size)
3085 (if undo-ask-before-discard
3086 (when (or (null undo-extra-outer-limit)
3087 (> size undo-extra-outer-limit))
3088 ;; Don't ask the question again unless it gets even bigger.
3089 ;; This applies, in particular, if the user quits from the question.
3090 ;; Such a quit quits out of GC, but something else will call GC
3091 ;; again momentarily. It will call this function again,
3092 ;; but we don't want to ask the question again.
3093 (setq undo-extra-outer-limit (+ size 50000))
3094 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3095 (yes-or-no-p (format-message
3096 "Buffer `%s' undo info is %d bytes long; discard it? "
3097 (buffer-name) size)))
3098 (progn (setq buffer-undo-list nil)
3099 (setq undo-extra-outer-limit nil)
3101 nil))
3102 (display-warning '(undo discard-info)
3103 (concat
3104 (format-message
3105 "Buffer `%s' undo info was %d bytes long.\n"
3106 (buffer-name) size)
3107 "The undo info was discarded because it exceeded \
3108 `undo-outer-limit'.
3110 This is normal if you executed a command that made a huge change
3111 to the buffer. In that case, to prevent similar problems in the
3112 future, set `undo-outer-limit' to a value that is large enough to
3113 cover the maximum size of normal changes you expect a single
3114 command to make, but not so large that it might exceed the
3115 maximum memory allotted to Emacs.
3117 If you did not execute any such command, the situation is
3118 probably due to a bug and you should report it.
3120 You can disable the popping up of this buffer by adding the entry
3121 \(undo discard-info) to the user option `warning-suppress-types',
3122 which is defined in the `warnings' library.\n")
3123 :warning)
3124 (setq buffer-undo-list nil)
3127 (defcustom password-word-equivalents
3128 '("password" "passcode" "passphrase" "pass phrase"
3129 ; These are sorted according to the GNU en_US locale.
3130 "암호" ; ko
3131 "パスワード" ; ja
3132 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3133 "ពាក្យសម្ងាត់" ; km
3134 "adgangskode" ; da
3135 "contraseña" ; es
3136 "contrasenya" ; ca
3137 "geslo" ; sl
3138 "hasło" ; pl
3139 "heslo" ; cs, sk
3140 "iphasiwedi" ; zu
3141 "jelszó" ; hu
3142 "lösenord" ; sv
3143 "lozinka" ; hr, sr
3144 "mật khẩu" ; vi
3145 "mot de passe" ; fr
3146 "parola" ; tr
3147 "pasahitza" ; eu
3148 "passord" ; nb
3149 "passwort" ; de
3150 "pasvorto" ; eo
3151 "salasana" ; fi
3152 "senha" ; pt
3153 "slaptažodis" ; lt
3154 "wachtwoord" ; nl
3155 "كلمة السر" ; ar
3156 "ססמה" ; he
3157 "лозинка" ; sr
3158 "пароль" ; kk, ru, uk
3159 "गुप्तशब्द" ; mr
3160 "शब्दकूट" ; hi
3161 "પાસવર્ડ" ; gu
3162 "సంకేతపదము" ; te
3163 "ਪਾਸਵਰਡ" ; pa
3164 "ಗುಪ್ತಪದ" ; kn
3165 "கடவுச்சொல்" ; ta
3166 "അടയാളവാക്ക്" ; ml
3167 "গুপ্তশব্দ" ; as
3168 "পাসওয়ার্ড" ; bn_IN
3169 "රහස්පදය" ; si
3170 "密码" ; zh_CN
3171 "密碼" ; zh_TW
3173 "List of words equivalent to \"password\".
3174 This is used by Shell mode and other parts of Emacs to recognize
3175 password prompts, including prompts in languages other than
3176 English. Different case choices should not be assumed to be
3177 included; callers should bind `case-fold-search' to t."
3178 :type '(repeat string)
3179 :version "24.4"
3180 :group 'processes)
3182 (defvar shell-command-history nil
3183 "History list for some commands that read shell commands.
3185 Maximum length of the history list is determined by the value
3186 of `history-length', which see.")
3188 (defvar shell-command-switch (purecopy "-c")
3189 "Switch used to have the shell execute its command line argument.")
3191 (defvar shell-command-default-error-buffer nil
3192 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3193 This buffer is used when `shell-command' or `shell-command-on-region'
3194 is run interactively. A value of nil means that output to stderr and
3195 stdout will be intermixed in the output stream.")
3197 (declare-function mailcap-file-default-commands "mailcap" (files))
3198 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3200 (defun minibuffer-default-add-shell-commands ()
3201 "Return a list of all commands associated with the current file.
3202 This function is used to add all related commands retrieved by `mailcap'
3203 to the end of the list of defaults just after the default value."
3204 (interactive)
3205 (let* ((filename (if (listp minibuffer-default)
3206 (car minibuffer-default)
3207 minibuffer-default))
3208 (commands (and filename (require 'mailcap nil t)
3209 (mailcap-file-default-commands (list filename)))))
3210 (setq commands (mapcar (lambda (command)
3211 (concat command " " filename))
3212 commands))
3213 (if (listp minibuffer-default)
3214 (append minibuffer-default commands)
3215 (cons minibuffer-default commands))))
3217 (declare-function shell-completion-vars "shell" ())
3219 (defvar minibuffer-local-shell-command-map
3220 (let ((map (make-sparse-keymap)))
3221 (set-keymap-parent map minibuffer-local-map)
3222 (define-key map "\t" 'completion-at-point)
3223 map)
3224 "Keymap used for completing shell commands in minibuffer.")
3226 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3227 "Read a shell command from the minibuffer.
3228 The arguments are the same as the ones of `read-from-minibuffer',
3229 except READ and KEYMAP are missing and HIST defaults
3230 to `shell-command-history'."
3231 (require 'shell)
3232 (minibuffer-with-setup-hook
3233 (lambda ()
3234 (shell-completion-vars)
3235 (set (make-local-variable 'minibuffer-default-add-function)
3236 'minibuffer-default-add-shell-commands))
3237 (apply 'read-from-minibuffer prompt initial-contents
3238 minibuffer-local-shell-command-map
3240 (or hist 'shell-command-history)
3241 args)))
3243 (defcustom async-shell-command-buffer 'confirm-new-buffer
3244 "What to do when the output buffer is used by another shell command.
3245 This option specifies how to resolve the conflict where a new command
3246 wants to direct its output to the buffer `*Async Shell Command*',
3247 but this buffer is already taken by another running shell command.
3249 The value `confirm-kill-process' is used to ask for confirmation before
3250 killing the already running process and running a new process
3251 in the same buffer, `confirm-new-buffer' for confirmation before running
3252 the command in a new buffer with a name other than the default buffer name,
3253 `new-buffer' for doing the same without confirmation,
3254 `confirm-rename-buffer' for confirmation before renaming the existing
3255 output buffer and running a new command in the default buffer,
3256 `rename-buffer' for doing the same without confirmation."
3257 :type '(choice (const :tag "Confirm killing of running command"
3258 confirm-kill-process)
3259 (const :tag "Confirm creation of a new buffer"
3260 confirm-new-buffer)
3261 (const :tag "Create a new buffer"
3262 new-buffer)
3263 (const :tag "Confirm renaming of existing buffer"
3264 confirm-rename-buffer)
3265 (const :tag "Rename the existing buffer"
3266 rename-buffer))
3267 :group 'shell
3268 :version "24.3")
3270 (defun shell-command--save-pos-or-erase ()
3271 "Store a buffer position or erase the buffer.
3272 See `shell-command-dont-erase-buffer'."
3273 (let ((sym shell-command-dont-erase-buffer)
3274 pos)
3275 (setq buffer-read-only nil)
3276 ;; Setting buffer-read-only to nil doesn't suffice
3277 ;; if some text has a non-nil read-only property,
3278 ;; which comint sometimes adds for prompts.
3279 (setq pos
3280 (cond ((eq sym 'save-point) (point))
3281 ((eq sym 'beg-last-out) (point-max))
3282 ((not sym)
3283 (let ((inhibit-read-only t))
3284 (erase-buffer) nil))))
3285 (when pos
3286 (goto-char (point-max))
3287 (push (cons (current-buffer) pos)
3288 shell-command-saved-pos))))
3290 (defun shell-command--set-point-after-cmd (&optional buffer)
3291 "Set point in BUFFER after command complete.
3292 BUFFER is the output buffer of the command; if nil, then defaults
3293 to the current BUFFER.
3294 Set point to the `cdr' of the element in `shell-command-saved-pos'
3295 whose `car' is BUFFER."
3296 (when shell-command-dont-erase-buffer
3297 (let* ((sym shell-command-dont-erase-buffer)
3298 (buf (or buffer (current-buffer)))
3299 (pos (alist-get buf shell-command-saved-pos)))
3300 (setq shell-command-saved-pos
3301 (assq-delete-all buf shell-command-saved-pos))
3302 (when (buffer-live-p buf)
3303 (let ((win (car (get-buffer-window-list buf)))
3304 (pmax (with-current-buffer buf (point-max))))
3305 (unless (and pos (memq sym '(save-point beg-last-out)))
3306 (setq pos pmax))
3307 ;; Set point in the window displaying buf, if any; otherwise
3308 ;; display buf temporary in selected frame and set the point.
3309 (if win
3310 (set-window-point win pos)
3311 (save-window-excursion
3312 (let ((win (display-buffer
3314 '(nil (inhibit-switch-frame . t)))))
3315 (set-window-point win pos)))))))))
3317 (defun async-shell-command (command &optional output-buffer error-buffer)
3318 "Execute string COMMAND asynchronously in background.
3320 Like `shell-command', but adds `&' at the end of COMMAND
3321 to execute it asynchronously.
3323 The output appears in the buffer `*Async Shell Command*'.
3324 That buffer is in shell mode.
3326 You can configure `async-shell-command-buffer' to specify what to do in
3327 case when `*Async Shell Command*' buffer is already taken by another
3328 running shell command. To run COMMAND without displaying the output
3329 in a window you can configure `display-buffer-alist' to use the action
3330 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3332 In Elisp, you will often be better served by calling `start-process'
3333 directly, since it offers more control and does not impose the use of a
3334 shell (with its need to quote arguments)."
3335 (interactive
3336 (list
3337 (read-shell-command "Async shell command: " nil nil
3338 (let ((filename
3339 (cond
3340 (buffer-file-name)
3341 ((eq major-mode 'dired-mode)
3342 (dired-get-filename nil t)))))
3343 (and filename (file-relative-name filename))))
3344 current-prefix-arg
3345 shell-command-default-error-buffer))
3346 (unless (string-match "&[ \t]*\\'" command)
3347 (setq command (concat command " &")))
3348 (shell-command command output-buffer error-buffer))
3350 (defun shell-command (command &optional output-buffer error-buffer)
3351 "Execute string COMMAND in inferior shell; display output, if any.
3352 With prefix argument, insert the COMMAND's output at point.
3354 Interactively, prompt for COMMAND in the minibuffer.
3356 If COMMAND ends in `&', execute it asynchronously.
3357 The output appears in the buffer `*Async Shell Command*'.
3358 That buffer is in shell mode. You can also use
3359 `async-shell-command' that automatically adds `&'.
3361 Otherwise, COMMAND is executed synchronously. The output appears in
3362 the buffer `*Shell Command Output*'. If the output is short enough to
3363 display in the echo area (which is determined by the variables
3364 `resize-mini-windows' and `max-mini-window-height'), it is shown
3365 there, but it is nonetheless available in buffer `*Shell Command
3366 Output*' even though that buffer is not automatically displayed.
3368 To specify a coding system for converting non-ASCII characters
3369 in the shell command output, use \\[universal-coding-system-argument] \
3370 before this command.
3372 Noninteractive callers can specify coding systems by binding
3373 `coding-system-for-read' and `coding-system-for-write'.
3375 The optional second argument OUTPUT-BUFFER, if non-nil,
3376 says to put the output in some other buffer.
3377 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3378 and insert the output there; a non-nil value of
3379 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3380 If OUTPUT-BUFFER is not a buffer and not nil, insert the output
3381 in current buffer after point leaving mark after it.
3382 This cannot be done asynchronously.
3384 If the command terminates without error, but generates output,
3385 and you did not specify \"insert it in the current buffer\",
3386 the output can be displayed in the echo area or in its buffer.
3387 If the output is short enough to display in the echo area
3388 \(determined by the variable `max-mini-window-height' if
3389 `resize-mini-windows' is non-nil), it is shown there.
3390 Otherwise,the buffer containing the output is displayed.
3392 If there is output and an error, and you did not specify \"insert it
3393 in the current buffer\", a message about the error goes at the end
3394 of the output.
3396 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3397 or buffer name to which to direct the command's standard error output.
3398 If it is nil, error output is mingled with regular output.
3399 In an interactive call, the variable `shell-command-default-error-buffer'
3400 specifies the value of ERROR-BUFFER.
3402 In Elisp, you will often be better served by calling `call-process' or
3403 `start-process' directly, since it offers more control and does not impose
3404 the use of a shell (with its need to quote arguments)."
3406 (interactive
3407 (list
3408 (read-shell-command "Shell command: " nil nil
3409 (let ((filename
3410 (cond
3411 (buffer-file-name)
3412 ((eq major-mode 'dired-mode)
3413 (dired-get-filename nil t)))))
3414 (and filename (file-relative-name filename))))
3415 current-prefix-arg
3416 shell-command-default-error-buffer))
3417 ;; Look for a handler in case default-directory is a remote file name.
3418 (let ((handler
3419 (find-file-name-handler (directory-file-name default-directory)
3420 'shell-command)))
3421 (if handler
3422 (funcall handler 'shell-command command output-buffer error-buffer)
3423 (if (and output-buffer
3424 (not (or (bufferp output-buffer) (stringp output-buffer))))
3425 ;; Output goes in current buffer.
3426 (let ((error-file
3427 (if error-buffer
3428 (make-temp-file
3429 (expand-file-name "scor"
3430 (or small-temporary-file-directory
3431 temporary-file-directory)))
3432 nil)))
3433 (barf-if-buffer-read-only)
3434 (push-mark nil t)
3435 ;; We do not use -f for csh; we will not support broken use of
3436 ;; .cshrcs. Even the BSD csh manual says to use
3437 ;; "if ($?prompt) exit" before things which are not useful
3438 ;; non-interactively. Besides, if someone wants their other
3439 ;; aliases for shell commands then they can still have them.
3440 (call-process shell-file-name nil
3441 (if error-file
3442 (list t error-file)
3444 nil shell-command-switch command)
3445 (when (and error-file (file-exists-p error-file))
3446 (if (< 0 (nth 7 (file-attributes error-file)))
3447 (with-current-buffer (get-buffer-create error-buffer)
3448 (let ((pos-from-end (- (point-max) (point))))
3449 (or (bobp)
3450 (insert "\f\n"))
3451 ;; Do no formatting while reading error file,
3452 ;; because that can run a shell command, and we
3453 ;; don't want that to cause an infinite recursion.
3454 (format-insert-file error-file nil)
3455 ;; Put point after the inserted errors.
3456 (goto-char (- (point-max) pos-from-end)))
3457 (display-buffer (current-buffer))))
3458 (delete-file error-file))
3459 ;; This is like exchange-point-and-mark, but doesn't
3460 ;; activate the mark. It is cleaner to avoid activation,
3461 ;; even though the command loop would deactivate the mark
3462 ;; because we inserted text.
3463 (goto-char (prog1 (mark t)
3464 (set-marker (mark-marker) (point)
3465 (current-buffer)))))
3466 ;; Output goes in a separate buffer.
3467 ;; Preserve the match data in case called from a program.
3468 ;; FIXME: It'd be ridiculous for an Elisp function to call
3469 ;; shell-command and assume that it won't mess the match-data!
3470 (save-match-data
3471 (if (string-match "[ \t]*&[ \t]*\\'" command)
3472 ;; Command ending with ampersand means asynchronous.
3473 (let ((buffer (get-buffer-create
3474 (or output-buffer "*Async Shell Command*")))
3475 (directory default-directory)
3476 proc)
3477 ;; Remove the ampersand.
3478 (setq command (substring command 0 (match-beginning 0)))
3479 ;; Ask the user what to do with already running process.
3480 (setq proc (get-buffer-process buffer))
3481 (when proc
3482 (cond
3483 ((eq async-shell-command-buffer 'confirm-kill-process)
3484 ;; If will kill a process, query first.
3485 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3486 (kill-process proc)
3487 (error "Shell command in progress")))
3488 ((eq async-shell-command-buffer 'confirm-new-buffer)
3489 ;; If will create a new buffer, query first.
3490 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3491 (setq buffer (generate-new-buffer
3492 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3493 output-buffer "*Async Shell Command*")))
3494 (error "Shell command in progress")))
3495 ((eq async-shell-command-buffer 'new-buffer)
3496 ;; It will create a new buffer.
3497 (setq buffer (generate-new-buffer
3498 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3499 output-buffer "*Async Shell Command*"))))
3500 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3501 ;; If will rename the buffer, query first.
3502 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3503 (progn
3504 (with-current-buffer buffer
3505 (rename-uniquely))
3506 (setq buffer (get-buffer-create
3507 (or output-buffer "*Async Shell Command*"))))
3508 (error "Shell command in progress")))
3509 ((eq async-shell-command-buffer 'rename-buffer)
3510 ;; It will rename the buffer.
3511 (with-current-buffer buffer
3512 (rename-uniquely))
3513 (setq buffer (get-buffer-create
3514 (or output-buffer "*Async Shell Command*"))))))
3515 (with-current-buffer buffer
3516 (display-buffer buffer '(nil (allow-no-window . t)))
3517 (shell-command--save-pos-or-erase)
3518 (setq default-directory directory)
3519 (setq proc (start-process "Shell" buffer shell-file-name
3520 shell-command-switch command))
3521 (setq mode-line-process '(":%s"))
3522 (require 'shell) (shell-mode)
3523 (set-process-sentinel proc 'shell-command-sentinel)
3524 ;; Use the comint filter for proper handling of carriage motion
3525 ;; (see `comint-inhibit-carriage-motion'),.
3526 (set-process-filter proc 'comint-output-filter)
3528 ;; Otherwise, command is executed synchronously.
3529 (shell-command-on-region (point) (point) command
3530 output-buffer nil error-buffer)))))))
3532 (defun display-message-or-buffer (message &optional buffer-name action frame)
3533 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3534 MESSAGE may be either a string or a buffer.
3536 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3537 for maximum height of the echo area, as defined by `max-mini-window-height'
3538 if `resize-mini-windows' is non-nil.
3540 Returns either the string shown in the echo area, or when a pop-up
3541 buffer is used, the window used to display it.
3543 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3544 name of the buffer used to display it in the case where a pop-up buffer
3545 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3546 string and it is displayed in the echo area, it is not specified whether
3547 the contents are inserted into the buffer anyway.
3549 Optional arguments ACTION and FRAME are as for `display-buffer',
3550 and are only used if a pop-up buffer is displayed."
3551 (cond ((and (stringp message) (not (string-match "\n" message)))
3552 ;; Trivial case where we can use the echo area
3553 (message "%s" message))
3554 ((and (stringp message)
3555 (= (string-match "\n" message) (1- (length message))))
3556 ;; Trivial case where we can just remove single trailing newline
3557 (message "%s" (substring message 0 (1- (length message)))))
3559 ;; General case
3560 (with-current-buffer
3561 (if (bufferp message)
3562 message
3563 (get-buffer-create (or buffer-name "*Message*")))
3565 (unless (bufferp message)
3566 (erase-buffer)
3567 (insert message))
3569 (let ((lines
3570 (if (= (buffer-size) 0)
3572 (count-screen-lines nil nil nil (minibuffer-window)))))
3573 (cond ((= lines 0))
3574 ((and (or (<= lines 1)
3575 (<= lines
3576 (if resize-mini-windows
3577 (cond ((floatp max-mini-window-height)
3578 (* (frame-height)
3579 max-mini-window-height))
3580 ((integerp max-mini-window-height)
3581 max-mini-window-height)
3584 1)))
3585 ;; Don't use the echo area if the output buffer is
3586 ;; already displayed in the selected frame.
3587 (not (get-buffer-window (current-buffer))))
3588 ;; Echo area
3589 (goto-char (point-max))
3590 (when (bolp)
3591 (backward-char 1))
3592 (message "%s" (buffer-substring (point-min) (point))))
3594 ;; Buffer
3595 (goto-char (point-min))
3596 (display-buffer (current-buffer) action frame))))))))
3599 ;; We have a sentinel to prevent insertion of a termination message
3600 ;; in the buffer itself, and to set the point in the buffer when
3601 ;; `shell-command-dont-erase-buffer' is non-nil.
3602 (defun shell-command-sentinel (process signal)
3603 (when (memq (process-status process) '(exit signal))
3604 (shell-command--set-point-after-cmd (process-buffer process))
3605 (message "%s: %s."
3606 (car (cdr (cdr (process-command process))))
3607 (substring signal 0 -1))))
3609 (defun shell-command-on-region (start end command
3610 &optional output-buffer replace
3611 error-buffer display-error-buffer
3612 region-noncontiguous-p)
3613 "Execute string COMMAND in inferior shell with region as input.
3614 Normally display output (if any) in temp buffer `*Shell Command Output*';
3615 Prefix arg means replace the region with it. Return the exit code of
3616 COMMAND.
3618 To specify a coding system for converting non-ASCII characters
3619 in the input and output to the shell command, use \\[universal-coding-system-argument]
3620 before this command. By default, the input (from the current buffer)
3621 is encoded using coding-system specified by `process-coding-system-alist',
3622 falling back to `default-process-coding-system' if no match for COMMAND
3623 is found in `process-coding-system-alist'.
3625 Noninteractive callers can specify coding systems by binding
3626 `coding-system-for-read' and `coding-system-for-write'.
3628 If the command generates output, the output may be displayed
3629 in the echo area or in a buffer.
3630 If the output is short enough to display in the echo area
3631 \(determined by the variable `max-mini-window-height' if
3632 `resize-mini-windows' is non-nil), it is shown there.
3633 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3634 The output is available in that buffer in both cases.
3636 If there is output and an error, a message about the error
3637 appears at the end of the output.
3639 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3640 command's output. If the value is a buffer or buffer name,
3641 erase that buffer and insert the output there; a non-nil value of
3642 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3643 If the value is nil, use the buffer `*Shell Command Output*'.
3644 Any other non-nil value means to insert the output in the
3645 current buffer after START.
3647 Optional fifth arg REPLACE, if non-nil, means to insert the
3648 output in place of text from START to END, putting point and mark
3649 around it.
3651 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3652 or buffer name to which to direct the command's standard error
3653 output. If nil, error output is mingled with regular output.
3654 When called interactively, `shell-command-default-error-buffer'
3655 is used for ERROR-BUFFER.
3657 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3658 display the error buffer if there were any errors. When called
3659 interactively, this is t."
3660 (interactive (let (string)
3661 (unless (mark)
3662 (user-error "The mark is not set now, so there is no region"))
3663 ;; Do this before calling region-beginning
3664 ;; and region-end, in case subprocess output
3665 ;; relocates them while we are in the minibuffer.
3666 (setq string (read-shell-command "Shell command on region: "))
3667 ;; call-interactively recognizes region-beginning and
3668 ;; region-end specially, leaving them in the history.
3669 (list (region-beginning) (region-end)
3670 string
3671 current-prefix-arg
3672 current-prefix-arg
3673 shell-command-default-error-buffer
3675 (region-noncontiguous-p))))
3676 (let ((error-file
3677 (if error-buffer
3678 (make-temp-file
3679 (expand-file-name "scor"
3680 (or small-temporary-file-directory
3681 temporary-file-directory)))
3682 nil))
3683 exit-status)
3684 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3685 (if region-noncontiguous-p
3686 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3687 output)
3688 (with-temp-buffer
3689 (insert input)
3690 (call-process-region (point-min) (point-max)
3691 shell-file-name t t
3692 nil shell-command-switch
3693 command)
3694 (setq output (split-string (buffer-string) "\n")))
3695 (goto-char start)
3696 (funcall region-insert-function output))
3697 (if (or replace
3698 (and output-buffer
3699 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3700 ;; Replace specified region with output from command.
3701 (let ((swap (and replace (< start end))))
3702 ;; Don't muck with mark unless REPLACE says we should.
3703 (goto-char start)
3704 (and replace (push-mark (point) 'nomsg))
3705 (setq exit-status
3706 (call-shell-region start end command replace
3707 (if error-file
3708 (list t error-file)
3709 t)))
3710 ;; It is rude to delete a buffer which the command is not using.
3711 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3712 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3713 ;; (kill-buffer shell-buffer)))
3714 ;; Don't muck with mark unless REPLACE says we should.
3715 (and replace swap (exchange-point-and-mark)))
3716 ;; No prefix argument: put the output in a temp buffer,
3717 ;; replacing its entire contents.
3718 (let ((buffer (get-buffer-create
3719 (or output-buffer "*Shell Command Output*"))))
3720 (unwind-protect
3721 (if (and (eq buffer (current-buffer))
3722 (or (not shell-command-dont-erase-buffer)
3723 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3724 (not (region-active-p)))))
3725 ;; If the input is the same buffer as the output,
3726 ;; delete everything but the specified region,
3727 ;; then replace that region with the output.
3728 (progn (setq buffer-read-only nil)
3729 (delete-region (max start end) (point-max))
3730 (delete-region (point-min) (min start end))
3731 (setq exit-status
3732 (call-process-region (point-min) (point-max)
3733 shell-file-name t
3734 (if error-file
3735 (list t error-file)
3737 nil shell-command-switch
3738 command)))
3739 ;; Clear the output buffer, then run the command with
3740 ;; output there.
3741 (let ((directory default-directory))
3742 (with-current-buffer buffer
3743 (if (not output-buffer)
3744 (setq default-directory directory))
3745 (shell-command--save-pos-or-erase)))
3746 (setq exit-status
3747 (call-shell-region start end command nil
3748 (if error-file
3749 (list buffer error-file)
3750 buffer))))
3751 ;; Report the output.
3752 (with-current-buffer buffer
3753 (setq mode-line-process
3754 (cond ((null exit-status)
3755 " - Error")
3756 ((stringp exit-status)
3757 (format " - Signal [%s]" exit-status))
3758 ((not (equal 0 exit-status))
3759 (format " - Exit [%d]" exit-status)))))
3760 (if (with-current-buffer buffer (> (point-max) (point-min)))
3761 ;; There's some output, display it
3762 (progn
3763 (display-message-or-buffer buffer)
3764 (shell-command--set-point-after-cmd buffer))
3765 ;; No output; error?
3766 (let ((output
3767 (if (and error-file
3768 (< 0 (nth 7 (file-attributes error-file))))
3769 (format "some error output%s"
3770 (if shell-command-default-error-buffer
3771 (format " to the \"%s\" buffer"
3772 shell-command-default-error-buffer)
3773 ""))
3774 "no output")))
3775 (cond ((null exit-status)
3776 (message "(Shell command failed with error)"))
3777 ((equal 0 exit-status)
3778 (message "(Shell command succeeded with %s)"
3779 output))
3780 ((stringp exit-status)
3781 (message "(Shell command killed by signal %s)"
3782 exit-status))
3784 (message "(Shell command failed with code %d and %s)"
3785 exit-status output))))
3786 ;; Don't kill: there might be useful info in the undo-log.
3787 ;; (kill-buffer buffer)
3788 )))))
3790 (when (and error-file (file-exists-p error-file))
3791 (if (< 0 (nth 7 (file-attributes error-file)))
3792 (with-current-buffer (get-buffer-create error-buffer)
3793 (let ((pos-from-end (- (point-max) (point))))
3794 (or (bobp)
3795 (insert "\f\n"))
3796 ;; Do no formatting while reading error file,
3797 ;; because that can run a shell command, and we
3798 ;; don't want that to cause an infinite recursion.
3799 (format-insert-file error-file nil)
3800 ;; Put point after the inserted errors.
3801 (goto-char (- (point-max) pos-from-end)))
3802 (and display-error-buffer
3803 (display-buffer (current-buffer)))))
3804 (delete-file error-file))
3805 exit-status))
3807 (defun shell-command-to-string (command)
3808 "Execute shell command COMMAND and return its output as a string."
3809 (with-output-to-string
3810 (with-current-buffer
3811 standard-output
3812 (process-file shell-file-name nil t nil shell-command-switch command))))
3814 (defun process-file (program &optional infile buffer display &rest args)
3815 "Process files synchronously in a separate process.
3816 Similar to `call-process', but may invoke a file handler based on
3817 `default-directory'. The current working directory of the
3818 subprocess is `default-directory'.
3820 File names in INFILE and BUFFER are handled normally, but file
3821 names in ARGS should be relative to `default-directory', as they
3822 are passed to the process verbatim. (This is a difference to
3823 `call-process' which does not support file handlers for INFILE
3824 and BUFFER.)
3826 Some file handlers might not support all variants, for example
3827 they might behave as if DISPLAY was nil, regardless of the actual
3828 value passed."
3829 (let ((fh (find-file-name-handler default-directory 'process-file))
3830 lc stderr-file)
3831 (unwind-protect
3832 (if fh (apply fh 'process-file program infile buffer display args)
3833 (when infile (setq lc (file-local-copy infile)))
3834 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3835 (make-temp-file "emacs")))
3836 (prog1
3837 (apply 'call-process program
3838 (or lc infile)
3839 (if stderr-file (list (car buffer) stderr-file) buffer)
3840 display args)
3841 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3842 (when stderr-file (delete-file stderr-file))
3843 (when lc (delete-file lc)))))
3845 (defvar process-file-side-effects t
3846 "Whether a call of `process-file' changes remote files.
3848 By default, this variable is always set to t, meaning that a
3849 call of `process-file' could potentially change any file on a
3850 remote host. When set to nil, a file handler could optimize
3851 its behavior with respect to remote file attribute caching.
3853 You should only ever change this variable with a let-binding;
3854 never with `setq'.")
3856 (defun start-file-process (name buffer program &rest program-args)
3857 "Start a program in a subprocess. Return the process object for it.
3859 Similar to `start-process', but may invoke a file handler based on
3860 `default-directory'. See Info node `(elisp)Magic File Names'.
3862 This handler ought to run PROGRAM, perhaps on the local host,
3863 perhaps on a remote host that corresponds to `default-directory'.
3864 In the latter case, the local part of `default-directory' becomes
3865 the working directory of the process.
3867 PROGRAM and PROGRAM-ARGS might be file names. They are not
3868 objects of file handler invocation. File handlers might not
3869 support pty association, if PROGRAM is nil."
3870 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3871 (if fh (apply fh 'start-file-process name buffer program program-args)
3872 (apply 'start-process name buffer program program-args))))
3874 ;;;; Process menu
3876 (defvar tabulated-list-format)
3877 (defvar tabulated-list-entries)
3878 (defvar tabulated-list-sort-key)
3879 (declare-function tabulated-list-init-header "tabulated-list" ())
3880 (declare-function tabulated-list-print "tabulated-list"
3881 (&optional remember-pos update))
3883 (defvar process-menu-query-only nil)
3885 (defvar process-menu-mode-map
3886 (let ((map (make-sparse-keymap)))
3887 (define-key map [?d] 'process-menu-delete-process)
3888 map))
3890 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3891 "Major mode for listing the processes called by Emacs."
3892 (setq tabulated-list-format [("Process" 15 t)
3893 ("PID" 7 t)
3894 ("Status" 7 t)
3895 ("Buffer" 15 t)
3896 ("TTY" 12 t)
3897 ("Command" 0 t)])
3898 (make-local-variable 'process-menu-query-only)
3899 (setq tabulated-list-sort-key (cons "Process" nil))
3900 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3901 (tabulated-list-init-header))
3903 (defun process-menu-delete-process ()
3904 "Kill process at point in a `list-processes' buffer."
3905 (interactive)
3906 (let ((pos (point)))
3907 (delete-process (tabulated-list-get-id))
3908 (revert-buffer)
3909 (goto-char (min pos (point-max)))
3910 (if (eobp)
3911 (forward-line -1)
3912 (beginning-of-line))))
3914 (defun list-processes--refresh ()
3915 "Recompute the list of processes for the Process List buffer.
3916 Also, delete any process that is exited or signaled."
3917 (setq tabulated-list-entries nil)
3918 (dolist (p (process-list))
3919 (cond ((memq (process-status p) '(exit signal closed))
3920 (delete-process p))
3921 ((or (not process-menu-query-only)
3922 (process-query-on-exit-flag p))
3923 (let* ((buf (process-buffer p))
3924 (type (process-type p))
3925 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
3926 (name (process-name p))
3927 (status (symbol-name (process-status p)))
3928 (buf-label (if (buffer-live-p buf)
3929 `(,(buffer-name buf)
3930 face link
3931 help-echo ,(format-message
3932 "Visit buffer `%s'"
3933 (buffer-name buf))
3934 follow-link t
3935 process-buffer ,buf
3936 action process-menu-visit-buffer)
3937 "--"))
3938 (tty (or (process-tty-name p) "--"))
3939 (cmd
3940 (if (memq type '(network serial))
3941 (let ((contact (process-contact p t)))
3942 (if (eq type 'network)
3943 (format "(%s %s)"
3944 (if (plist-get contact :type)
3945 "datagram"
3946 "network")
3947 (if (plist-get contact :server)
3948 (format "server on %s"
3950 (plist-get contact :host)
3951 (plist-get contact :local)))
3952 (format "connection to %s"
3953 (plist-get contact :host))))
3954 (format "(serial port %s%s)"
3955 (or (plist-get contact :port) "?")
3956 (let ((speed (plist-get contact :speed)))
3957 (if speed
3958 (format " at %s b/s" speed)
3959 "")))))
3960 (mapconcat 'identity (process-command p) " "))))
3961 (push (list p (vector name pid status buf-label tty cmd))
3962 tabulated-list-entries))))))
3964 (defun process-menu-visit-buffer (button)
3965 (display-buffer (button-get button 'process-buffer)))
3967 (defun list-processes (&optional query-only buffer)
3968 "Display a list of all processes that are Emacs sub-processes.
3969 If optional argument QUERY-ONLY is non-nil, only processes with
3970 the query-on-exit flag set are listed.
3971 Any process listed as exited or signaled is actually eliminated
3972 after the listing is made.
3973 Optional argument BUFFER specifies a buffer to use, instead of
3974 \"*Process List*\".
3975 The return value is always nil.
3977 This function lists only processes that were launched by Emacs. To
3978 see other processes running on the system, use `list-system-processes'."
3979 (interactive)
3980 (or (fboundp 'process-list)
3981 (error "Asynchronous subprocesses are not supported on this system"))
3982 (unless (bufferp buffer)
3983 (setq buffer (get-buffer-create "*Process List*")))
3984 (with-current-buffer buffer
3985 (process-menu-mode)
3986 (setq process-menu-query-only query-only)
3987 (list-processes--refresh)
3988 (tabulated-list-print))
3989 (display-buffer buffer)
3990 nil)
3992 ;;;; Prefix commands
3994 (setq prefix-command--needs-update nil)
3995 (setq prefix-command--last-echo nil)
3997 (defun internal-echo-keystrokes-prefix ()
3998 ;; BEWARE: Called directly from C code.
3999 ;; If the return value is non-nil, it means we are in the middle of
4000 ;; a command with prefix, such as a command invoked with prefix-arg.
4001 (if (not prefix-command--needs-update)
4002 prefix-command--last-echo
4003 (setq prefix-command--last-echo
4004 (let ((strs nil))
4005 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
4006 (lambda (fun) (push (funcall fun) strs)))
4007 (setq strs (delq nil strs))
4008 (when strs (mapconcat #'identity strs " "))))))
4010 (defvar prefix-command-echo-keystrokes-functions nil
4011 "Abnormal hook which constructs the description of the current prefix state.
4012 Each function is called with no argument, should return a string or nil.")
4014 (defun prefix-command-update ()
4015 "Update state of prefix commands.
4016 Call it whenever you change the \"prefix command state\"."
4017 (setq prefix-command--needs-update t))
4019 (defvar prefix-command-preserve-state-hook nil
4020 "Normal hook run when a command needs to preserve the prefix.")
4022 (defun prefix-command-preserve-state ()
4023 "Pass the current prefix command state to the next command.
4024 Should be called by all prefix commands.
4025 Runs `prefix-command-preserve-state-hook'."
4026 (run-hooks 'prefix-command-preserve-state-hook)
4027 ;; If the current command is a prefix command, we don't want the next (real)
4028 ;; command to have `last-command' set to, say, `universal-argument'.
4029 (setq this-command last-command)
4030 (setq real-this-command real-last-command)
4031 (prefix-command-update))
4033 (defun reset-this-command-lengths ()
4034 (declare (obsolete prefix-command-preserve-state "25.1"))
4035 nil)
4037 ;;;;; The main prefix command.
4039 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4041 (add-hook 'prefix-command-echo-keystrokes-functions
4042 #'universal-argument--description)
4043 (defun universal-argument--description ()
4044 (when prefix-arg
4045 (concat "C-u"
4046 (pcase prefix-arg
4047 (`(-) " -")
4048 (`(,(and (pred integerp) n))
4049 (let ((str ""))
4050 (while (and (> n 4) (= (mod n 4) 0))
4051 (setq str (concat str " C-u"))
4052 (setq n (/ n 4)))
4053 (if (= n 4) str (format " %s" prefix-arg))))
4054 (_ (format " %s" prefix-arg))))))
4056 (add-hook 'prefix-command-preserve-state-hook
4057 #'universal-argument--preserve)
4058 (defun universal-argument--preserve ()
4059 (setq prefix-arg current-prefix-arg))
4061 (defvar universal-argument-map
4062 (let ((map (make-sparse-keymap))
4063 (universal-argument-minus
4064 ;; For backward compatibility, minus with no modifiers is an ordinary
4065 ;; command if digits have already been entered.
4066 `(menu-item "" negative-argument
4067 :filter ,(lambda (cmd)
4068 (if (integerp prefix-arg) nil cmd)))))
4069 (define-key map [switch-frame]
4070 (lambda (e) (interactive "e")
4071 (handle-switch-frame e) (universal-argument--mode)))
4072 (define-key map [?\C-u] 'universal-argument-more)
4073 (define-key map [?-] universal-argument-minus)
4074 (define-key map [?0] 'digit-argument)
4075 (define-key map [?1] 'digit-argument)
4076 (define-key map [?2] 'digit-argument)
4077 (define-key map [?3] 'digit-argument)
4078 (define-key map [?4] 'digit-argument)
4079 (define-key map [?5] 'digit-argument)
4080 (define-key map [?6] 'digit-argument)
4081 (define-key map [?7] 'digit-argument)
4082 (define-key map [?8] 'digit-argument)
4083 (define-key map [?9] 'digit-argument)
4084 (define-key map [kp-0] 'digit-argument)
4085 (define-key map [kp-1] 'digit-argument)
4086 (define-key map [kp-2] 'digit-argument)
4087 (define-key map [kp-3] 'digit-argument)
4088 (define-key map [kp-4] 'digit-argument)
4089 (define-key map [kp-5] 'digit-argument)
4090 (define-key map [kp-6] 'digit-argument)
4091 (define-key map [kp-7] 'digit-argument)
4092 (define-key map [kp-8] 'digit-argument)
4093 (define-key map [kp-9] 'digit-argument)
4094 (define-key map [kp-subtract] universal-argument-minus)
4095 map)
4096 "Keymap used while processing \\[universal-argument].")
4098 (defun universal-argument--mode ()
4099 (prefix-command-update)
4100 (set-transient-map universal-argument-map nil))
4102 (defun universal-argument ()
4103 "Begin a numeric argument for the following command.
4104 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4105 \\[universal-argument] following the digits or minus sign ends the argument.
4106 \\[universal-argument] without digits or minus sign provides 4 as argument.
4107 Repeating \\[universal-argument] without digits or minus sign
4108 multiplies the argument by 4 each time.
4109 For some commands, just \\[universal-argument] by itself serves as a flag
4110 which is different in effect from any particular numeric argument.
4111 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4112 (interactive)
4113 (prefix-command-preserve-state)
4114 (setq prefix-arg (list 4))
4115 (universal-argument--mode))
4117 (defun universal-argument-more (arg)
4118 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4119 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4120 (interactive "P")
4121 (prefix-command-preserve-state)
4122 (setq prefix-arg (if (consp arg)
4123 (list (* 4 (car arg)))
4124 (if (eq arg '-)
4125 (list -4)
4126 arg)))
4127 (when (consp prefix-arg) (universal-argument--mode)))
4129 (defun negative-argument (arg)
4130 "Begin a negative numeric argument for the next command.
4131 \\[universal-argument] following digits or minus sign ends the argument."
4132 (interactive "P")
4133 (prefix-command-preserve-state)
4134 (setq prefix-arg (cond ((integerp arg) (- arg))
4135 ((eq arg '-) nil)
4136 (t '-)))
4137 (universal-argument--mode))
4139 (defun digit-argument (arg)
4140 "Part of the numeric argument for the next command.
4141 \\[universal-argument] following digits or minus sign ends the argument."
4142 (interactive "P")
4143 (prefix-command-preserve-state)
4144 (let* ((char (if (integerp last-command-event)
4145 last-command-event
4146 (get last-command-event 'ascii-character)))
4147 (digit (- (logand char ?\177) ?0)))
4148 (setq prefix-arg (cond ((integerp arg)
4149 (+ (* arg 10)
4150 (if (< arg 0) (- digit) digit)))
4151 ((eq arg '-)
4152 ;; Treat -0 as just -, so that -01 will work.
4153 (if (zerop digit) '- (- digit)))
4155 digit))))
4156 (universal-argument--mode))
4159 (defvar filter-buffer-substring-functions nil
4160 "This variable is a wrapper hook around `buffer-substring--filter'.
4161 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4162 (make-obsolete-variable 'filter-buffer-substring-functions
4163 'filter-buffer-substring-function "24.4")
4165 (defvar filter-buffer-substring-function #'buffer-substring--filter
4166 "Function to perform the filtering in `filter-buffer-substring'.
4167 The function is called with the same 3 arguments (BEG END DELETE)
4168 that `filter-buffer-substring' received. It should return the
4169 buffer substring between BEG and END, after filtering. If DELETE is
4170 non-nil, it should delete the text between BEG and END from the buffer.")
4172 (defvar buffer-substring-filters nil
4173 "List of filter functions for `buffer-substring--filter'.
4174 Each function must accept a single argument, a string, and return a string.
4175 The buffer substring is passed to the first function in the list,
4176 and the return value of each function is passed to the next.
4177 As a special convention, point is set to the start of the buffer text
4178 being operated on (i.e., the first argument of `buffer-substring--filter')
4179 before these functions are called.")
4180 (make-obsolete-variable 'buffer-substring-filters
4181 'filter-buffer-substring-function "24.1")
4183 (defun filter-buffer-substring (beg end &optional delete)
4184 "Return the buffer substring between BEG and END, after filtering.
4185 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4187 This calls the function that `filter-buffer-substring-function' specifies
4188 \(passing the same three arguments that it received) to do the work,
4189 and returns whatever it does. The default function does no filtering,
4190 unless a hook has been set.
4192 Use `filter-buffer-substring' instead of `buffer-substring',
4193 `buffer-substring-no-properties', or `delete-and-extract-region' when
4194 you want to allow filtering to take place. For example, major or minor
4195 modes can use `filter-buffer-substring-function' to extract characters
4196 that are special to a buffer, and should not be copied into other buffers."
4197 (funcall filter-buffer-substring-function beg end delete))
4199 (defun buffer-substring--filter (beg end &optional delete)
4200 "Default function to use for `filter-buffer-substring-function'.
4201 Its arguments and return value are as specified for `filter-buffer-substring'.
4202 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4203 \(see `with-wrapper-hook' for details about wrapper hooks),
4204 and the abnormal hook `buffer-substring-filters'.
4205 No filtering is done unless a hook says to."
4206 (subr--with-wrapper-hook-no-warnings
4207 filter-buffer-substring-functions (beg end delete)
4208 (cond
4209 ((or delete buffer-substring-filters)
4210 (save-excursion
4211 (goto-char beg)
4212 (let ((string (if delete (delete-and-extract-region beg end)
4213 (buffer-substring beg end))))
4214 (dolist (filter buffer-substring-filters)
4215 (setq string (funcall filter string)))
4216 string)))
4218 (buffer-substring beg end)))))
4221 ;;;; Window system cut and paste hooks.
4223 (defvar interprogram-cut-function #'gui-select-text
4224 "Function to call to make a killed region available to other programs.
4225 Most window systems provide a facility for cutting and pasting
4226 text between different programs, such as the clipboard on X and
4227 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4229 This variable holds a function that Emacs calls whenever text is
4230 put in the kill ring, to make the new kill available to other
4231 programs. The function takes one argument, TEXT, which is a
4232 string containing the text which should be made available.")
4234 (defvar interprogram-paste-function #'gui-selection-value
4235 "Function to call to get text cut from other programs.
4236 Most window systems provide a facility for cutting and pasting
4237 text between different programs, such as the clipboard on X and
4238 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4240 This variable holds a function that Emacs calls to obtain text
4241 that other programs have provided for pasting. The function is
4242 called with no arguments. If no other program has provided text
4243 to paste, the function should return nil (in which case the
4244 caller, usually `current-kill', should use the top of the Emacs
4245 kill ring). If another program has provided text to paste, the
4246 function should return that text as a string (in which case the
4247 caller should put this string in the kill ring as the latest
4248 kill).
4250 The function may also return a list of strings if the window
4251 system supports multiple selections. The first string will be
4252 used as the pasted text, but the other will be placed in the kill
4253 ring for easy access via `yank-pop'.
4255 Note that the function should return a string only if a program
4256 other than Emacs has provided a string for pasting; if Emacs
4257 provided the most recent string, the function should return nil.
4258 If it is difficult to tell whether Emacs or some other program
4259 provided the current string, it is probably good enough to return
4260 nil if the string is equal (according to `string=') to the last
4261 text Emacs provided.")
4265 ;;;; The kill ring data structure.
4267 (defvar kill-ring nil
4268 "List of killed text sequences.
4269 Since the kill ring is supposed to interact nicely with cut-and-paste
4270 facilities offered by window systems, use of this variable should
4271 interact nicely with `interprogram-cut-function' and
4272 `interprogram-paste-function'. The functions `kill-new',
4273 `kill-append', and `current-kill' are supposed to implement this
4274 interaction; you may want to use them instead of manipulating the kill
4275 ring directly.")
4277 (defcustom kill-ring-max 60
4278 "Maximum length of kill ring before oldest elements are thrown away."
4279 :type 'integer
4280 :group 'killing)
4282 (defvar kill-ring-yank-pointer nil
4283 "The tail of the kill ring whose car is the last thing yanked.")
4285 (defcustom save-interprogram-paste-before-kill nil
4286 "Save clipboard strings into kill ring before replacing them.
4287 When one selects something in another program to paste it into Emacs,
4288 but kills something in Emacs before actually pasting it,
4289 this selection is gone unless this variable is non-nil,
4290 in which case the other program's selection is saved in the `kill-ring'
4291 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4292 :type 'boolean
4293 :group 'killing
4294 :version "23.2")
4296 (defcustom kill-do-not-save-duplicates nil
4297 "Do not add a new string to `kill-ring' if it duplicates the last one.
4298 The comparison is done using `equal-including-properties'."
4299 :type 'boolean
4300 :group 'killing
4301 :version "23.2")
4303 (defun kill-new (string &optional replace)
4304 "Make STRING the latest kill in the kill ring.
4305 Set `kill-ring-yank-pointer' to point to it.
4306 If `interprogram-cut-function' is non-nil, apply it to STRING.
4307 Optional second argument REPLACE non-nil means that STRING will replace
4308 the front of the kill ring, rather than being added to the list.
4310 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4311 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4312 STRING.
4314 When the yank handler has a non-nil PARAM element, the original STRING
4315 argument is not used by `insert-for-yank'. However, since Lisp code
4316 may access and use elements from the kill ring directly, the STRING
4317 argument should still be a \"useful\" string for such uses."
4318 (unless (and kill-do-not-save-duplicates
4319 ;; Due to text properties such as 'yank-handler that
4320 ;; can alter the contents to yank, comparison using
4321 ;; `equal' is unsafe.
4322 (equal-including-properties string (car kill-ring)))
4323 (if (fboundp 'menu-bar-update-yank-menu)
4324 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4325 (when save-interprogram-paste-before-kill
4326 (let ((interprogram-paste (and interprogram-paste-function
4327 (funcall interprogram-paste-function))))
4328 (when interprogram-paste
4329 (dolist (s (if (listp interprogram-paste)
4330 (nreverse interprogram-paste)
4331 (list interprogram-paste)))
4332 (unless (and kill-do-not-save-duplicates
4333 (equal-including-properties s (car kill-ring)))
4334 (push s kill-ring))))))
4335 (unless (and kill-do-not-save-duplicates
4336 (equal-including-properties string (car kill-ring)))
4337 (if (and replace kill-ring)
4338 (setcar kill-ring string)
4339 (push string kill-ring)
4340 (if (> (length kill-ring) kill-ring-max)
4341 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4342 (setq kill-ring-yank-pointer kill-ring)
4343 (if interprogram-cut-function
4344 (funcall interprogram-cut-function string)))
4346 ;; It has been argued that this should work similar to `self-insert-command'
4347 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4348 (defcustom kill-append-merge-undo nil
4349 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4350 :type 'boolean
4351 :group 'killing
4352 :version "25.1")
4354 (defun kill-append (string before-p)
4355 "Append STRING to the end of the latest kill in the kill ring.
4356 If BEFORE-P is non-nil, prepend STRING to the kill.
4357 Also removes the last undo boundary in the current buffer,
4358 depending on `kill-append-merge-undo'.
4359 If `interprogram-cut-function' is set, pass the resulting kill to it."
4360 (let* ((cur (car kill-ring)))
4361 (kill-new (if before-p (concat string cur) (concat cur string))
4362 (or (= (length cur) 0)
4363 (equal nil (get-text-property 0 'yank-handler cur))))
4364 (when (and kill-append-merge-undo (not buffer-read-only))
4365 (let ((prev buffer-undo-list)
4366 (next (cdr buffer-undo-list)))
4367 ;; find the next undo boundary
4368 (while (car next)
4369 (pop next)
4370 (pop prev))
4371 ;; remove this undo boundary
4372 (when prev
4373 (setcdr prev (cdr next)))))))
4375 (defcustom yank-pop-change-selection nil
4376 "Whether rotating the kill ring changes the window system selection.
4377 If non-nil, whenever the kill ring is rotated (usually via the
4378 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4379 to copy the new kill to the window system selection."
4380 :type 'boolean
4381 :group 'killing
4382 :version "23.1")
4384 (defun current-kill (n &optional do-not-move)
4385 "Rotate the yanking point by N places, and then return that kill.
4386 If N is zero and `interprogram-paste-function' is set to a
4387 function that returns a string or a list of strings, and if that
4388 function doesn't return nil, then that string (or list) is added
4389 to the front of the kill ring and the string (or first string in
4390 the list) is returned as the latest kill.
4392 If N is not zero, and if `yank-pop-change-selection' is
4393 non-nil, use `interprogram-cut-function' to transfer the
4394 kill at the new yank point into the window system selection.
4396 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4397 move the yanking point; just return the Nth kill forward."
4399 (let ((interprogram-paste (and (= n 0)
4400 interprogram-paste-function
4401 (funcall interprogram-paste-function))))
4402 (if interprogram-paste
4403 (progn
4404 ;; Disable the interprogram cut function when we add the new
4405 ;; text to the kill ring, so Emacs doesn't try to own the
4406 ;; selection, with identical text.
4407 (let ((interprogram-cut-function nil))
4408 (if (listp interprogram-paste)
4409 (mapc 'kill-new (nreverse interprogram-paste))
4410 (kill-new interprogram-paste)))
4411 (car kill-ring))
4412 (or kill-ring (error "Kill ring is empty"))
4413 (let ((ARGth-kill-element
4414 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4415 (length kill-ring))
4416 kill-ring)))
4417 (unless do-not-move
4418 (setq kill-ring-yank-pointer ARGth-kill-element)
4419 (when (and yank-pop-change-selection
4420 (> n 0)
4421 interprogram-cut-function)
4422 (funcall interprogram-cut-function (car ARGth-kill-element))))
4423 (car ARGth-kill-element)))))
4427 ;;;; Commands for manipulating the kill ring.
4429 (defcustom kill-read-only-ok nil
4430 "Non-nil means don't signal an error for killing read-only text."
4431 :type 'boolean
4432 :group 'killing)
4434 (defun kill-region (beg end &optional region)
4435 "Kill (\"cut\") text between point and mark.
4436 This deletes the text from the buffer and saves it in the kill ring.
4437 The command \\[yank] can retrieve it from there.
4438 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4440 If you want to append the killed region to the last killed text,
4441 use \\[append-next-kill] before \\[kill-region].
4443 Any command that calls this function is a \"kill command\".
4444 If the previous command was also a kill command,
4445 the text killed this time appends to the text killed last time
4446 to make one entry in the kill ring.
4448 The killed text is filtered by `filter-buffer-substring' before it is
4449 saved in the kill ring, so the actual saved text might be different
4450 from what was killed.
4452 If the buffer is read-only, Emacs will beep and refrain from deleting
4453 the text, but put the text in the kill ring anyway. This means that
4454 you can use the killing commands to copy text from a read-only buffer.
4456 Lisp programs should use this function for killing text.
4457 (To delete text, use `delete-region'.)
4458 Supply two arguments, character positions BEG and END indicating the
4459 stretch of text to be killed. If the optional argument REGION is
4460 non-nil, the function ignores BEG and END, and kills the current
4461 region instead."
4462 ;; Pass mark first, then point, because the order matters when
4463 ;; calling `kill-append'.
4464 (interactive (list (mark) (point) 'region))
4465 (unless (and beg end)
4466 (user-error "The mark is not set now, so there is no region"))
4467 (condition-case nil
4468 (let ((string (if region
4469 (funcall region-extract-function 'delete)
4470 (filter-buffer-substring beg end 'delete))))
4471 (when string ;STRING is nil if BEG = END
4472 ;; Add that string to the kill ring, one way or another.
4473 (if (eq last-command 'kill-region)
4474 (kill-append string (< end beg))
4475 (kill-new string)))
4476 (when (or string (eq last-command 'kill-region))
4477 (setq this-command 'kill-region))
4478 (setq deactivate-mark t)
4479 nil)
4480 ((buffer-read-only text-read-only)
4481 ;; The code above failed because the buffer, or some of the characters
4482 ;; in the region, are read-only.
4483 ;; We should beep, in case the user just isn't aware of this.
4484 ;; However, there's no harm in putting
4485 ;; the region's text in the kill ring, anyway.
4486 (copy-region-as-kill beg end region)
4487 ;; Set this-command now, so it will be set even if we get an error.
4488 (setq this-command 'kill-region)
4489 ;; This should barf, if appropriate, and give us the correct error.
4490 (if kill-read-only-ok
4491 (progn (message "Read only text copied to kill ring") nil)
4492 ;; Signal an error if the buffer is read-only.
4493 (barf-if-buffer-read-only)
4494 ;; If the buffer isn't read-only, the text is.
4495 (signal 'text-read-only (list (current-buffer)))))))
4497 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4498 ;; to get two copies of the text when the user accidentally types M-w and
4499 ;; then corrects it with the intended C-w.
4500 (defun copy-region-as-kill (beg end &optional region)
4501 "Save the region as if killed, but don't kill it.
4502 In Transient Mark mode, deactivate the mark.
4503 If `interprogram-cut-function' is non-nil, also save the text for a window
4504 system cut and paste.
4506 The copied text is filtered by `filter-buffer-substring' before it is
4507 saved in the kill ring, so the actual saved text might be different
4508 from what was in the buffer.
4510 When called from Lisp, save in the kill ring the stretch of text
4511 between BEG and END, unless the optional argument REGION is
4512 non-nil, in which case ignore BEG and END, and save the current
4513 region instead.
4515 This command's old key binding has been given to `kill-ring-save'."
4516 ;; Pass mark first, then point, because the order matters when
4517 ;; calling `kill-append'.
4518 (interactive (list (mark) (point)
4519 (prefix-numeric-value current-prefix-arg)))
4520 (let ((str (if region
4521 (funcall region-extract-function nil)
4522 (filter-buffer-substring beg end))))
4523 (if (eq last-command 'kill-region)
4524 (kill-append str (< end beg))
4525 (kill-new str)))
4526 (setq deactivate-mark t)
4527 nil)
4529 (defun kill-ring-save (beg end &optional region)
4530 "Save the region as if killed, but don't kill it.
4531 In Transient Mark mode, deactivate the mark.
4532 If `interprogram-cut-function' is non-nil, also save the text for a window
4533 system cut and paste.
4535 If you want to append the killed line to the last killed text,
4536 use \\[append-next-kill] before \\[kill-ring-save].
4538 The copied text is filtered by `filter-buffer-substring' before it is
4539 saved in the kill ring, so the actual saved text might be different
4540 from what was in the buffer.
4542 When called from Lisp, save in the kill ring the stretch of text
4543 between BEG and END, unless the optional argument REGION is
4544 non-nil, in which case ignore BEG and END, and save the current
4545 region instead.
4547 This command is similar to `copy-region-as-kill', except that it gives
4548 visual feedback indicating the extent of the region being copied."
4549 ;; Pass mark first, then point, because the order matters when
4550 ;; calling `kill-append'.
4551 (interactive (list (mark) (point)
4552 (prefix-numeric-value current-prefix-arg)))
4553 (copy-region-as-kill beg end region)
4554 ;; This use of called-interactively-p is correct because the code it
4555 ;; controls just gives the user visual feedback.
4556 (if (called-interactively-p 'interactive)
4557 (indicate-copied-region)))
4559 (defun indicate-copied-region (&optional message-len)
4560 "Indicate that the region text has been copied interactively.
4561 If the mark is visible in the selected window, blink the cursor
4562 between point and mark if there is currently no active region
4563 highlighting.
4565 If the mark lies outside the selected window, display an
4566 informative message containing a sample of the copied text. The
4567 optional argument MESSAGE-LEN, if non-nil, specifies the length
4568 of this sample text; it defaults to 40."
4569 (let ((mark (mark t))
4570 (point (point))
4571 ;; Inhibit quitting so we can make a quit here
4572 ;; look like a C-g typed as a command.
4573 (inhibit-quit t))
4574 (if (pos-visible-in-window-p mark (selected-window))
4575 ;; Swap point-and-mark quickly so as to show the region that
4576 ;; was selected. Don't do it if the region is highlighted.
4577 (unless (and (region-active-p)
4578 (face-background 'region))
4579 ;; Swap point and mark.
4580 (set-marker (mark-marker) (point) (current-buffer))
4581 (goto-char mark)
4582 (sit-for blink-matching-delay)
4583 ;; Swap back.
4584 (set-marker (mark-marker) mark (current-buffer))
4585 (goto-char point)
4586 ;; If user quit, deactivate the mark
4587 ;; as C-g would as a command.
4588 (and quit-flag (region-active-p)
4589 (deactivate-mark)))
4590 (let ((len (min (abs (- mark point))
4591 (or message-len 40))))
4592 (if (< point mark)
4593 ;; Don't say "killed"; that is misleading.
4594 (message "Saved text until \"%s\""
4595 (buffer-substring-no-properties (- mark len) mark))
4596 (message "Saved text from \"%s\""
4597 (buffer-substring-no-properties mark (+ mark len))))))))
4599 (defun append-next-kill (&optional interactive)
4600 "Cause following command, if it kills, to add to previous kill.
4601 If the next command kills forward from point, the kill is
4602 appended to the previous killed text. If the command kills
4603 backward, the kill is prepended. Kill commands that act on the
4604 region, such as `kill-region', are regarded as killing forward if
4605 point is after mark, and killing backward if point is before
4606 mark.
4608 If the next command is not a kill command, `append-next-kill' has
4609 no effect.
4611 The argument is used for internal purposes; do not supply one."
4612 (interactive "p")
4613 ;; We don't use (interactive-p), since that breaks kbd macros.
4614 (if interactive
4615 (progn
4616 (setq this-command 'kill-region)
4617 (message "If the next command is a kill, it will append"))
4618 (setq last-command 'kill-region)))
4620 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4621 "Character set that matches bidirectional formatting control characters.")
4623 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4624 "Character set that matches any character except bidirectional controls.")
4626 (defun squeeze-bidi-context-1 (from to category replacement)
4627 "A subroutine of `squeeze-bidi-context'.
4628 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4629 (let ((pt (copy-marker from))
4630 (limit (copy-marker to))
4631 (old-pt 0)
4632 lim1)
4633 (setq lim1 limit)
4634 (goto-char pt)
4635 (while (< pt limit)
4636 (if (> pt old-pt)
4637 (move-marker lim1
4638 (save-excursion
4639 ;; L and R categories include embedding and
4640 ;; override controls, but we don't want to
4641 ;; replace them, because that might change
4642 ;; the visual order. Likewise with PDF and
4643 ;; isolate controls.
4644 (+ pt (skip-chars-forward
4645 bidi-directional-non-controls-chars
4646 limit)))))
4647 ;; Replace any run of non-RTL characters by a single LRM.
4648 (if (null (re-search-forward category lim1 t))
4649 ;; No more characters of CATEGORY, we are done.
4650 (setq pt limit)
4651 (replace-match replacement nil t)
4652 (move-marker pt (point)))
4653 (setq old-pt pt)
4654 ;; Skip directional controls, if any.
4655 (move-marker
4656 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4658 (defun squeeze-bidi-context (from to)
4659 "Replace characters between FROM and TO while keeping bidi context.
4661 This function replaces the region of text with as few characters
4662 as possible, while preserving the effect that region will have on
4663 bidirectional display before and after the region."
4664 (let ((start (set-marker (make-marker)
4665 (if (> from 0) from (+ (point-max) from))))
4666 (end (set-marker (make-marker) to))
4667 ;; This is for when they copy text with read-only text
4668 ;; properties.
4669 (inhibit-read-only t))
4670 (if (null (marker-position end))
4671 (setq end (point-max-marker)))
4672 ;; Replace each run of non-RTL characters with a single LRM.
4673 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4674 ;; Replace each run of non-LTR characters with a single RLM. Note
4675 ;; that the \cR category includes both the Arabic Letter (AL) and
4676 ;; R characters; here we ignore the distinction between them,
4677 ;; because that distinction only affects Arabic Number (AN)
4678 ;; characters, which are weak and don't affect the reordering.
4679 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4681 (defun line-substring-with-bidi-context (start end &optional no-properties)
4682 "Return buffer text between START and END with its bidi context.
4684 START and END are assumed to belong to the same physical line
4685 of buffer text. This function prepends and appends to the text
4686 between START and END bidi control characters that preserve the
4687 visual order of that text when it is inserted at some other place."
4688 (if (or (< start (point-min))
4689 (> end (point-max)))
4690 (signal 'args-out-of-range (list (current-buffer) start end)))
4691 (let ((buf (current-buffer))
4692 substr para-dir from to)
4693 (save-excursion
4694 (goto-char start)
4695 (setq para-dir (current-bidi-paragraph-direction))
4696 (setq from (line-beginning-position)
4697 to (line-end-position))
4698 (goto-char from)
4699 ;; If we don't have any mixed directional characters in the
4700 ;; entire line, we can just copy the substring without adding
4701 ;; any context.
4702 (if (or (looking-at-p "\\CR*$")
4703 (looking-at-p "\\CL*$"))
4704 (setq substr (if no-properties
4705 (buffer-substring-no-properties start end)
4706 (buffer-substring start end)))
4707 (setq substr
4708 (with-temp-buffer
4709 (if no-properties
4710 (insert-buffer-substring-no-properties buf from to)
4711 (insert-buffer-substring buf from to))
4712 (squeeze-bidi-context 1 (1+ (- start from)))
4713 (squeeze-bidi-context (- end to) nil)
4714 (buffer-substring 1 (point-max)))))
4716 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4717 ;; (1) force the string to have the same base embedding
4718 ;; direction as the paragraph direction at the source, no matter
4719 ;; what is the paragraph direction at destination; and (2) avoid
4720 ;; affecting the visual order of the surrounding text at
4721 ;; destination if there are characters of different
4722 ;; directionality there.
4723 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4724 substr "\x2069"))))
4726 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4727 "Return portion of current buffer between START and END with bidi context.
4729 This function works similar to `buffer-substring', but it prepends and
4730 appends to the text bidi directional control characters necessary to
4731 preserve the visual appearance of the text if it is inserted at another
4732 place. This is useful when the buffer substring includes bidirectional
4733 text and control characters that cause non-trivial reordering on display.
4734 If copied verbatim, such text can have a very different visual appearance,
4735 and can also change the visual appearance of the surrounding text at the
4736 destination of the copy.
4738 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4739 the text properties."
4740 (let (line-end substr)
4741 (if (or (< start (point-min))
4742 (> end (point-max)))
4743 (signal 'args-out-of-range (list (current-buffer) start end)))
4744 (save-excursion
4745 (goto-char start)
4746 (setq line-end (min end (line-end-position)))
4747 (while (< start end)
4748 (setq substr
4749 (concat substr
4750 (if substr "\n" "")
4751 (line-substring-with-bidi-context start line-end
4752 no-properties)))
4753 (forward-line 1)
4754 (setq start (point))
4755 (setq line-end (min end (line-end-position))))
4756 substr)))
4758 ;; Yanking.
4760 (defcustom yank-handled-properties
4761 '((font-lock-face . yank-handle-font-lock-face-property)
4762 (category . yank-handle-category-property))
4763 "List of special text property handling conditions for yanking.
4764 Each element should have the form (PROP . FUN), where PROP is a
4765 property symbol and FUN is a function. When the `yank' command
4766 inserts text into the buffer, it scans the inserted text for
4767 stretches of text that have `eq' values of the text property
4768 PROP; for each such stretch of text, FUN is called with three
4769 arguments: the property's value in that text, and the start and
4770 end positions of the text.
4772 This is done prior to removing the properties specified by
4773 `yank-excluded-properties'."
4774 :group 'killing
4775 :type '(repeat (cons (symbol :tag "property symbol")
4776 function))
4777 :version "24.3")
4779 ;; This is actually used in subr.el but defcustom does not work there.
4780 (defcustom yank-excluded-properties
4781 '(category field follow-link fontified font-lock-face help-echo
4782 intangible invisible keymap local-map mouse-face read-only
4783 yank-handler)
4784 "Text properties to discard when yanking.
4785 The value should be a list of text properties to discard or t,
4786 which means to discard all text properties.
4788 See also `yank-handled-properties'."
4789 :type '(choice (const :tag "All" t) (repeat symbol))
4790 :group 'killing
4791 :version "24.3")
4793 (defvar yank-window-start nil)
4794 (defvar yank-undo-function nil
4795 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4796 Function is called with two parameters, START and END corresponding to
4797 the value of the mark and point; it is guaranteed that START <= END.
4798 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4800 (defun yank-pop (&optional arg)
4801 "Replace just-yanked stretch of killed text with a different stretch.
4802 This command is allowed only immediately after a `yank' or a `yank-pop'.
4803 At such a time, the region contains a stretch of reinserted
4804 previously-killed text. `yank-pop' deletes that text and inserts in its
4805 place a different stretch of killed text.
4807 With no argument, the previous kill is inserted.
4808 With argument N, insert the Nth previous kill.
4809 If N is negative, this is a more recent kill.
4811 The sequence of kills wraps around, so that after the oldest one
4812 comes the newest one.
4814 This command honors the `yank-handled-properties' and
4815 `yank-excluded-properties' variables, and the `yank-handler' text
4816 property, in the way that `yank' does."
4817 (interactive "*p")
4818 (if (not (eq last-command 'yank))
4819 (user-error "Previous command was not a yank"))
4820 (setq this-command 'yank)
4821 (unless arg (setq arg 1))
4822 (let ((inhibit-read-only t)
4823 (before (< (point) (mark t))))
4824 (if before
4825 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4826 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4827 (setq yank-undo-function nil)
4828 (set-marker (mark-marker) (point) (current-buffer))
4829 (insert-for-yank (current-kill arg))
4830 ;; Set the window start back where it was in the yank command,
4831 ;; if possible.
4832 (set-window-start (selected-window) yank-window-start t)
4833 (if before
4834 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4835 ;; It is cleaner to avoid activation, even though the command
4836 ;; loop would deactivate the mark because we inserted text.
4837 (goto-char (prog1 (mark t)
4838 (set-marker (mark-marker) (point) (current-buffer))))))
4839 nil)
4841 (defun yank (&optional arg)
4842 "Reinsert (\"paste\") the last stretch of killed text.
4843 More precisely, reinsert the most recent kill, which is the
4844 stretch of killed text most recently killed OR yanked. Put point
4845 at the end, and set mark at the beginning without activating it.
4846 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4847 With argument N, reinsert the Nth most recent kill.
4849 This command honors the `yank-handled-properties' and
4850 `yank-excluded-properties' variables, and the `yank-handler' text
4851 property, as described below.
4853 Properties listed in `yank-handled-properties' are processed,
4854 then those listed in `yank-excluded-properties' are discarded.
4856 If STRING has a non-nil `yank-handler' property anywhere, the
4857 normal insert behavior is altered, and instead, for each contiguous
4858 segment of STRING that has a given value of the `yank-handler'
4859 property, that value is used as follows:
4861 The value of a `yank-handler' property must be a list of one to four
4862 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4863 FUNCTION, if non-nil, should be a function of one argument (the
4864 object to insert); FUNCTION is called instead of `insert'.
4865 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4866 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4867 PARAM may be a list of strings to insert as a rectangle). If PARAM
4868 is nil, then the current segment of STRING is used.
4869 If NOEXCLUDE is present and non-nil, the normal removal of
4870 `yank-excluded-properties' is not performed; instead FUNCTION is
4871 responsible for the removal. This may be necessary if FUNCTION
4872 adjusts point before or after inserting the object.
4873 UNDO, if present and non-nil, should be a function to be called
4874 by `yank-pop' to undo the insertion of the current PARAM. It is
4875 given two arguments, the start and end of the region. FUNCTION
4876 may set `yank-undo-function' to override UNDO.
4878 See also the command `yank-pop' (\\[yank-pop])."
4879 (interactive "*P")
4880 (setq yank-window-start (window-start))
4881 ;; If we don't get all the way thru, make last-command indicate that
4882 ;; for the following command.
4883 (setq this-command t)
4884 (push-mark)
4885 (insert-for-yank (current-kill (cond
4886 ((listp arg) 0)
4887 ((eq arg '-) -2)
4888 (t (1- arg)))))
4889 (if (consp arg)
4890 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4891 ;; It is cleaner to avoid activation, even though the command
4892 ;; loop would deactivate the mark because we inserted text.
4893 (goto-char (prog1 (mark t)
4894 (set-marker (mark-marker) (point) (current-buffer)))))
4895 ;; If we do get all the way thru, make this-command indicate that.
4896 (if (eq this-command t)
4897 (setq this-command 'yank))
4898 nil)
4900 (defun rotate-yank-pointer (arg)
4901 "Rotate the yanking point in the kill ring.
4902 With ARG, rotate that many kills forward (or backward, if negative)."
4903 (interactive "p")
4904 (current-kill arg))
4906 ;; Some kill commands.
4908 ;; Internal subroutine of delete-char
4909 (defun kill-forward-chars (arg)
4910 (if (listp arg) (setq arg (car arg)))
4911 (if (eq arg '-) (setq arg -1))
4912 (kill-region (point) (+ (point) arg)))
4914 ;; Internal subroutine of backward-delete-char
4915 (defun kill-backward-chars (arg)
4916 (if (listp arg) (setq arg (car arg)))
4917 (if (eq arg '-) (setq arg -1))
4918 (kill-region (point) (- (point) arg)))
4920 (defcustom backward-delete-char-untabify-method 'untabify
4921 "The method for untabifying when deleting backward.
4922 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4923 `hungry' -- delete all whitespace, both tabs and spaces;
4924 `all' -- delete all whitespace, including tabs, spaces and newlines;
4925 nil -- just delete one character."
4926 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4927 :version "20.3"
4928 :group 'killing)
4930 (defun backward-delete-char-untabify (arg &optional killp)
4931 "Delete characters backward, changing tabs into spaces.
4932 The exact behavior depends on `backward-delete-char-untabify-method'.
4933 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4934 Interactively, ARG is the prefix arg (default 1)
4935 and KILLP is t if a prefix arg was specified."
4936 (interactive "*p\nP")
4937 (when (eq backward-delete-char-untabify-method 'untabify)
4938 (let ((count arg))
4939 (save-excursion
4940 (while (and (> count 0) (not (bobp)))
4941 (if (= (preceding-char) ?\t)
4942 (let ((col (current-column)))
4943 (forward-char -1)
4944 (setq col (- col (current-column)))
4945 (insert-char ?\s col)
4946 (delete-char 1)))
4947 (forward-char -1)
4948 (setq count (1- count))))))
4949 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4950 ((eq backward-delete-char-untabify-method 'all)
4951 " \t\n\r")))
4952 (n (if skip
4953 (let* ((oldpt (point))
4954 (wh (- oldpt (save-excursion
4955 (skip-chars-backward skip)
4956 (constrain-to-field nil oldpt)))))
4957 (+ arg (if (zerop wh) 0 (1- wh))))
4958 arg)))
4959 ;; Avoid warning about delete-backward-char
4960 (with-no-warnings (delete-backward-char n killp))))
4962 (defun zap-to-char (arg char)
4963 "Kill up to and including ARGth occurrence of CHAR.
4964 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4965 Goes backward if ARG is negative; error if CHAR not found."
4966 (interactive (list (prefix-numeric-value current-prefix-arg)
4967 (read-char "Zap to char: " t)))
4968 ;; Avoid "obsolete" warnings for translation-table-for-input.
4969 (with-no-warnings
4970 (if (char-table-p translation-table-for-input)
4971 (setq char (or (aref translation-table-for-input char) char))))
4972 (kill-region (point) (progn
4973 (search-forward (char-to-string char) nil nil arg)
4974 (point))))
4976 ;; kill-line and its subroutines.
4978 (defcustom kill-whole-line nil
4979 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4980 :type 'boolean
4981 :group 'killing)
4983 (defun kill-line (&optional arg)
4984 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4985 With prefix argument ARG, kill that many lines from point.
4986 Negative arguments kill lines backward.
4987 With zero argument, kills the text before point on the current line.
4989 When calling from a program, nil means \"no arg\",
4990 a number counts as a prefix arg.
4992 To kill a whole line, when point is not at the beginning, type \
4993 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4995 If `show-trailing-whitespace' is non-nil, this command will just
4996 kill the rest of the current line, even if there are no nonblanks
4997 there.
4999 If option `kill-whole-line' is non-nil, then this command kills the whole line
5000 including its terminating newline, when used at the beginning of a line
5001 with no argument. As a consequence, you can always kill a whole line
5002 by typing \\[move-beginning-of-line] \\[kill-line].
5004 If you want to append the killed line to the last killed text,
5005 use \\[append-next-kill] before \\[kill-line].
5007 If the buffer is read-only, Emacs will beep and refrain from deleting
5008 the line, but put the line in the kill ring anyway. This means that
5009 you can use this command to copy text from a read-only buffer.
5010 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5011 even beep.)"
5012 (interactive "P")
5013 (kill-region (point)
5014 ;; It is better to move point to the other end of the kill
5015 ;; before killing. That way, in a read-only buffer, point
5016 ;; moves across the text that is copied to the kill ring.
5017 ;; The choice has no effect on undo now that undo records
5018 ;; the value of point from before the command was run.
5019 (progn
5020 (if arg
5021 (forward-visible-line (prefix-numeric-value arg))
5022 (if (eobp)
5023 (signal 'end-of-buffer nil))
5024 (let ((end
5025 (save-excursion
5026 (end-of-visible-line) (point))))
5027 (if (or (save-excursion
5028 ;; If trailing whitespace is visible,
5029 ;; don't treat it as nothing.
5030 (unless show-trailing-whitespace
5031 (skip-chars-forward " \t" end))
5032 (= (point) end))
5033 (and kill-whole-line (bolp)))
5034 (forward-visible-line 1)
5035 (goto-char end))))
5036 (point))))
5038 (defun kill-whole-line (&optional arg)
5039 "Kill current line.
5040 With prefix ARG, kill that many lines starting from the current line.
5041 If ARG is negative, kill backward. Also kill the preceding newline.
5042 \(This is meant to make \\[repeat] work well with negative arguments.)
5043 If ARG is zero, kill current line but exclude the trailing newline."
5044 (interactive "p")
5045 (or arg (setq arg 1))
5046 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5047 (signal 'end-of-buffer nil))
5048 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5049 (signal 'beginning-of-buffer nil))
5050 (unless (eq last-command 'kill-region)
5051 (kill-new "")
5052 (setq last-command 'kill-region))
5053 (cond ((zerop arg)
5054 ;; We need to kill in two steps, because the previous command
5055 ;; could have been a kill command, in which case the text
5056 ;; before point needs to be prepended to the current kill
5057 ;; ring entry and the text after point appended. Also, we
5058 ;; need to use save-excursion to avoid copying the same text
5059 ;; twice to the kill ring in read-only buffers.
5060 (save-excursion
5061 (kill-region (point) (progn (forward-visible-line 0) (point))))
5062 (kill-region (point) (progn (end-of-visible-line) (point))))
5063 ((< arg 0)
5064 (save-excursion
5065 (kill-region (point) (progn (end-of-visible-line) (point))))
5066 (kill-region (point)
5067 (progn (forward-visible-line (1+ arg))
5068 (unless (bobp) (backward-char))
5069 (point))))
5071 (save-excursion
5072 (kill-region (point) (progn (forward-visible-line 0) (point))))
5073 (kill-region (point)
5074 (progn (forward-visible-line arg) (point))))))
5076 (defun forward-visible-line (arg)
5077 "Move forward by ARG lines, ignoring currently invisible newlines only.
5078 If ARG is negative, move backward -ARG lines.
5079 If ARG is zero, move to the beginning of the current line."
5080 (condition-case nil
5081 (if (> arg 0)
5082 (progn
5083 (while (> arg 0)
5084 (or (zerop (forward-line 1))
5085 (signal 'end-of-buffer nil))
5086 ;; If the newline we just skipped is invisible,
5087 ;; don't count it.
5088 (let ((prop
5089 (get-char-property (1- (point)) 'invisible)))
5090 (if (if (eq buffer-invisibility-spec t)
5091 prop
5092 (or (memq prop buffer-invisibility-spec)
5093 (assq prop buffer-invisibility-spec)))
5094 (setq arg (1+ arg))))
5095 (setq arg (1- arg)))
5096 ;; If invisible text follows, and it is a number of complete lines,
5097 ;; skip it.
5098 (let ((opoint (point)))
5099 (while (and (not (eobp))
5100 (let ((prop
5101 (get-char-property (point) 'invisible)))
5102 (if (eq buffer-invisibility-spec t)
5103 prop
5104 (or (memq prop buffer-invisibility-spec)
5105 (assq prop buffer-invisibility-spec)))))
5106 (goto-char
5107 (if (get-text-property (point) 'invisible)
5108 (or (next-single-property-change (point) 'invisible)
5109 (point-max))
5110 (next-overlay-change (point)))))
5111 (unless (bolp)
5112 (goto-char opoint))))
5113 (let ((first t))
5114 (while (or first (<= arg 0))
5115 (if first
5116 (beginning-of-line)
5117 (or (zerop (forward-line -1))
5118 (signal 'beginning-of-buffer nil)))
5119 ;; If the newline we just moved to is invisible,
5120 ;; don't count it.
5121 (unless (bobp)
5122 (let ((prop
5123 (get-char-property (1- (point)) 'invisible)))
5124 (unless (if (eq buffer-invisibility-spec t)
5125 prop
5126 (or (memq prop buffer-invisibility-spec)
5127 (assq prop buffer-invisibility-spec)))
5128 (setq arg (1+ arg)))))
5129 (setq first nil))
5130 ;; If invisible text follows, and it is a number of complete lines,
5131 ;; skip it.
5132 (let ((opoint (point)))
5133 (while (and (not (bobp))
5134 (let ((prop
5135 (get-char-property (1- (point)) 'invisible)))
5136 (if (eq buffer-invisibility-spec t)
5137 prop
5138 (or (memq prop buffer-invisibility-spec)
5139 (assq prop buffer-invisibility-spec)))))
5140 (goto-char
5141 (if (get-text-property (1- (point)) 'invisible)
5142 (or (previous-single-property-change (point) 'invisible)
5143 (point-min))
5144 (previous-overlay-change (point)))))
5145 (unless (bolp)
5146 (goto-char opoint)))))
5147 ((beginning-of-buffer end-of-buffer)
5148 nil)))
5150 (defun end-of-visible-line ()
5151 "Move to end of current visible line."
5152 (end-of-line)
5153 ;; If the following character is currently invisible,
5154 ;; skip all characters with that same `invisible' property value,
5155 ;; then find the next newline.
5156 (while (and (not (eobp))
5157 (save-excursion
5158 (skip-chars-forward "^\n")
5159 (let ((prop
5160 (get-char-property (point) 'invisible)))
5161 (if (eq buffer-invisibility-spec t)
5162 prop
5163 (or (memq prop buffer-invisibility-spec)
5164 (assq prop buffer-invisibility-spec))))))
5165 (skip-chars-forward "^\n")
5166 (if (get-text-property (point) 'invisible)
5167 (goto-char (or (next-single-property-change (point) 'invisible)
5168 (point-max)))
5169 (goto-char (next-overlay-change (point))))
5170 (end-of-line)))
5172 (defun kill-current-buffer ()
5173 "Kill the current buffer.
5174 When called in the minibuffer, get out of the minibuffer
5175 using `abort-recursive-edit'.
5177 This is like `kill-this-buffer', but it doesn't have to be invoked
5178 via the menu bar, and pays no attention to the menu-bar's frame."
5179 (interactive)
5180 (let ((frame (selected-frame)))
5181 (if (and (frame-live-p frame)
5182 (not (window-minibuffer-p (frame-selected-window frame))))
5183 (kill-buffer (current-buffer))
5184 (abort-recursive-edit))))
5187 (defun insert-buffer (buffer)
5188 "Insert after point the contents of BUFFER.
5189 Puts mark after the inserted text.
5190 BUFFER may be a buffer or a buffer name."
5191 (declare (interactive-only insert-buffer-substring))
5192 (interactive
5193 (list
5194 (progn
5195 (barf-if-buffer-read-only)
5196 (read-buffer "Insert buffer: "
5197 (if (eq (selected-window) (next-window))
5198 (other-buffer (current-buffer))
5199 (window-buffer (next-window)))
5200 t))))
5201 (push-mark
5202 (save-excursion
5203 (insert-buffer-substring (get-buffer buffer))
5204 (point)))
5205 nil)
5207 (defun append-to-buffer (buffer start end)
5208 "Append to specified buffer the text of the region.
5209 It is inserted into that buffer before its point.
5211 When calling from a program, give three arguments:
5212 BUFFER (or buffer name), START and END.
5213 START and END specify the portion of the current buffer to be copied."
5214 (interactive
5215 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5216 (region-beginning) (region-end)))
5217 (let* ((oldbuf (current-buffer))
5218 (append-to (get-buffer-create buffer))
5219 (windows (get-buffer-window-list append-to t t))
5220 point)
5221 (save-excursion
5222 (with-current-buffer append-to
5223 (setq point (point))
5224 (barf-if-buffer-read-only)
5225 (insert-buffer-substring oldbuf start end)
5226 (dolist (window windows)
5227 (when (= (window-point window) point)
5228 (set-window-point window (point))))))))
5230 (defun prepend-to-buffer (buffer start end)
5231 "Prepend to specified buffer the text of the region.
5232 It is inserted into that buffer after its point.
5234 When calling from a program, give three arguments:
5235 BUFFER (or buffer name), START and END.
5236 START and END specify the portion of the current buffer to be copied."
5237 (interactive "BPrepend to buffer: \nr")
5238 (let ((oldbuf (current-buffer)))
5239 (with-current-buffer (get-buffer-create buffer)
5240 (barf-if-buffer-read-only)
5241 (save-excursion
5242 (insert-buffer-substring oldbuf start end)))))
5244 (defun copy-to-buffer (buffer start end)
5245 "Copy to specified buffer the text of the region.
5246 It is inserted into that buffer, replacing existing text there.
5248 When calling from a program, give three arguments:
5249 BUFFER (or buffer name), START and END.
5250 START and END specify the portion of the current buffer to be copied."
5251 (interactive "BCopy to buffer: \nr")
5252 (let ((oldbuf (current-buffer)))
5253 (with-current-buffer (get-buffer-create buffer)
5254 (barf-if-buffer-read-only)
5255 (erase-buffer)
5256 (save-excursion
5257 (insert-buffer-substring oldbuf start end)))))
5259 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5261 (defvar activate-mark-hook nil
5262 "Hook run when the mark becomes active.
5263 It is also run at the end of a command, if the mark is active and
5264 it is possible that the region may have changed.")
5266 (defvar deactivate-mark-hook nil
5267 "Hook run when the mark becomes inactive.")
5269 (defun mark (&optional force)
5270 "Return this buffer's mark value as integer, or nil if never set.
5272 In Transient Mark mode, this function signals an error if
5273 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5274 or the argument FORCE is non-nil, it disregards whether the mark
5275 is active, and returns an integer or nil in the usual way.
5277 If you are using this in an editing command, you are most likely making
5278 a mistake; see the documentation of `set-mark'."
5279 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5280 (marker-position (mark-marker))
5281 (signal 'mark-inactive nil)))
5283 ;; Behind display-selections-p.
5285 (defun deactivate-mark (&optional force)
5286 "Deactivate the mark.
5287 If Transient Mark mode is disabled, this function normally does
5288 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5290 Deactivating the mark sets `mark-active' to nil, updates the
5291 primary selection according to `select-active-regions', and runs
5292 `deactivate-mark-hook'.
5294 If Transient Mark mode was temporarily enabled, reset the value
5295 of the variable `transient-mark-mode'; if this causes Transient
5296 Mark mode to be disabled, don't change `mark-active' to nil or
5297 run `deactivate-mark-hook'."
5298 (when (or (region-active-p) force)
5299 (when (and (if (eq select-active-regions 'only)
5300 (eq (car-safe transient-mark-mode) 'only)
5301 select-active-regions)
5302 (region-active-p)
5303 (display-selections-p))
5304 ;; The var `saved-region-selection', if non-nil, is the text in
5305 ;; the region prior to the last command modifying the buffer.
5306 ;; Set the selection to that, or to the current region.
5307 (cond (saved-region-selection
5308 (if (gui-backend-selection-owner-p 'PRIMARY)
5309 (gui-set-selection 'PRIMARY saved-region-selection))
5310 (setq saved-region-selection nil))
5311 ;; If another program has acquired the selection, region
5312 ;; deactivation should not clobber it (Bug#11772).
5313 ((and (/= (region-beginning) (region-end))
5314 (or (gui-backend-selection-owner-p 'PRIMARY)
5315 (null (gui-backend-selection-exists-p 'PRIMARY))))
5316 (gui-set-selection 'PRIMARY
5317 (funcall region-extract-function nil)))))
5318 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5319 (cond
5320 ((eq (car-safe transient-mark-mode) 'only)
5321 (setq transient-mark-mode (cdr transient-mark-mode))
5322 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5323 (kill-local-variable 'transient-mark-mode)))
5324 ((eq transient-mark-mode 'lambda)
5325 (kill-local-variable 'transient-mark-mode)))
5326 (setq mark-active nil)
5327 (run-hooks 'deactivate-mark-hook)
5328 (redisplay--update-region-highlight (selected-window))))
5330 (defun activate-mark (&optional no-tmm)
5331 "Activate the mark.
5332 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5333 (when (mark t)
5334 (unless (region-active-p)
5335 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5336 (setq mark-active t)
5337 (unless (or transient-mark-mode no-tmm)
5338 (setq-local transient-mark-mode 'lambda))
5339 (run-hooks 'activate-mark-hook))))
5341 (defun set-mark (pos)
5342 "Set this buffer's mark to POS. Don't use this function!
5343 That is to say, don't use this function unless you want
5344 the user to see that the mark has moved, and you want the previous
5345 mark position to be lost.
5347 Normally, when a new mark is set, the old one should go on the stack.
5348 This is why most applications should use `push-mark', not `set-mark'.
5350 Novice Emacs Lisp programmers often try to use the mark for the wrong
5351 purposes. The mark saves a location for the user's convenience.
5352 Most editing commands should not alter the mark.
5353 To remember a location for internal use in the Lisp program,
5354 store it in a Lisp variable. Example:
5356 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5357 (if pos
5358 (progn
5359 (set-marker (mark-marker) pos (current-buffer))
5360 (activate-mark 'no-tmm))
5361 ;; Normally we never clear mark-active except in Transient Mark mode.
5362 ;; But when we actually clear out the mark value too, we must
5363 ;; clear mark-active in any mode.
5364 (deactivate-mark t)
5365 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5366 ;; it should never be nil if the mark is nil.
5367 (setq mark-active nil)
5368 (set-marker (mark-marker) nil)))
5370 (defun save-mark-and-excursion--save ()
5371 (cons
5372 (let ((mark (mark-marker)))
5373 (and (marker-position mark) (copy-marker mark)))
5374 mark-active))
5376 (defun save-mark-and-excursion--restore (saved-mark-info)
5377 (let ((saved-mark (car saved-mark-info))
5378 (omark (marker-position (mark-marker)))
5379 (nmark nil)
5380 (saved-mark-active (cdr saved-mark-info)))
5381 ;; Mark marker
5382 (if (null saved-mark)
5383 (set-marker (mark-marker) nil)
5384 (setf nmark (marker-position saved-mark))
5385 (set-marker (mark-marker) nmark)
5386 (set-marker saved-mark nil))
5387 ;; Mark active
5388 (let ((cur-mark-active mark-active))
5389 (setq mark-active saved-mark-active)
5390 ;; If mark is active now, and either was not active or was at a
5391 ;; different place, run the activate hook.
5392 (if saved-mark-active
5393 (when (or (not cur-mark-active)
5394 (not (eq omark nmark)))
5395 (run-hooks 'activate-mark-hook))
5396 ;; If mark has ceased to be active, run deactivate hook.
5397 (when cur-mark-active
5398 (run-hooks 'deactivate-mark-hook))))))
5400 (defmacro save-mark-and-excursion (&rest body)
5401 "Like `save-excursion', but also save and restore the mark state.
5402 This macro does what `save-excursion' did before Emacs 25.1."
5403 (declare (indent 0) (debug t))
5404 (let ((saved-marker-sym (make-symbol "saved-marker")))
5405 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5406 (unwind-protect
5407 (save-excursion ,@body)
5408 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5410 (defcustom use-empty-active-region nil
5411 "Whether \"region-aware\" commands should act on empty regions.
5412 If nil, region-aware commands treat the empty region as inactive.
5413 If non-nil, region-aware commands treat the region as active as
5414 long as the mark is active, even if the region is empty.
5416 Region-aware commands are those that act on the region if it is
5417 active and Transient Mark mode is enabled, and on the text near
5418 point otherwise."
5419 :type 'boolean
5420 :version "23.1"
5421 :group 'editing-basics)
5423 (defun use-region-p ()
5424 "Return t if the region is active and it is appropriate to act on it.
5425 This is used by commands that act specially on the region under
5426 Transient Mark mode.
5428 The return value is t if Transient Mark mode is enabled and the
5429 mark is active; furthermore, if `use-empty-active-region' is nil,
5430 the region must not be empty. Otherwise, the return value is nil.
5432 For some commands, it may be appropriate to ignore the value of
5433 `use-empty-active-region'; in that case, use `region-active-p'."
5434 (and (region-active-p)
5435 (or use-empty-active-region (> (region-end) (region-beginning)))))
5437 (defun region-active-p ()
5438 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5440 Some commands act specially on the region when Transient Mark
5441 mode is enabled. Usually, such commands should use
5442 `use-region-p' instead of this function, because `use-region-p'
5443 also checks the value of `use-empty-active-region'."
5444 (and transient-mark-mode mark-active
5445 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5446 ;; without the mark being set (e.g. bug#17324). We really should fix
5447 ;; that problem, but in the mean time, let's make sure we don't say the
5448 ;; region is active when there's no mark.
5449 (progn (cl-assert (mark)) t)))
5451 (defun region-bounds ()
5452 "Return the boundaries of the region as a list of (START . END) positions."
5453 (funcall region-extract-function 'bounds))
5455 (defun region-noncontiguous-p ()
5456 "Return non-nil if the region contains several pieces.
5457 An example is a rectangular region handled as a list of
5458 separate contiguous regions for each line."
5459 (> (length (region-bounds)) 1))
5461 (defvar redisplay-unhighlight-region-function
5462 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5464 (defvar redisplay-highlight-region-function
5465 (lambda (start end window rol)
5466 (if (not (overlayp rol))
5467 (let ((nrol (make-overlay start end)))
5468 (funcall redisplay-unhighlight-region-function rol)
5469 (overlay-put nrol 'window window)
5470 (overlay-put nrol 'face 'region)
5471 ;; Normal priority so that a large region doesn't hide all the
5472 ;; overlays within it, but high secondary priority so that if it
5473 ;; ends/starts in the middle of a small overlay, that small overlay
5474 ;; won't hide the region's boundaries.
5475 (overlay-put nrol 'priority '(nil . 100))
5476 nrol)
5477 (unless (and (eq (overlay-buffer rol) (current-buffer))
5478 (eq (overlay-start rol) start)
5479 (eq (overlay-end rol) end))
5480 (move-overlay rol start end (current-buffer)))
5481 rol)))
5483 (defun redisplay--update-region-highlight (window)
5484 (let ((rol (window-parameter window 'internal-region-overlay)))
5485 (if (not (and (region-active-p)
5486 (or highlight-nonselected-windows
5487 (eq window (selected-window))
5488 (and (window-minibuffer-p)
5489 (eq window (minibuffer-selected-window))))))
5490 (funcall redisplay-unhighlight-region-function rol)
5491 (let* ((pt (window-point window))
5492 (mark (mark))
5493 (start (min pt mark))
5494 (end (max pt mark))
5495 (new
5496 (funcall redisplay-highlight-region-function
5497 start end window rol)))
5498 (unless (equal new rol)
5499 (set-window-parameter window 'internal-region-overlay
5500 new))))))
5502 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5503 "Hook run just before redisplay.
5504 It is called in each window that is to be redisplayed. It takes one argument,
5505 which is the window that will be redisplayed. When run, the `current-buffer'
5506 is set to the buffer displayed in that window.")
5508 (defun redisplay--pre-redisplay-functions (windows)
5509 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5510 (if (null windows)
5511 (with-current-buffer (window-buffer (selected-window))
5512 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5513 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5514 (with-current-buffer (window-buffer win)
5515 (run-hook-with-args 'pre-redisplay-functions win))))))
5517 (add-function :before pre-redisplay-function
5518 #'redisplay--pre-redisplay-functions)
5521 (defvar-local mark-ring nil
5522 "The list of former marks of the current buffer, most recent first.")
5523 (put 'mark-ring 'permanent-local t)
5525 (defcustom mark-ring-max 16
5526 "Maximum size of mark ring. Start discarding off end if gets this big."
5527 :type 'integer
5528 :group 'editing-basics)
5530 (defvar global-mark-ring nil
5531 "The list of saved global marks, most recent first.")
5533 (defcustom global-mark-ring-max 16
5534 "Maximum size of global mark ring. \
5535 Start discarding off end if gets this big."
5536 :type 'integer
5537 :group 'editing-basics)
5539 (defun pop-to-mark-command ()
5540 "Jump to mark, and pop a new position for mark off the ring.
5541 \(Does not affect global mark ring)."
5542 (interactive)
5543 (if (null (mark t))
5544 (user-error "No mark set in this buffer")
5545 (if (= (point) (mark t))
5546 (message "Mark popped"))
5547 (goto-char (mark t))
5548 (pop-mark)))
5550 (defun push-mark-command (arg &optional nomsg)
5551 "Set mark at where point is.
5552 If no prefix ARG and mark is already set there, just activate it.
5553 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5554 (interactive "P")
5555 (let ((mark (mark t)))
5556 (if (or arg (null mark) (/= mark (point)))
5557 (push-mark nil nomsg t)
5558 (activate-mark 'no-tmm)
5559 (unless nomsg
5560 (message "Mark activated")))))
5562 (defcustom set-mark-command-repeat-pop nil
5563 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5564 That means that C-u \\[set-mark-command] \\[set-mark-command]
5565 will pop the mark twice, and
5566 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5567 will pop the mark three times.
5569 A value of nil means \\[set-mark-command]'s behavior does not change
5570 after C-u \\[set-mark-command]."
5571 :type 'boolean
5572 :group 'editing-basics)
5574 (defun set-mark-command (arg)
5575 "Set the mark where point is, and activate it; or jump to the mark.
5576 Setting the mark also alters the region, which is the text
5577 between point and mark; this is the closest equivalent in
5578 Emacs to what some editors call the \"selection\".
5580 With no prefix argument, set the mark at point, and push the
5581 old mark position on local mark ring. Also push the new mark on
5582 global mark ring, if the previous mark was set in another buffer.
5584 When Transient Mark Mode is off, immediately repeating this
5585 command activates `transient-mark-mode' temporarily.
5587 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5588 jump to the mark, and set the mark from
5589 position popped off the local mark ring (this does not affect the global
5590 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5591 mark ring (see `pop-global-mark').
5593 If `set-mark-command-repeat-pop' is non-nil, repeating
5594 the \\[set-mark-command] command with no prefix argument pops the next position
5595 off the local (or global) mark ring and jumps there.
5597 With \\[universal-argument] \\[universal-argument] as prefix
5598 argument, unconditionally set mark where point is, even if
5599 `set-mark-command-repeat-pop' is non-nil.
5601 Novice Emacs Lisp programmers often try to use the mark for the wrong
5602 purposes. See the documentation of `set-mark' for more information."
5603 (interactive "P")
5604 (cond ((eq transient-mark-mode 'lambda)
5605 (kill-local-variable 'transient-mark-mode))
5606 ((eq (car-safe transient-mark-mode) 'only)
5607 (deactivate-mark)))
5608 (cond
5609 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5610 (push-mark-command nil))
5611 ((not (eq this-command 'set-mark-command))
5612 (if arg
5613 (pop-to-mark-command)
5614 (push-mark-command t)))
5615 ((and set-mark-command-repeat-pop
5616 (eq last-command 'pop-global-mark)
5617 (not arg))
5618 (setq this-command 'pop-global-mark)
5619 (pop-global-mark))
5620 ((or (and set-mark-command-repeat-pop
5621 (eq last-command 'pop-to-mark-command))
5622 arg)
5623 (setq this-command 'pop-to-mark-command)
5624 (pop-to-mark-command))
5625 ((eq last-command 'set-mark-command)
5626 (if (region-active-p)
5627 (progn
5628 (deactivate-mark)
5629 (message "Mark deactivated"))
5630 (activate-mark)
5631 (message "Mark activated")))
5633 (push-mark-command nil))))
5635 (defun push-mark (&optional location nomsg activate)
5636 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5637 If the last global mark pushed was not in the current buffer,
5638 also push LOCATION on the global mark ring.
5639 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5641 Novice Emacs Lisp programmers often try to use the mark for the wrong
5642 purposes. See the documentation of `set-mark' for more information.
5644 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5645 (unless (null (mark t))
5646 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5647 (when (> (length mark-ring) mark-ring-max)
5648 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5649 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5650 (set-marker (mark-marker) (or location (point)) (current-buffer))
5651 ;; Now push the mark on the global mark ring.
5652 (if (and global-mark-ring
5653 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5654 ;; The last global mark pushed was in this same buffer.
5655 ;; Don't push another one.
5657 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5658 (when (> (length global-mark-ring) global-mark-ring-max)
5659 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5660 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5661 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5662 (message "Mark set"))
5663 (if (or activate (not transient-mark-mode))
5664 (set-mark (mark t)))
5665 nil)
5667 (defun pop-mark ()
5668 "Pop off mark ring into the buffer's actual mark.
5669 Does not set point. Does nothing if mark ring is empty."
5670 (when mark-ring
5671 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5672 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5673 (move-marker (car mark-ring) nil)
5674 (if (null (mark t)) (ding))
5675 (setq mark-ring (cdr mark-ring)))
5676 (deactivate-mark))
5678 (define-obsolete-function-alias
5679 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5680 (defun exchange-point-and-mark (&optional arg)
5681 "Put the mark where point is now, and point where the mark is now.
5682 This command works even when the mark is not active,
5683 and it reactivates the mark.
5685 If Transient Mark mode is on, a prefix ARG deactivates the mark
5686 if it is active, and otherwise avoids reactivating it. If
5687 Transient Mark mode is off, a prefix ARG enables Transient Mark
5688 mode temporarily."
5689 (interactive "P")
5690 (let ((omark (mark t))
5691 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5692 (if (null omark)
5693 (user-error "No mark set in this buffer"))
5694 (set-mark (point))
5695 (goto-char omark)
5696 (cond (temp-highlight
5697 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5698 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5699 (not (or arg (region-active-p))))
5700 (deactivate-mark))
5701 (t (activate-mark)))
5702 nil))
5704 (defcustom shift-select-mode t
5705 "When non-nil, shifted motion keys activate the mark momentarily.
5707 While the mark is activated in this way, any shift-translated point
5708 motion key extends the region, and if Transient Mark mode was off, it
5709 is temporarily turned on. Furthermore, the mark will be deactivated
5710 by any subsequent point motion key that was not shift-translated, or
5711 by any action that normally deactivates the mark in Transient Mark mode.
5713 See `this-command-keys-shift-translated' for the meaning of
5714 shift-translation."
5715 :type 'boolean
5716 :group 'editing-basics)
5718 (defun handle-shift-selection ()
5719 "Activate/deactivate mark depending on invocation thru shift translation.
5720 This function is called by `call-interactively' when a command
5721 with a `^' character in its `interactive' spec is invoked, before
5722 running the command itself.
5724 If `shift-select-mode' is enabled and the command was invoked
5725 through shift translation, set the mark and activate the region
5726 temporarily, unless it was already set in this way. See
5727 `this-command-keys-shift-translated' for the meaning of shift
5728 translation.
5730 Otherwise, if the region has been activated temporarily,
5731 deactivate it, and restore the variable `transient-mark-mode' to
5732 its earlier value."
5733 (cond ((and shift-select-mode this-command-keys-shift-translated)
5734 (unless (and mark-active
5735 (eq (car-safe transient-mark-mode) 'only))
5736 (setq-local transient-mark-mode
5737 (cons 'only
5738 (unless (eq transient-mark-mode 'lambda)
5739 transient-mark-mode)))
5740 (push-mark nil nil t)))
5741 ((eq (car-safe transient-mark-mode) 'only)
5742 (setq transient-mark-mode (cdr transient-mark-mode))
5743 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5744 (kill-local-variable 'transient-mark-mode))
5745 (deactivate-mark))))
5747 (define-minor-mode transient-mark-mode
5748 "Toggle Transient Mark mode.
5749 With a prefix argument ARG, enable Transient Mark mode if ARG is
5750 positive, and disable it otherwise. If called from Lisp, enable
5751 Transient Mark mode if ARG is omitted or nil.
5753 Transient Mark mode is a global minor mode. When enabled, the
5754 region is highlighted with the `region' face whenever the mark
5755 is active. The mark is \"deactivated\" by changing the buffer,
5756 and after certain other operations that set the mark but whose
5757 main purpose is something else--for example, incremental search,
5758 \\[beginning-of-buffer], and \\[end-of-buffer].
5760 You can also deactivate the mark by typing \\[keyboard-quit] or
5761 \\[keyboard-escape-quit].
5763 Many commands change their behavior when Transient Mark mode is
5764 in effect and the mark is active, by acting on the region instead
5765 of their usual default part of the buffer's text. Examples of
5766 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5767 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5768 To see the documentation of commands which are sensitive to the
5769 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5770 or \"mark.*active\" at the prompt."
5771 :global t
5772 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5773 :variable (default-value 'transient-mark-mode))
5775 (defvar widen-automatically t
5776 "Non-nil means it is ok for commands to call `widen' when they want to.
5777 Some commands will do this in order to go to positions outside
5778 the current accessible part of the buffer.
5780 If `widen-automatically' is nil, these commands will do something else
5781 as a fallback, and won't change the buffer bounds.")
5783 (defvar non-essential nil
5784 "Whether the currently executing code is performing an essential task.
5785 This variable should be non-nil only when running code which should not
5786 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5787 user for a password when we are simply scanning a set of files in the
5788 background or displaying possible completions before the user even asked
5789 for it.")
5791 (defun pop-global-mark ()
5792 "Pop off global mark ring and jump to the top location."
5793 (interactive)
5794 ;; Pop entries which refer to non-existent buffers.
5795 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5796 (setq global-mark-ring (cdr global-mark-ring)))
5797 (or global-mark-ring
5798 (error "No global mark set"))
5799 (let* ((marker (car global-mark-ring))
5800 (buffer (marker-buffer marker))
5801 (position (marker-position marker)))
5802 (setq global-mark-ring (nconc (cdr global-mark-ring)
5803 (list (car global-mark-ring))))
5804 (set-buffer buffer)
5805 (or (and (>= position (point-min))
5806 (<= position (point-max)))
5807 (if widen-automatically
5808 (widen)
5809 (error "Global mark position is outside accessible part of buffer")))
5810 (goto-char position)
5811 (switch-to-buffer buffer)))
5813 (defcustom next-line-add-newlines nil
5814 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5815 :type 'boolean
5816 :version "21.1"
5817 :group 'editing-basics)
5819 (defun next-line (&optional arg try-vscroll)
5820 "Move cursor vertically down ARG lines.
5821 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5822 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5823 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5824 function will not vscroll.
5826 ARG defaults to 1.
5828 If there is no character in the target line exactly under the current column,
5829 the cursor is positioned after the character in that line which spans this
5830 column, or at the end of the line if it is not long enough.
5831 If there is no line in the buffer after this one, behavior depends on the
5832 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5833 to create a line, and moves the cursor to that line. Otherwise it moves the
5834 cursor to the end of the buffer.
5836 If the variable `line-move-visual' is non-nil, this command moves
5837 by display lines. Otherwise, it moves by buffer lines, without
5838 taking variable-width characters or continued lines into account.
5839 See \\[next-logical-line] for a command that always moves by buffer lines.
5841 The command \\[set-goal-column] can be used to create
5842 a semipermanent goal column for this command.
5843 Then instead of trying to move exactly vertically (or as close as possible),
5844 this command moves to the specified goal column (or as close as possible).
5845 The goal column is stored in the variable `goal-column', which is nil
5846 when there is no goal column. Note that setting `goal-column'
5847 overrides `line-move-visual' and causes this command to move by buffer
5848 lines rather than by display lines."
5849 (declare (interactive-only forward-line))
5850 (interactive "^p\np")
5851 (or arg (setq arg 1))
5852 (if (and next-line-add-newlines (= arg 1))
5853 (if (save-excursion (end-of-line) (eobp))
5854 ;; When adding a newline, don't expand an abbrev.
5855 (let ((abbrev-mode nil))
5856 (end-of-line)
5857 (insert (if use-hard-newlines hard-newline "\n")))
5858 (line-move arg nil nil try-vscroll))
5859 (if (called-interactively-p 'interactive)
5860 (condition-case err
5861 (line-move arg nil nil try-vscroll)
5862 ((beginning-of-buffer end-of-buffer)
5863 (signal (car err) (cdr err))))
5864 (line-move arg nil nil try-vscroll)))
5865 nil)
5867 (defun previous-line (&optional arg try-vscroll)
5868 "Move cursor vertically up ARG lines.
5869 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5870 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5871 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5872 function will not vscroll.
5874 ARG defaults to 1.
5876 If there is no character in the target line exactly over the current column,
5877 the cursor is positioned after the character in that line which spans this
5878 column, or at the end of the line if it is not long enough.
5880 If the variable `line-move-visual' is non-nil, this command moves
5881 by display lines. Otherwise, it moves by buffer lines, without
5882 taking variable-width characters or continued lines into account.
5883 See \\[previous-logical-line] for a command that always moves by buffer lines.
5885 The command \\[set-goal-column] can be used to create
5886 a semipermanent goal column for this command.
5887 Then instead of trying to move exactly vertically (or as close as possible),
5888 this command moves to the specified goal column (or as close as possible).
5889 The goal column is stored in the variable `goal-column', which is nil
5890 when there is no goal column. Note that setting `goal-column'
5891 overrides `line-move-visual' and causes this command to move by buffer
5892 lines rather than by display lines."
5893 (declare (interactive-only
5894 "use `forward-line' with negative argument instead."))
5895 (interactive "^p\np")
5896 (or arg (setq arg 1))
5897 (if (called-interactively-p 'interactive)
5898 (condition-case err
5899 (line-move (- arg) nil nil try-vscroll)
5900 ((beginning-of-buffer end-of-buffer)
5901 (signal (car err) (cdr err))))
5902 (line-move (- arg) nil nil try-vscroll))
5903 nil)
5905 (defcustom track-eol nil
5906 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5907 This means moving to the end of each line moved onto.
5908 The beginning of a blank line does not count as the end of a line.
5909 This has no effect when the variable `line-move-visual' is non-nil."
5910 :type 'boolean
5911 :group 'editing-basics)
5913 (defcustom goal-column nil
5914 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5915 A non-nil setting overrides the variable `line-move-visual', which see."
5916 :type '(choice integer
5917 (const :tag "None" nil))
5918 :group 'editing-basics)
5919 (make-variable-buffer-local 'goal-column)
5921 (defvar temporary-goal-column 0
5922 "Current goal column for vertical motion.
5923 It is the column where point was at the start of the current run
5924 of vertical motion commands.
5926 When moving by visual lines via the function `line-move-visual', it is a cons
5927 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5928 divided by the default column width, and HSCROLL is the number of
5929 columns by which window is scrolled from left margin.
5931 When the `track-eol' feature is doing its job, the value is
5932 `most-positive-fixnum'.")
5934 (defcustom line-move-ignore-invisible t
5935 "Non-nil means commands that move by lines ignore invisible newlines.
5936 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5937 as if newlines that are invisible didn't exist, and count
5938 only visible newlines. Thus, moving across across 2 newlines
5939 one of which is invisible will be counted as a one-line move.
5940 Also, a non-nil value causes invisible text to be ignored when
5941 counting columns for the purposes of keeping point in the same
5942 column by \\[next-line] and \\[previous-line].
5944 Outline mode sets this."
5945 :type 'boolean
5946 :group 'editing-basics)
5948 (defcustom line-move-visual t
5949 "When non-nil, `line-move' moves point by visual lines.
5950 This movement is based on where the cursor is displayed on the
5951 screen, instead of relying on buffer contents alone. It takes
5952 into account variable-width characters and line continuation.
5953 If nil, `line-move' moves point by logical lines.
5954 A non-nil setting of `goal-column' overrides the value of this variable
5955 and forces movement by logical lines.
5956 A window that is horizontally scrolled also forces movement by logical
5957 lines."
5958 :type 'boolean
5959 :group 'editing-basics
5960 :version "23.1")
5962 ;; Only used if display-graphic-p.
5963 (declare-function font-info "font.c" (name &optional frame))
5965 (defun default-font-height ()
5966 "Return the height in pixels of the current buffer's default face font.
5968 If the default font is remapped (see `face-remapping-alist'), the
5969 function returns the height of the remapped face."
5970 (let ((default-font (face-font 'default)))
5971 (cond
5972 ((and (display-multi-font-p)
5973 ;; Avoid calling font-info if the frame's default font was
5974 ;; not changed since the frame was created. That's because
5975 ;; font-info is expensive for some fonts, see bug #14838.
5976 (not (string= (frame-parameter nil 'font) default-font)))
5977 (aref (font-info default-font) 3))
5978 (t (frame-char-height)))))
5980 (defun default-font-width ()
5981 "Return the width in pixels of the current buffer's default face font.
5983 If the default font is remapped (see `face-remapping-alist'), the
5984 function returns the width of the remapped face."
5985 (let ((default-font (face-font 'default)))
5986 (cond
5987 ((and (display-multi-font-p)
5988 ;; Avoid calling font-info if the frame's default font was
5989 ;; not changed since the frame was created. That's because
5990 ;; font-info is expensive for some fonts, see bug #14838.
5991 (not (string= (frame-parameter nil 'font) default-font)))
5992 (let* ((info (font-info (face-font 'default)))
5993 (width (aref info 11)))
5994 (if (> width 0)
5995 width
5996 (aref info 10))))
5997 (t (frame-char-width)))))
5999 (defun default-line-height ()
6000 "Return the pixel height of current buffer's default-face text line.
6002 The value includes `line-spacing', if any, defined for the buffer
6003 or the frame."
6004 (let ((dfh (default-font-height))
6005 (lsp (if (display-graphic-p)
6006 (or line-spacing
6007 (default-value 'line-spacing)
6008 (frame-parameter nil 'line-spacing)
6010 0)))
6011 (if (floatp lsp)
6012 (setq lsp (truncate (* (frame-char-height) lsp))))
6013 (+ dfh lsp)))
6015 (defun window-screen-lines ()
6016 "Return the number of screen lines in the text area of the selected window.
6018 This is different from `window-text-height' in that this function counts
6019 lines in units of the height of the font used by the default face displayed
6020 in the window, not in units of the frame's default font, and also accounts
6021 for `line-spacing', if any, defined for the window's buffer or frame.
6023 The value is a floating-point number."
6024 (let ((edges (window-inside-pixel-edges))
6025 (dlh (default-line-height)))
6026 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
6028 ;; Returns non-nil if partial move was done.
6029 (defun line-move-partial (arg noerror &optional _to-end)
6030 (if (< arg 0)
6031 ;; Move backward (up).
6032 ;; If already vscrolled, reduce vscroll
6033 (let ((vs (window-vscroll nil t))
6034 (dlh (default-line-height)))
6035 (when (> vs dlh)
6036 (set-window-vscroll nil (- vs dlh) t)))
6038 ;; Move forward (down).
6039 (let* ((lh (window-line-height -1))
6040 (rowh (car lh))
6041 (vpos (nth 1 lh))
6042 (ypos (nth 2 lh))
6043 (rbot (nth 3 lh))
6044 (this-lh (window-line-height))
6045 (this-height (car this-lh))
6046 (this-ypos (nth 2 this-lh))
6047 (dlh (default-line-height))
6048 (wslines (window-screen-lines))
6049 (edges (window-inside-pixel-edges))
6050 (winh (- (nth 3 edges) (nth 1 edges) 1))
6051 py vs last-line)
6052 (if (> (mod wslines 1.0) 0.0)
6053 (setq wslines (round (+ wslines 0.5))))
6054 (when (or (null lh)
6055 (>= rbot dlh)
6056 (<= ypos (- dlh))
6057 (null this-lh)
6058 (<= this-ypos (- dlh)))
6059 (unless lh
6060 (let ((wend (pos-visible-in-window-p t nil t)))
6061 (setq rbot (nth 3 wend)
6062 rowh (nth 4 wend)
6063 vpos (nth 5 wend))))
6064 (unless this-lh
6065 (let ((wstart (pos-visible-in-window-p nil nil t)))
6066 (setq this-ypos (nth 2 wstart)
6067 this-height (nth 4 wstart))))
6068 (setq py
6069 (or (nth 1 this-lh)
6070 (let ((ppos (posn-at-point))
6071 col-row)
6072 (setq col-row (posn-actual-col-row ppos))
6073 (if col-row
6074 (- (cdr col-row) (window-vscroll))
6075 (cdr (posn-col-row ppos))))))
6076 ;; VPOS > 0 means the last line is only partially visible.
6077 ;; But if the part that is visible is at least as tall as the
6078 ;; default font, that means the line is actually fully
6079 ;; readable, and something like line-spacing is hidden. So in
6080 ;; that case we accept the last line in the window as still
6081 ;; visible, and consider the margin as starting one line
6082 ;; later.
6083 (if (and vpos (> vpos 0))
6084 (if (and rowh
6085 (>= rowh (default-font-height))
6086 (< rowh dlh))
6087 (setq last-line (min (- wslines scroll-margin) vpos))
6088 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6089 (cond
6090 ;; If last line of window is fully visible, and vscrolling
6091 ;; more would make this line invisible, move forward.
6092 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6093 (null this-height)
6094 (<= this-height dlh))
6095 (or (null rbot) (= rbot 0)))
6096 nil)
6097 ;; If cursor is not in the bottom scroll margin, and the
6098 ;; current line is is not too tall, move forward.
6099 ((and (or (null this-height) (<= this-height winh))
6100 vpos
6101 (> vpos 0)
6102 (< py last-line))
6103 nil)
6104 ;; When already vscrolled, we vscroll some more if we can,
6105 ;; or clear vscroll and move forward at end of tall image.
6106 ((> vs 0)
6107 (when (or (and rbot (> rbot 0))
6108 (and this-height (> this-height dlh)))
6109 (set-window-vscroll nil (+ vs dlh) t)))
6110 ;; If cursor just entered the bottom scroll margin, move forward,
6111 ;; but also optionally vscroll one line so redisplay won't recenter.
6112 ((and vpos
6113 (> vpos 0)
6114 (= py last-line))
6115 ;; Don't vscroll if the partially-visible line at window
6116 ;; bottom is not too tall (a.k.a. "just one more text
6117 ;; line"): in that case, we do want redisplay to behave
6118 ;; normally, i.e. recenter or whatever.
6120 ;; Note: ROWH + RBOT from the value returned by
6121 ;; pos-visible-in-window-p give the total height of the
6122 ;; partially-visible glyph row at the end of the window. As
6123 ;; we are dealing with floats, we disregard sub-pixel
6124 ;; discrepancies between that and DLH.
6125 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6126 (set-window-vscroll nil dlh t))
6127 (line-move-1 arg noerror)
6129 ;; If there are lines above the last line, scroll-up one line.
6130 ((and vpos (> vpos 0))
6131 (scroll-up 1)
6133 ;; Finally, start vscroll.
6135 (set-window-vscroll nil dlh t)))))))
6138 ;; This is like line-move-1 except that it also performs
6139 ;; vertical scrolling of tall images if appropriate.
6140 ;; That is not really a clean thing to do, since it mixes
6141 ;; scrolling with cursor motion. But so far we don't have
6142 ;; a cleaner solution to the problem of making C-n do something
6143 ;; useful given a tall image.
6144 (defun line-move (arg &optional noerror _to-end try-vscroll)
6145 "Move forward ARG lines.
6146 If NOERROR, don't signal an error if we can't move ARG lines.
6147 TO-END is unused.
6148 TRY-VSCROLL controls whether to vscroll tall lines: if either
6149 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6150 not vscroll."
6151 (if noninteractive
6152 (line-move-1 arg noerror)
6153 (unless (and auto-window-vscroll try-vscroll
6154 ;; Only vscroll for single line moves
6155 (= (abs arg) 1)
6156 ;; Under scroll-conservatively, the display engine
6157 ;; does this better.
6158 (zerop scroll-conservatively)
6159 ;; But don't vscroll in a keyboard macro.
6160 (not defining-kbd-macro)
6161 (not executing-kbd-macro)
6162 (line-move-partial arg noerror))
6163 (set-window-vscroll nil 0 t)
6164 (if (and line-move-visual
6165 ;; Display-based column are incompatible with goal-column.
6166 (not goal-column)
6167 ;; When the text in the window is scrolled to the left,
6168 ;; display-based motion doesn't make sense (because each
6169 ;; logical line occupies exactly one screen line).
6170 (not (> (window-hscroll) 0))
6171 ;; Likewise when the text _was_ scrolled to the left
6172 ;; when the current run of vertical motion commands
6173 ;; started.
6174 (not (and (memq last-command
6175 `(next-line previous-line ,this-command))
6176 auto-hscroll-mode
6177 (numberp temporary-goal-column)
6178 (>= temporary-goal-column
6179 (- (window-width) hscroll-margin)))))
6180 (prog1 (line-move-visual arg noerror)
6181 ;; If we moved into a tall line, set vscroll to make
6182 ;; scrolling through tall images more smooth.
6183 (let ((lh (line-pixel-height))
6184 (edges (window-inside-pixel-edges))
6185 (dlh (default-line-height))
6186 winh)
6187 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6188 (if (and (< arg 0)
6189 (< (point) (window-start))
6190 (> lh winh))
6191 (set-window-vscroll
6193 (- lh dlh) t))))
6194 (line-move-1 arg noerror)))))
6196 ;; Display-based alternative to line-move-1.
6197 ;; Arg says how many lines to move. The value is t if we can move the
6198 ;; specified number of lines.
6199 (defun line-move-visual (arg &optional noerror)
6200 "Move ARG lines forward.
6201 If NOERROR, don't signal an error if we can't move that many lines."
6202 (let ((opoint (point))
6203 (hscroll (window-hscroll))
6204 target-hscroll)
6205 ;; Check if the previous command was a line-motion command, or if
6206 ;; we were called from some other command.
6207 (if (and (consp temporary-goal-column)
6208 (memq last-command `(next-line previous-line ,this-command)))
6209 ;; If so, there's no need to reset `temporary-goal-column',
6210 ;; but we may need to hscroll.
6211 (if (or (/= (cdr temporary-goal-column) hscroll)
6212 (> (cdr temporary-goal-column) 0))
6213 (setq target-hscroll (cdr temporary-goal-column)))
6214 ;; Otherwise, we should reset `temporary-goal-column'.
6215 (let ((posn (posn-at-point))
6216 x-pos)
6217 (cond
6218 ;; Handle the `overflow-newline-into-fringe' case:
6219 ((eq (nth 1 posn) 'right-fringe)
6220 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
6221 ((car (posn-x-y posn))
6222 (setq x-pos (car (posn-x-y posn)))
6223 ;; In R2L lines, the X pixel coordinate is measured from the
6224 ;; left edge of the window, but columns are still counted
6225 ;; from the logical-order beginning of the line, i.e. from
6226 ;; the right edge in this case. We need to adjust for that.
6227 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6228 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6229 (setq temporary-goal-column
6230 (cons (/ (float x-pos)
6231 (frame-char-width))
6232 hscroll)))
6233 (executing-kbd-macro
6234 ;; When we move beyond the first/last character visible in
6235 ;; the window, posn-at-point will return nil, so we need to
6236 ;; approximate the goal column as below.
6237 (setq temporary-goal-column
6238 (mod (current-column) (window-text-width)))))))
6239 (if target-hscroll
6240 (set-window-hscroll (selected-window) target-hscroll))
6241 ;; vertical-motion can move more than it was asked to if it moves
6242 ;; across display strings with newlines. We don't want to ring
6243 ;; the bell and announce beginning/end of buffer in that case.
6244 (or (and (or (and (>= arg 0)
6245 (>= (vertical-motion
6246 (cons (or goal-column
6247 (if (consp temporary-goal-column)
6248 (car temporary-goal-column)
6249 temporary-goal-column))
6250 arg))
6251 arg))
6252 (and (< arg 0)
6253 (<= (vertical-motion
6254 (cons (or goal-column
6255 (if (consp temporary-goal-column)
6256 (car temporary-goal-column)
6257 temporary-goal-column))
6258 arg))
6259 arg)))
6260 (or (>= arg 0)
6261 (/= (point) opoint)
6262 ;; If the goal column lies on a display string,
6263 ;; `vertical-motion' advances the cursor to the end
6264 ;; of the string. For arg < 0, this can cause the
6265 ;; cursor to get stuck. (Bug#3020).
6266 (= (vertical-motion arg) arg)))
6267 (unless noerror
6268 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6269 nil)))))
6271 ;; This is the guts of next-line and previous-line.
6272 ;; Arg says how many lines to move.
6273 ;; The value is t if we can move the specified number of lines.
6274 (defun line-move-1 (arg &optional noerror _to-end)
6275 ;; Don't run any point-motion hooks, and disregard intangibility,
6276 ;; for intermediate positions.
6277 (let ((inhibit-point-motion-hooks t)
6278 (opoint (point))
6279 (orig-arg arg))
6280 (if (consp temporary-goal-column)
6281 (setq temporary-goal-column (+ (car temporary-goal-column)
6282 (cdr temporary-goal-column))))
6283 (unwind-protect
6284 (progn
6285 (if (not (memq last-command '(next-line previous-line)))
6286 (setq temporary-goal-column
6287 (if (and track-eol (eolp)
6288 ;; Don't count beg of empty line as end of line
6289 ;; unless we just did explicit end-of-line.
6290 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6291 most-positive-fixnum
6292 (current-column))))
6294 (if (not (or (integerp selective-display)
6295 line-move-ignore-invisible))
6296 ;; Use just newline characters.
6297 ;; Set ARG to 0 if we move as many lines as requested.
6298 (or (if (> arg 0)
6299 (progn (if (> arg 1) (forward-line (1- arg)))
6300 ;; This way of moving forward ARG lines
6301 ;; verifies that we have a newline after the last one.
6302 ;; It doesn't get confused by intangible text.
6303 (end-of-line)
6304 (if (zerop (forward-line 1))
6305 (setq arg 0)))
6306 (and (zerop (forward-line arg))
6307 (bolp)
6308 (setq arg 0)))
6309 (unless noerror
6310 (signal (if (< arg 0)
6311 'beginning-of-buffer
6312 'end-of-buffer)
6313 nil)))
6314 ;; Move by arg lines, but ignore invisible ones.
6315 (let (done)
6316 (while (and (> arg 0) (not done))
6317 ;; If the following character is currently invisible,
6318 ;; skip all characters with that same `invisible' property value.
6319 (while (and (not (eobp)) (invisible-p (point)))
6320 (goto-char (next-char-property-change (point))))
6321 ;; Move a line.
6322 ;; We don't use `end-of-line', since we want to escape
6323 ;; from field boundaries occurring exactly at point.
6324 (goto-char (constrain-to-field
6325 (let ((inhibit-field-text-motion t))
6326 (line-end-position))
6327 (point) t t
6328 'inhibit-line-move-field-capture))
6329 ;; If there's no invisibility here, move over the newline.
6330 (cond
6331 ((eobp)
6332 (if (not noerror)
6333 (signal 'end-of-buffer nil)
6334 (setq done t)))
6335 ((and (> arg 1) ;; Use vertical-motion for last move
6336 (not (integerp selective-display))
6337 (not (invisible-p (point))))
6338 ;; We avoid vertical-motion when possible
6339 ;; because that has to fontify.
6340 (forward-line 1))
6341 ;; Otherwise move a more sophisticated way.
6342 ((zerop (vertical-motion 1))
6343 (if (not noerror)
6344 (signal 'end-of-buffer nil)
6345 (setq done t))))
6346 (unless done
6347 (setq arg (1- arg))))
6348 ;; The logic of this is the same as the loop above,
6349 ;; it just goes in the other direction.
6350 (while (and (< arg 0) (not done))
6351 ;; For completely consistency with the forward-motion
6352 ;; case, we should call beginning-of-line here.
6353 ;; However, if point is inside a field and on a
6354 ;; continued line, the call to (vertical-motion -1)
6355 ;; below won't move us back far enough; then we return
6356 ;; to the same column in line-move-finish, and point
6357 ;; gets stuck -- cyd
6358 (forward-line 0)
6359 (cond
6360 ((bobp)
6361 (if (not noerror)
6362 (signal 'beginning-of-buffer nil)
6363 (setq done t)))
6364 ((and (< arg -1) ;; Use vertical-motion for last move
6365 (not (integerp selective-display))
6366 (not (invisible-p (1- (point)))))
6367 (forward-line -1))
6368 ((zerop (vertical-motion -1))
6369 (if (not noerror)
6370 (signal 'beginning-of-buffer nil)
6371 (setq done t))))
6372 (unless done
6373 (setq arg (1+ arg))
6374 (while (and ;; Don't move over previous invis lines
6375 ;; if our target is the middle of this line.
6376 (or (zerop (or goal-column temporary-goal-column))
6377 (< arg 0))
6378 (not (bobp)) (invisible-p (1- (point))))
6379 (goto-char (previous-char-property-change (point))))))))
6380 ;; This is the value the function returns.
6381 (= arg 0))
6383 (cond ((> arg 0)
6384 ;; If we did not move down as far as desired, at least go
6385 ;; to end of line. Be sure to call point-entered and
6386 ;; point-left-hooks.
6387 (let* ((npoint (prog1 (line-end-position)
6388 (goto-char opoint)))
6389 (inhibit-point-motion-hooks nil))
6390 (goto-char npoint)))
6391 ((< arg 0)
6392 ;; If we did not move up as far as desired,
6393 ;; at least go to beginning of line.
6394 (let* ((npoint (prog1 (line-beginning-position)
6395 (goto-char opoint)))
6396 (inhibit-point-motion-hooks nil))
6397 (goto-char npoint)))
6399 (line-move-finish (or goal-column temporary-goal-column)
6400 opoint (> orig-arg 0)))))))
6402 (defun line-move-finish (column opoint forward)
6403 (let ((repeat t))
6404 (while repeat
6405 ;; Set REPEAT to t to repeat the whole thing.
6406 (setq repeat nil)
6408 (let (new
6409 (old (point))
6410 (line-beg (line-beginning-position))
6411 (line-end
6412 ;; Compute the end of the line
6413 ;; ignoring effectively invisible newlines.
6414 (save-excursion
6415 ;; Like end-of-line but ignores fields.
6416 (skip-chars-forward "^\n")
6417 (while (and (not (eobp)) (invisible-p (point)))
6418 (goto-char (next-char-property-change (point)))
6419 (skip-chars-forward "^\n"))
6420 (point))))
6422 ;; Move to the desired column.
6423 (if (and line-move-visual
6424 (not (or truncate-lines truncate-partial-width-windows)))
6425 ;; Under line-move-visual, goal-column should be
6426 ;; interpreted in units of the frame's canonical character
6427 ;; width, which is exactly what vertical-motion does.
6428 (vertical-motion (cons column 0))
6429 (line-move-to-column (truncate column)))
6431 ;; Corner case: suppose we start out in a field boundary in
6432 ;; the middle of a continued line. When we get to
6433 ;; line-move-finish, point is at the start of a new *screen*
6434 ;; line but the same text line; then line-move-to-column would
6435 ;; move us backwards. Test using C-n with point on the "x" in
6436 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6437 (and forward
6438 (< (point) old)
6439 (goto-char old))
6441 (setq new (point))
6443 ;; Process intangibility within a line.
6444 ;; With inhibit-point-motion-hooks bound to nil, a call to
6445 ;; goto-char moves point past intangible text.
6447 ;; However, inhibit-point-motion-hooks controls both the
6448 ;; intangibility and the point-entered/point-left hooks. The
6449 ;; following hack avoids calling the point-* hooks
6450 ;; unnecessarily. Note that we move *forward* past intangible
6451 ;; text when the initial and final points are the same.
6452 (goto-char new)
6453 (let ((inhibit-point-motion-hooks nil))
6454 (goto-char new)
6456 ;; If intangibility moves us to a different (later) place
6457 ;; in the same line, use that as the destination.
6458 (if (<= (point) line-end)
6459 (setq new (point))
6460 ;; If that position is "too late",
6461 ;; try the previous allowable position.
6462 ;; See if it is ok.
6463 (backward-char)
6464 (if (if forward
6465 ;; If going forward, don't accept the previous
6466 ;; allowable position if it is before the target line.
6467 (< line-beg (point))
6468 ;; If going backward, don't accept the previous
6469 ;; allowable position if it is still after the target line.
6470 (<= (point) line-end))
6471 (setq new (point))
6472 ;; As a last resort, use the end of the line.
6473 (setq new line-end))))
6475 ;; Now move to the updated destination, processing fields
6476 ;; as well as intangibility.
6477 (goto-char opoint)
6478 (let ((inhibit-point-motion-hooks nil))
6479 (goto-char
6480 ;; Ignore field boundaries if the initial and final
6481 ;; positions have the same `field' property, even if the
6482 ;; fields are non-contiguous. This seems to be "nicer"
6483 ;; behavior in many situations.
6484 (if (eq (get-char-property new 'field)
6485 (get-char-property opoint 'field))
6487 (constrain-to-field new opoint t t
6488 'inhibit-line-move-field-capture))))
6490 ;; If all this moved us to a different line,
6491 ;; retry everything within that new line.
6492 (when (or (< (point) line-beg) (> (point) line-end))
6493 ;; Repeat the intangibility and field processing.
6494 (setq repeat t))))))
6496 (defun line-move-to-column (col)
6497 "Try to find column COL, considering invisibility.
6498 This function works only in certain cases,
6499 because what we really need is for `move-to-column'
6500 and `current-column' to be able to ignore invisible text."
6501 (if (zerop col)
6502 (beginning-of-line)
6503 (move-to-column col))
6505 (when (and line-move-ignore-invisible
6506 (not (bolp)) (invisible-p (1- (point))))
6507 (let ((normal-location (point))
6508 (normal-column (current-column)))
6509 ;; If the following character is currently invisible,
6510 ;; skip all characters with that same `invisible' property value.
6511 (while (and (not (eobp))
6512 (invisible-p (point)))
6513 (goto-char (next-char-property-change (point))))
6514 ;; Have we advanced to a larger column position?
6515 (if (> (current-column) normal-column)
6516 ;; We have made some progress towards the desired column.
6517 ;; See if we can make any further progress.
6518 (line-move-to-column (+ (current-column) (- col normal-column)))
6519 ;; Otherwise, go to the place we originally found
6520 ;; and move back over invisible text.
6521 ;; that will get us to the same place on the screen
6522 ;; but with a more reasonable buffer position.
6523 (goto-char normal-location)
6524 (let ((line-beg
6525 ;; We want the real line beginning, so it's consistent
6526 ;; with bolp below, otherwise we might infloop.
6527 (let ((inhibit-field-text-motion t))
6528 (line-beginning-position))))
6529 (while (and (not (bolp)) (invisible-p (1- (point))))
6530 (goto-char (previous-char-property-change (point) line-beg))))))))
6532 (defun move-end-of-line (arg)
6533 "Move point to end of current line as displayed.
6534 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6535 If point reaches the beginning or end of buffer, it stops there.
6537 To ignore the effects of the `intangible' text or overlay
6538 property, bind `inhibit-point-motion-hooks' to t.
6539 If there is an image in the current line, this function
6540 disregards newlines that are part of the text on which the image
6541 rests."
6542 (interactive "^p")
6543 (or arg (setq arg 1))
6544 (let (done)
6545 (while (not done)
6546 (let ((newpos
6547 (save-excursion
6548 (let ((goal-column 0)
6549 (line-move-visual nil))
6550 (and (line-move arg t)
6551 ;; With bidi reordering, we may not be at bol,
6552 ;; so make sure we are.
6553 (skip-chars-backward "^\n")
6554 (not (bobp))
6555 (progn
6556 (while (and (not (bobp)) (invisible-p (1- (point))))
6557 (goto-char (previous-single-char-property-change
6558 (point) 'invisible)))
6559 (backward-char 1)))
6560 (point)))))
6561 (goto-char newpos)
6562 (if (and (> (point) newpos)
6563 (eq (preceding-char) ?\n))
6564 (backward-char 1)
6565 (if (and (> (point) newpos) (not (eobp))
6566 (not (eq (following-char) ?\n)))
6567 ;; If we skipped something intangible and now we're not
6568 ;; really at eol, keep going.
6569 (setq arg 1)
6570 (setq done t)))))))
6572 (defun move-beginning-of-line (arg)
6573 "Move point to beginning of current line as displayed.
6574 \(If there's an image in the line, this disregards newlines
6575 which are part of the text that the image rests on.)
6577 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6578 If point reaches the beginning or end of buffer, it stops there.
6579 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6580 (interactive "^p")
6581 (or arg (setq arg 1))
6583 (let ((orig (point))
6584 first-vis first-vis-field-value)
6586 ;; Move by lines, if ARG is not 1 (the default).
6587 (if (/= arg 1)
6588 (let ((line-move-visual nil))
6589 (line-move (1- arg) t)))
6591 ;; Move to beginning-of-line, ignoring fields and invisible text.
6592 (skip-chars-backward "^\n")
6593 (while (and (not (bobp)) (invisible-p (1- (point))))
6594 (goto-char (previous-char-property-change (point)))
6595 (skip-chars-backward "^\n"))
6597 ;; Now find first visible char in the line.
6598 (while (and (< (point) orig) (invisible-p (point)))
6599 (goto-char (next-char-property-change (point) orig)))
6600 (setq first-vis (point))
6602 ;; See if fields would stop us from reaching FIRST-VIS.
6603 (setq first-vis-field-value
6604 (constrain-to-field first-vis orig (/= arg 1) t nil))
6606 (goto-char (if (/= first-vis-field-value first-vis)
6607 ;; If yes, obey them.
6608 first-vis-field-value
6609 ;; Otherwise, move to START with attention to fields.
6610 ;; (It is possible that fields never matter in this case.)
6611 (constrain-to-field (point) orig
6612 (/= arg 1) t nil)))))
6615 ;; Many people have said they rarely use this feature, and often type
6616 ;; it by accident. Maybe it shouldn't even be on a key.
6617 (put 'set-goal-column 'disabled t)
6619 (defun set-goal-column (arg)
6620 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6621 Those commands will move to this position in the line moved to
6622 rather than trying to keep the same horizontal position.
6623 With a non-nil argument ARG, clears out the goal column
6624 so that \\[next-line] and \\[previous-line] resume vertical motion.
6625 The goal column is stored in the variable `goal-column'.
6626 This is a buffer-local setting."
6627 (interactive "P")
6628 (if arg
6629 (progn
6630 (setq goal-column nil)
6631 (message "No goal column"))
6632 (setq goal-column (current-column))
6633 ;; The older method below can be erroneous if `set-goal-column' is bound
6634 ;; to a sequence containing %
6635 ;;(message (substitute-command-keys
6636 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6637 ;;goal-column)
6638 (message "%s"
6639 (concat
6640 (format "Goal column %d " goal-column)
6641 (substitute-command-keys
6642 "(use \\[set-goal-column] with an arg to unset it)")))
6645 nil)
6647 ;;; Editing based on visual lines, as opposed to logical lines.
6649 (defun end-of-visual-line (&optional n)
6650 "Move point to end of current visual line.
6651 With argument N not nil or 1, move forward N - 1 visual lines first.
6652 If point reaches the beginning or end of buffer, it stops there.
6653 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6654 (interactive "^p")
6655 (or n (setq n 1))
6656 (if (/= n 1)
6657 (let ((line-move-visual t))
6658 (line-move (1- n) t)))
6659 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6660 ;; constrain to field boundaries, so we don't either.
6661 (vertical-motion (cons (window-width) 0)))
6663 (defun beginning-of-visual-line (&optional n)
6664 "Move point to beginning of current visual line.
6665 With argument N not nil or 1, move forward N - 1 visual lines first.
6666 If point reaches the beginning or end of buffer, it stops there.
6667 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6668 (interactive "^p")
6669 (or n (setq n 1))
6670 (let ((opoint (point)))
6671 (if (/= n 1)
6672 (let ((line-move-visual t))
6673 (line-move (1- n) t)))
6674 (vertical-motion 0)
6675 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6676 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6678 (defun kill-visual-line (&optional arg)
6679 "Kill the rest of the visual line.
6680 With prefix argument ARG, kill that many visual lines from point.
6681 If ARG is negative, kill visual lines backward.
6682 If ARG is zero, kill the text before point on the current visual
6683 line.
6685 If you want to append the killed line to the last killed text,
6686 use \\[append-next-kill] before \\[kill-line].
6688 If the buffer is read-only, Emacs will beep and refrain from deleting
6689 the line, but put the line in the kill ring anyway. This means that
6690 you can use this command to copy text from a read-only buffer.
6691 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6692 even beep.)"
6693 (interactive "P")
6694 ;; Like in `kill-line', it's better to move point to the other end
6695 ;; of the kill before killing.
6696 (let ((opoint (point))
6697 (kill-whole-line (and kill-whole-line (bolp))))
6698 (if arg
6699 (vertical-motion (prefix-numeric-value arg))
6700 (end-of-visual-line 1)
6701 (if (= (point) opoint)
6702 (vertical-motion 1)
6703 ;; Skip any trailing whitespace at the end of the visual line.
6704 ;; We used to do this only if `show-trailing-whitespace' is
6705 ;; nil, but that's wrong; the correct thing would be to check
6706 ;; whether the trailing whitespace is highlighted. But, it's
6707 ;; OK to just do this unconditionally.
6708 (skip-chars-forward " \t")))
6709 (kill-region opoint (if (and kill-whole-line (= (following-char) ?\n))
6710 (1+ (point))
6711 (point)))))
6713 (defun next-logical-line (&optional arg try-vscroll)
6714 "Move cursor vertically down ARG lines.
6715 This is identical to `next-line', except that it always moves
6716 by logical lines instead of visual lines, ignoring the value of
6717 the variable `line-move-visual'."
6718 (interactive "^p\np")
6719 (let ((line-move-visual nil))
6720 (with-no-warnings
6721 (next-line arg try-vscroll))))
6723 (defun previous-logical-line (&optional arg try-vscroll)
6724 "Move cursor vertically up ARG lines.
6725 This is identical to `previous-line', except that it always moves
6726 by logical lines instead of visual lines, ignoring the value of
6727 the variable `line-move-visual'."
6728 (interactive "^p\np")
6729 (let ((line-move-visual nil))
6730 (with-no-warnings
6731 (previous-line arg try-vscroll))))
6733 (defgroup visual-line nil
6734 "Editing based on visual lines."
6735 :group 'convenience
6736 :version "23.1")
6738 (defvar visual-line-mode-map
6739 (let ((map (make-sparse-keymap)))
6740 (define-key map [remap kill-line] 'kill-visual-line)
6741 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6742 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6743 ;; These keybindings interfere with xterm function keys. Are
6744 ;; there any other suitable bindings?
6745 ;; (define-key map "\M-[" 'previous-logical-line)
6746 ;; (define-key map "\M-]" 'next-logical-line)
6747 map))
6749 (defcustom visual-line-fringe-indicators '(nil nil)
6750 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6751 The value should be a list of the form (LEFT RIGHT), where LEFT
6752 and RIGHT are symbols representing the bitmaps to display, to
6753 indicate wrapped lines, in the left and right fringes respectively.
6754 See also `fringe-indicator-alist'.
6755 The default is not to display fringe indicators for wrapped lines.
6756 This variable does not affect fringe indicators displayed for
6757 other purposes."
6758 :type '(list (choice (const :tag "Hide left indicator" nil)
6759 (const :tag "Left curly arrow" left-curly-arrow)
6760 (symbol :tag "Other bitmap"))
6761 (choice (const :tag "Hide right indicator" nil)
6762 (const :tag "Right curly arrow" right-curly-arrow)
6763 (symbol :tag "Other bitmap")))
6764 :set (lambda (symbol value)
6765 (dolist (buf (buffer-list))
6766 (with-current-buffer buf
6767 (when (and (boundp 'visual-line-mode)
6768 (symbol-value 'visual-line-mode))
6769 (setq fringe-indicator-alist
6770 (cons (cons 'continuation value)
6771 (assq-delete-all
6772 'continuation
6773 (copy-tree fringe-indicator-alist)))))))
6774 (set-default symbol value)))
6776 (defvar visual-line--saved-state nil)
6778 (define-minor-mode visual-line-mode
6779 "Toggle visual line based editing (Visual Line mode).
6780 With a prefix argument ARG, enable Visual Line mode if ARG is
6781 positive, and disable it otherwise. If called from Lisp, enable
6782 the mode if ARG is omitted or nil.
6784 When Visual Line mode is enabled, `word-wrap' is turned on in
6785 this buffer, and simple editing commands are redefined to act on
6786 visual lines, not logical lines. See Info node `Visual Line
6787 Mode' for details."
6788 :keymap visual-line-mode-map
6789 :group 'visual-line
6790 :lighter " Wrap"
6791 (if visual-line-mode
6792 (progn
6793 (set (make-local-variable 'visual-line--saved-state) nil)
6794 ;; Save the local values of some variables, to be restored if
6795 ;; visual-line-mode is turned off.
6796 (dolist (var '(line-move-visual truncate-lines
6797 truncate-partial-width-windows
6798 word-wrap fringe-indicator-alist))
6799 (if (local-variable-p var)
6800 (push (cons var (symbol-value var))
6801 visual-line--saved-state)))
6802 (set (make-local-variable 'line-move-visual) t)
6803 (set (make-local-variable 'truncate-partial-width-windows) nil)
6804 (setq truncate-lines nil
6805 word-wrap t
6806 fringe-indicator-alist
6807 (cons (cons 'continuation visual-line-fringe-indicators)
6808 fringe-indicator-alist)))
6809 (kill-local-variable 'line-move-visual)
6810 (kill-local-variable 'word-wrap)
6811 (kill-local-variable 'truncate-lines)
6812 (kill-local-variable 'truncate-partial-width-windows)
6813 (kill-local-variable 'fringe-indicator-alist)
6814 (dolist (saved visual-line--saved-state)
6815 (set (make-local-variable (car saved)) (cdr saved)))
6816 (kill-local-variable 'visual-line--saved-state)))
6818 (defun turn-on-visual-line-mode ()
6819 (visual-line-mode 1))
6821 (define-globalized-minor-mode global-visual-line-mode
6822 visual-line-mode turn-on-visual-line-mode)
6825 (defun transpose-chars (arg)
6826 "Interchange characters around point, moving forward one character.
6827 With prefix arg ARG, effect is to take character before point
6828 and drag it forward past ARG other characters (backward if ARG negative).
6829 If no argument and at end of line, the previous two chars are exchanged."
6830 (interactive "*P")
6831 (when (and (null arg) (eolp) (not (bobp))
6832 (not (get-text-property (1- (point)) 'read-only)))
6833 (forward-char -1))
6834 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6836 (defun transpose-words (arg)
6837 "Interchange words around point, leaving point at end of them.
6838 With prefix arg ARG, effect is to take word before or around point
6839 and drag it forward past ARG other words (backward if ARG negative).
6840 If ARG is zero, the words around or after point and around or after mark
6841 are interchanged."
6842 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6843 (interactive "*p")
6844 (transpose-subr 'forward-word arg))
6846 (defun transpose-sexps (arg)
6847 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6848 Unlike `transpose-words', point must be between the two sexps and not
6849 in the middle of a sexp to be transposed.
6850 With non-zero prefix arg ARG, effect is to take the sexp before point
6851 and drag it forward past ARG other sexps (backward if ARG is negative).
6852 If ARG is zero, the sexps ending at or after point and at or after mark
6853 are interchanged."
6854 (interactive "*p")
6855 (transpose-subr
6856 (lambda (arg)
6857 ;; Here we should try to simulate the behavior of
6858 ;; (cons (progn (forward-sexp x) (point))
6859 ;; (progn (forward-sexp (- x)) (point)))
6860 ;; Except that we don't want to rely on the second forward-sexp
6861 ;; putting us back to where we want to be, since forward-sexp-function
6862 ;; might do funny things like infix-precedence.
6863 (if (if (> arg 0)
6864 (looking-at "\\sw\\|\\s_")
6865 (and (not (bobp))
6866 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6867 ;; Jumping over a symbol. We might be inside it, mind you.
6868 (progn (funcall (if (> arg 0)
6869 'skip-syntax-backward 'skip-syntax-forward)
6870 "w_")
6871 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6872 ;; Otherwise, we're between sexps. Take a step back before jumping
6873 ;; to make sure we'll obey the same precedence no matter which direction
6874 ;; we're going.
6875 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6876 (cons (save-excursion (forward-sexp arg) (point))
6877 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6878 (not (zerop (funcall (if (> arg 0)
6879 'skip-syntax-forward
6880 'skip-syntax-backward)
6881 ".")))))
6882 (point)))))
6883 arg 'special))
6885 (defun transpose-lines (arg)
6886 "Exchange current line and previous line, leaving point after both.
6887 With argument ARG, takes previous line and moves it past ARG lines.
6888 With argument 0, interchanges line point is in with line mark is in."
6889 (interactive "*p")
6890 (transpose-subr (function
6891 (lambda (arg)
6892 (if (> arg 0)
6893 (progn
6894 ;; Move forward over ARG lines,
6895 ;; but create newlines if necessary.
6896 (setq arg (forward-line arg))
6897 (if (/= (preceding-char) ?\n)
6898 (setq arg (1+ arg)))
6899 (if (> arg 0)
6900 (newline arg)))
6901 (forward-line arg))))
6902 arg))
6904 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6905 ;; which seems inconsistent with the ARG /= 0 case.
6906 ;; FIXME document SPECIAL.
6907 (defun transpose-subr (mover arg &optional special)
6908 "Subroutine to do the work of transposing objects.
6909 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6910 moves forward by units of the given object (e.g. forward-sentence,
6911 forward-paragraph). If ARG is zero, exchanges the current object
6912 with the one containing mark. If ARG is an integer, moves the
6913 current object past ARG following (if ARG is positive) or
6914 preceding (if ARG is negative) objects, leaving point after the
6915 current object."
6916 (let ((aux (if special mover
6917 (lambda (x)
6918 (cons (progn (funcall mover x) (point))
6919 (progn (funcall mover (- x)) (point))))))
6920 pos1 pos2)
6921 (cond
6922 ((= arg 0)
6923 (save-excursion
6924 (setq pos1 (funcall aux 1))
6925 (goto-char (or (mark) (error "No mark set in this buffer")))
6926 (setq pos2 (funcall aux 1))
6927 (transpose-subr-1 pos1 pos2))
6928 (exchange-point-and-mark))
6929 ((> arg 0)
6930 (setq pos1 (funcall aux -1))
6931 (setq pos2 (funcall aux arg))
6932 (transpose-subr-1 pos1 pos2)
6933 (goto-char (car pos2)))
6935 (setq pos1 (funcall aux -1))
6936 (goto-char (car pos1))
6937 (setq pos2 (funcall aux arg))
6938 (transpose-subr-1 pos1 pos2)
6939 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6941 (defun transpose-subr-1 (pos1 pos2)
6942 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6943 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6944 (when (> (car pos1) (car pos2))
6945 (let ((swap pos1))
6946 (setq pos1 pos2 pos2 swap)))
6947 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6948 (atomic-change-group
6949 ;; This sequence of insertions attempts to preserve marker
6950 ;; positions at the start and end of the transposed objects.
6951 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6952 (len1 (- (cdr pos1) (car pos1)))
6953 (len2 (length word))
6954 (boundary (make-marker)))
6955 (set-marker boundary (car pos2))
6956 (goto-char (cdr pos1))
6957 (insert-before-markers word)
6958 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6959 (goto-char boundary)
6960 (insert word)
6961 (goto-char (+ boundary len1))
6962 (delete-region (point) (+ (point) len2))
6963 (set-marker boundary nil))))
6965 (defun backward-word (&optional arg)
6966 "Move backward until encountering the beginning of a word.
6967 With argument ARG, do this that many times.
6968 If ARG is omitted or nil, move point backward one word.
6970 The word boundaries are normally determined by the buffer's syntax
6971 table, but `find-word-boundary-function-table', such as set up
6972 by `subword-mode', can change that. If a Lisp program needs to
6973 move by words determined strictly by the syntax table, it should
6974 use `backward-word-strictly' instead."
6975 (interactive "^p")
6976 (forward-word (- (or arg 1))))
6978 (defun mark-word (&optional arg allow-extend)
6979 "Set mark ARG words away from point.
6980 The place mark goes is the same place \\[forward-word] would
6981 move to with the same argument.
6982 Interactively, if this command is repeated
6983 or (in Transient Mark mode) if the mark is active,
6984 it marks the next ARG words after the ones already marked."
6985 (interactive "P\np")
6986 (cond ((and allow-extend
6987 (or (and (eq last-command this-command) (mark t))
6988 (region-active-p)))
6989 (setq arg (if arg (prefix-numeric-value arg)
6990 (if (< (mark) (point)) -1 1)))
6991 (set-mark
6992 (save-excursion
6993 (goto-char (mark))
6994 (forward-word arg)
6995 (point))))
6997 (push-mark
6998 (save-excursion
6999 (forward-word (prefix-numeric-value arg))
7000 (point))
7001 nil t))))
7003 (defun kill-word (arg)
7004 "Kill characters forward until encountering the end of a word.
7005 With argument ARG, do this that many times."
7006 (interactive "p")
7007 (kill-region (point) (progn (forward-word arg) (point))))
7009 (defun backward-kill-word (arg)
7010 "Kill characters backward until encountering the beginning of a word.
7011 With argument ARG, do this that many times."
7012 (interactive "p")
7013 (kill-word (- arg)))
7015 (defun current-word (&optional strict really-word)
7016 "Return the word at or near point, as a string.
7017 The return value includes no text properties.
7019 If optional arg STRICT is non-nil, return nil unless point is
7020 within or adjacent to a word, otherwise look for a word within
7021 point's line. If there is no word anywhere on point's line, the
7022 value is nil regardless of STRICT.
7024 By default, this function treats as a single word any sequence of
7025 characters that have either word or symbol syntax. If optional
7026 arg REALLY-WORD is non-nil, only characters of word syntax can
7027 constitute a word."
7028 (save-excursion
7029 (let* ((oldpoint (point)) (start (point)) (end (point))
7030 (syntaxes (if really-word "w" "w_"))
7031 (not-syntaxes (concat "^" syntaxes)))
7032 (skip-syntax-backward syntaxes) (setq start (point))
7033 (goto-char oldpoint)
7034 (skip-syntax-forward syntaxes) (setq end (point))
7035 (when (and (eq start oldpoint) (eq end oldpoint)
7036 ;; Point is neither within nor adjacent to a word.
7037 (not strict))
7038 ;; Look for preceding word in same line.
7039 (skip-syntax-backward not-syntaxes (line-beginning-position))
7040 (if (bolp)
7041 ;; No preceding word in same line.
7042 ;; Look for following word in same line.
7043 (progn
7044 (skip-syntax-forward not-syntaxes (line-end-position))
7045 (setq start (point))
7046 (skip-syntax-forward syntaxes)
7047 (setq end (point)))
7048 (setq end (point))
7049 (skip-syntax-backward syntaxes)
7050 (setq start (point))))
7051 ;; If we found something nonempty, return it as a string.
7052 (unless (= start end)
7053 (buffer-substring-no-properties start end)))))
7055 (defcustom fill-prefix nil
7056 "String for filling to insert at front of new line, or nil for none."
7057 :type '(choice (const :tag "None" nil)
7058 string)
7059 :group 'fill)
7060 (make-variable-buffer-local 'fill-prefix)
7061 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
7063 (defcustom auto-fill-inhibit-regexp nil
7064 "Regexp to match lines which should not be auto-filled."
7065 :type '(choice (const :tag "None" nil)
7066 regexp)
7067 :group 'fill)
7069 (defun do-auto-fill ()
7070 "The default value for `normal-auto-fill-function'.
7071 This is the default auto-fill function, some major modes use a different one.
7072 Returns t if it really did any work."
7073 (let (fc justify give-up
7074 (fill-prefix fill-prefix))
7075 (if (or (not (setq justify (current-justification)))
7076 (null (setq fc (current-fill-column)))
7077 (and (eq justify 'left)
7078 (<= (current-column) fc))
7079 (and auto-fill-inhibit-regexp
7080 (save-excursion (beginning-of-line)
7081 (looking-at auto-fill-inhibit-regexp))))
7082 nil ;; Auto-filling not required
7083 (if (memq justify '(full center right))
7084 (save-excursion (unjustify-current-line)))
7086 ;; Choose a fill-prefix automatically.
7087 (when (and adaptive-fill-mode
7088 (or (null fill-prefix) (string= fill-prefix "")))
7089 (let ((prefix
7090 (fill-context-prefix
7091 (save-excursion (fill-forward-paragraph -1) (point))
7092 (save-excursion (fill-forward-paragraph 1) (point)))))
7093 (and prefix (not (equal prefix ""))
7094 ;; Use auto-indentation rather than a guessed empty prefix.
7095 (not (and fill-indent-according-to-mode
7096 (string-match "\\`[ \t]*\\'" prefix)))
7097 (setq fill-prefix prefix))))
7099 (while (and (not give-up) (> (current-column) fc))
7100 ;; Determine where to split the line.
7101 (let* (after-prefix
7102 (fill-point
7103 (save-excursion
7104 (beginning-of-line)
7105 (setq after-prefix (point))
7106 (and fill-prefix
7107 (looking-at (regexp-quote fill-prefix))
7108 (setq after-prefix (match-end 0)))
7109 (move-to-column (1+ fc))
7110 (fill-move-to-break-point after-prefix)
7111 (point))))
7113 ;; See whether the place we found is any good.
7114 (if (save-excursion
7115 (goto-char fill-point)
7116 (or (bolp)
7117 ;; There is no use breaking at end of line.
7118 (save-excursion (skip-chars-forward " ") (eolp))
7119 ;; It is futile to split at the end of the prefix
7120 ;; since we would just insert the prefix again.
7121 (and after-prefix (<= (point) after-prefix))
7122 ;; Don't split right after a comment starter
7123 ;; since we would just make another comment starter.
7124 (and comment-start-skip
7125 (let ((limit (point)))
7126 (beginning-of-line)
7127 (and (re-search-forward comment-start-skip
7128 limit t)
7129 (eq (point) limit))))))
7130 ;; No good place to break => stop trying.
7131 (setq give-up t)
7132 ;; Ok, we have a useful place to break the line. Do it.
7133 (let ((prev-column (current-column)))
7134 ;; If point is at the fill-point, do not `save-excursion'.
7135 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7136 ;; point will end up before it rather than after it.
7137 (if (save-excursion
7138 (skip-chars-backward " \t")
7139 (= (point) fill-point))
7140 (default-indent-new-line t)
7141 (save-excursion
7142 (goto-char fill-point)
7143 (default-indent-new-line t)))
7144 ;; Now do justification, if required
7145 (if (not (eq justify 'left))
7146 (save-excursion
7147 (end-of-line 0)
7148 (justify-current-line justify nil t)))
7149 ;; If making the new line didn't reduce the hpos of
7150 ;; the end of the line, then give up now;
7151 ;; trying again will not help.
7152 (if (>= (current-column) prev-column)
7153 (setq give-up t))))))
7154 ;; Justify last line.
7155 (justify-current-line justify t t)
7156 t)))
7158 (defvar comment-line-break-function 'comment-indent-new-line
7159 "Mode-specific function which line breaks and continues a comment.
7160 This function is called during auto-filling when a comment syntax
7161 is defined.
7162 The function should take a single optional argument, which is a flag
7163 indicating whether it should use soft newlines.")
7165 (defun default-indent-new-line (&optional soft)
7166 "Break line at point and indent.
7167 If a comment syntax is defined, call `comment-indent-new-line'.
7169 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7170 unless optional argument SOFT is non-nil."
7171 (interactive)
7172 (if comment-start
7173 (funcall comment-line-break-function soft)
7174 ;; Insert the newline before removing empty space so that markers
7175 ;; get preserved better.
7176 (if soft (insert-and-inherit ?\n) (newline 1))
7177 (save-excursion (forward-char -1) (delete-horizontal-space))
7178 (delete-horizontal-space)
7180 (if (and fill-prefix (not adaptive-fill-mode))
7181 ;; Blindly trust a non-adaptive fill-prefix.
7182 (progn
7183 (indent-to-left-margin)
7184 (insert-before-markers-and-inherit fill-prefix))
7186 (cond
7187 ;; If there's an adaptive prefix, use it unless we're inside
7188 ;; a comment and the prefix is not a comment starter.
7189 (fill-prefix
7190 (indent-to-left-margin)
7191 (insert-and-inherit fill-prefix))
7192 ;; If we're not inside a comment, just try to indent.
7193 (t (indent-according-to-mode))))))
7195 (defvar normal-auto-fill-function 'do-auto-fill
7196 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7197 Some major modes set this.")
7199 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7200 ;; `functions' and `hooks' are usually unsafe to set, but setting
7201 ;; auto-fill-function to nil in a file-local setting is safe and
7202 ;; can be useful to prevent auto-filling.
7203 (put 'auto-fill-function 'safe-local-variable 'null)
7205 (define-minor-mode auto-fill-mode
7206 "Toggle automatic line breaking (Auto Fill mode).
7207 With a prefix argument ARG, enable Auto Fill mode if ARG is
7208 positive, and disable it otherwise. If called from Lisp, enable
7209 the mode if ARG is omitted or nil.
7211 When Auto Fill mode is enabled, inserting a space at a column
7212 beyond `current-fill-column' automatically breaks the line at a
7213 previous space.
7215 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7216 non-nil.
7218 The value of `normal-auto-fill-function' specifies the function to use
7219 for `auto-fill-function' when turning Auto Fill mode on."
7220 :variable (auto-fill-function
7221 . (lambda (v) (setq auto-fill-function
7222 (if v normal-auto-fill-function)))))
7224 ;; This holds a document string used to document auto-fill-mode.
7225 (defun auto-fill-function ()
7226 "Automatically break line at a previous space, in insertion of text."
7227 nil)
7229 (defun turn-on-auto-fill ()
7230 "Unconditionally turn on Auto Fill mode."
7231 (auto-fill-mode 1))
7233 (defun turn-off-auto-fill ()
7234 "Unconditionally turn off Auto Fill mode."
7235 (auto-fill-mode -1))
7237 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7239 (defun set-fill-column (arg)
7240 "Set `fill-column' to specified argument.
7241 Use \\[universal-argument] followed by a number to specify a column.
7242 Just \\[universal-argument] as argument means to use the current column."
7243 (interactive
7244 (list (or current-prefix-arg
7245 ;; We used to use current-column silently, but C-x f is too easily
7246 ;; typed as a typo for C-x C-f, so we turned it into an error and
7247 ;; now an interactive prompt.
7248 (read-number "Set fill-column to: " (current-column)))))
7249 (if (consp arg)
7250 (setq arg (current-column)))
7251 (if (not (integerp arg))
7252 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7253 (error "set-fill-column requires an explicit argument")
7254 (message "Fill column set to %d (was %d)" arg fill-column)
7255 (setq fill-column arg)))
7257 (defun set-selective-display (arg)
7258 "Set `selective-display' to ARG; clear it if no arg.
7259 When the value of `selective-display' is a number > 0,
7260 lines whose indentation is >= that value are not displayed.
7261 The variable `selective-display' has a separate value for each buffer."
7262 (interactive "P")
7263 (if (eq selective-display t)
7264 (error "selective-display already in use for marked lines"))
7265 (let ((current-vpos
7266 (save-restriction
7267 (narrow-to-region (point-min) (point))
7268 (goto-char (window-start))
7269 (vertical-motion (window-height)))))
7270 (setq selective-display
7271 (and arg (prefix-numeric-value arg)))
7272 (recenter current-vpos))
7273 (set-window-start (selected-window) (window-start))
7274 (princ "selective-display set to " t)
7275 (prin1 selective-display t)
7276 (princ "." t))
7278 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7280 (defun toggle-truncate-lines (&optional arg)
7281 "Toggle truncating of long lines for the current buffer.
7282 When truncating is off, long lines are folded.
7283 With prefix argument ARG, truncate long lines if ARG is positive,
7284 otherwise fold them. Note that in side-by-side windows, this
7285 command has no effect if `truncate-partial-width-windows' is
7286 non-nil."
7287 (interactive "P")
7288 (setq truncate-lines
7289 (if (null arg)
7290 (not truncate-lines)
7291 (> (prefix-numeric-value arg) 0)))
7292 (force-mode-line-update)
7293 (unless truncate-lines
7294 (let ((buffer (current-buffer)))
7295 (walk-windows (lambda (window)
7296 (if (eq buffer (window-buffer window))
7297 (set-window-hscroll window 0)))
7298 nil t)))
7299 (message "Truncate long lines %s"
7300 (if truncate-lines "enabled" "disabled")))
7302 (defun toggle-word-wrap (&optional arg)
7303 "Toggle whether to use word-wrapping for continuation lines.
7304 With prefix argument ARG, wrap continuation lines at word boundaries
7305 if ARG is positive, otherwise wrap them at the right screen edge.
7306 This command toggles the value of `word-wrap'. It has no effect
7307 if long lines are truncated."
7308 (interactive "P")
7309 (setq word-wrap
7310 (if (null arg)
7311 (not word-wrap)
7312 (> (prefix-numeric-value arg) 0)))
7313 (force-mode-line-update)
7314 (message "Word wrapping %s"
7315 (if word-wrap "enabled" "disabled")))
7317 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7318 "The string displayed in the mode line when in overwrite mode.")
7319 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7320 "The string displayed in the mode line when in binary overwrite mode.")
7322 (define-minor-mode overwrite-mode
7323 "Toggle Overwrite mode.
7324 With a prefix argument ARG, enable Overwrite mode if ARG is
7325 positive, and disable it otherwise. If called from Lisp, enable
7326 the mode if ARG is omitted or nil.
7328 When Overwrite mode is enabled, printing characters typed in
7329 replace existing text on a one-for-one basis, rather than pushing
7330 it to the right. At the end of a line, such characters extend
7331 the line. Before a tab, such characters insert until the tab is
7332 filled in. \\[quoted-insert] still inserts characters in
7333 overwrite mode; this is supposed to make it easier to insert
7334 characters when necessary."
7335 :variable (overwrite-mode
7336 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7338 (define-minor-mode binary-overwrite-mode
7339 "Toggle Binary Overwrite mode.
7340 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7341 is positive, and disable it otherwise. If called from Lisp,
7342 enable the mode if ARG is omitted or nil.
7344 When Binary Overwrite mode is enabled, printing characters typed
7345 in replace existing text. Newlines are not treated specially, so
7346 typing at the end of a line joins the line to the next, with the
7347 typed character between them. Typing before a tab character
7348 simply replaces the tab with the character typed.
7349 \\[quoted-insert] replaces the text at the cursor, just as
7350 ordinary typing characters do.
7352 Note that Binary Overwrite mode is not its own minor mode; it is
7353 a specialization of overwrite mode, entered by setting the
7354 `overwrite-mode' variable to `overwrite-mode-binary'."
7355 :variable (overwrite-mode
7356 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7358 (define-minor-mode line-number-mode
7359 "Toggle line number display in the mode line (Line Number mode).
7360 With a prefix argument ARG, enable Line Number mode if ARG is
7361 positive, and disable it otherwise. If called from Lisp, enable
7362 the mode if ARG is omitted or nil.
7364 Line numbers do not appear for very large buffers and buffers
7365 with very long lines; see variables `line-number-display-limit'
7366 and `line-number-display-limit-width'."
7367 :init-value t :global t :group 'mode-line)
7369 (define-minor-mode column-number-mode
7370 "Toggle column number display in the mode line (Column Number mode).
7371 With a prefix argument ARG, enable Column Number mode if ARG is
7372 positive, and disable it otherwise.
7374 If called from Lisp, enable the mode if ARG is omitted or nil."
7375 :global t :group 'mode-line)
7377 (define-minor-mode size-indication-mode
7378 "Toggle buffer size display in the mode line (Size Indication mode).
7379 With a prefix argument ARG, enable Size Indication mode if ARG is
7380 positive, and disable it otherwise.
7382 If called from Lisp, enable the mode if ARG is omitted or nil."
7383 :global t :group 'mode-line)
7385 (define-minor-mode auto-save-mode
7386 "Toggle auto-saving in the current buffer (Auto Save mode).
7387 With a prefix argument ARG, enable Auto Save mode if ARG is
7388 positive, and disable it otherwise.
7390 If called from Lisp, enable the mode if ARG is omitted or nil."
7391 :variable ((and buffer-auto-save-file-name
7392 ;; If auto-save is off because buffer has shrunk,
7393 ;; then toggling should turn it on.
7394 (>= buffer-saved-size 0))
7395 . (lambda (val)
7396 (setq buffer-auto-save-file-name
7397 (cond
7398 ((null val) nil)
7399 ((and buffer-file-name auto-save-visited-file-name
7400 (not buffer-read-only))
7401 buffer-file-name)
7402 (t (make-auto-save-file-name))))))
7403 ;; If -1 was stored here, to temporarily turn off saving,
7404 ;; turn it back on.
7405 (and (< buffer-saved-size 0)
7406 (setq buffer-saved-size 0)))
7408 (defgroup paren-blinking nil
7409 "Blinking matching of parens and expressions."
7410 :prefix "blink-matching-"
7411 :group 'paren-matching)
7413 (defcustom blink-matching-paren t
7414 "Non-nil means show matching open-paren when close-paren is inserted.
7415 If t, highlight the paren. If `jump', briefly move cursor to its
7416 position. If `jump-offscreen', move cursor there even if the
7417 position is off screen. With any other non-nil value, the
7418 off-screen position of the opening paren will be shown in the
7419 echo area."
7420 :type '(choice
7421 (const :tag "Disable" nil)
7422 (const :tag "Highlight" t)
7423 (const :tag "Move cursor" jump)
7424 (const :tag "Move cursor, even if off screen" jump-offscreen))
7425 :group 'paren-blinking)
7427 (defcustom blink-matching-paren-on-screen t
7428 "Non-nil means show matching open-paren when it is on screen.
7429 If nil, don't show it (but the open-paren can still be shown
7430 in the echo area when it is off screen).
7432 This variable has no effect if `blink-matching-paren' is nil.
7433 \(In that case, the open-paren is never shown.)
7434 It is also ignored if `show-paren-mode' is enabled."
7435 :type 'boolean
7436 :group 'paren-blinking)
7438 (defcustom blink-matching-paren-distance (* 100 1024)
7439 "If non-nil, maximum distance to search backwards for matching open-paren.
7440 If nil, search stops at the beginning of the accessible portion of the buffer."
7441 :version "23.2" ; 25->100k
7442 :type '(choice (const nil) integer)
7443 :group 'paren-blinking)
7445 (defcustom blink-matching-delay 1
7446 "Time in seconds to delay after showing a matching paren."
7447 :type 'number
7448 :group 'paren-blinking)
7450 (defcustom blink-matching-paren-dont-ignore-comments nil
7451 "If nil, `blink-matching-paren' ignores comments.
7452 More precisely, when looking for the matching parenthesis,
7453 it skips the contents of comments that end before point."
7454 :type 'boolean
7455 :group 'paren-blinking)
7457 (defun blink-matching-check-mismatch (start end)
7458 "Return whether or not START...END are matching parens.
7459 END is the current point and START is the blink position.
7460 START might be nil if no matching starter was found.
7461 Returns non-nil if we find there is a mismatch."
7462 (let* ((end-syntax (syntax-after (1- end)))
7463 (matching-paren (and (consp end-syntax)
7464 (eq (syntax-class end-syntax) 5)
7465 (cdr end-syntax))))
7466 ;; For self-matched chars like " and $, we can't know when they're
7467 ;; mismatched or unmatched, so we can only do it for parens.
7468 (when matching-paren
7469 (not (and start
7471 (eq (char-after start) matching-paren)
7472 ;; The cdr might hold a new paren-class info rather than
7473 ;; a matching-char info, in which case the two CDRs
7474 ;; should match.
7475 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7477 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7478 "Function to check parentheses mismatches.
7479 The function takes two arguments (START and END) where START is the
7480 position just before the opening token and END is the position right after.
7481 START can be nil, if it was not found.
7482 The function should return non-nil if the two tokens do not match.")
7484 (defvar blink-matching--overlay
7485 (let ((ol (make-overlay (point) (point) nil t)))
7486 (overlay-put ol 'face 'show-paren-match)
7487 (delete-overlay ol)
7489 "Overlay used to highlight the matching paren.")
7491 (defun blink-matching-open ()
7492 "Momentarily highlight the beginning of the sexp before point."
7493 (interactive)
7494 (when (and (not (bobp))
7495 blink-matching-paren)
7496 (let* ((oldpos (point))
7497 (message-log-max nil) ; Don't log messages about paren matching.
7498 (blinkpos
7499 (save-excursion
7500 (save-restriction
7501 (if blink-matching-paren-distance
7502 (narrow-to-region
7503 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7504 (- (point) blink-matching-paren-distance))
7505 oldpos))
7506 (let ((parse-sexp-ignore-comments
7507 (and parse-sexp-ignore-comments
7508 (not blink-matching-paren-dont-ignore-comments))))
7509 (condition-case ()
7510 (progn
7511 (syntax-propertize (point))
7512 (forward-sexp -1)
7513 ;; backward-sexp skips backward over prefix chars,
7514 ;; so move back to the matching paren.
7515 (while (and (< (point) (1- oldpos))
7516 (let ((code (syntax-after (point))))
7517 (or (eq (syntax-class code) 6)
7518 (eq (logand 1048576 (car code))
7519 1048576))))
7520 (forward-char 1))
7521 (point))
7522 (error nil))))))
7523 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7524 (cond
7525 (mismatch
7526 (if blinkpos
7527 (if (minibufferp)
7528 (minibuffer-message "Mismatched parentheses")
7529 (message "Mismatched parentheses"))
7530 (if (minibufferp)
7531 (minibuffer-message "No matching parenthesis found")
7532 (message "No matching parenthesis found"))))
7533 ((not blinkpos) nil)
7534 ((or
7535 (eq blink-matching-paren 'jump-offscreen)
7536 (pos-visible-in-window-p blinkpos))
7537 ;; Matching open within window, temporarily move to or highlight
7538 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7539 ;; is non-nil.
7540 (and blink-matching-paren-on-screen
7541 (not show-paren-mode)
7542 (if (memq blink-matching-paren '(jump jump-offscreen))
7543 (save-excursion
7544 (goto-char blinkpos)
7545 (sit-for blink-matching-delay))
7546 (unwind-protect
7547 (progn
7548 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7549 (current-buffer))
7550 (sit-for blink-matching-delay))
7551 (delete-overlay blink-matching--overlay)))))
7553 (let ((open-paren-line-string
7554 (save-excursion
7555 (goto-char blinkpos)
7556 ;; Show what precedes the open in its line, if anything.
7557 (cond
7558 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7559 (buffer-substring (line-beginning-position)
7560 (1+ blinkpos)))
7561 ;; Show what follows the open in its line, if anything.
7562 ((save-excursion
7563 (forward-char 1)
7564 (skip-chars-forward " \t")
7565 (not (eolp)))
7566 (buffer-substring blinkpos
7567 (line-end-position)))
7568 ;; Otherwise show the previous nonblank line,
7569 ;; if there is one.
7570 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7571 (concat
7572 (buffer-substring (progn
7573 (skip-chars-backward "\n \t")
7574 (line-beginning-position))
7575 (progn (end-of-line)
7576 (skip-chars-backward " \t")
7577 (point)))
7578 ;; Replace the newline and other whitespace with `...'.
7579 "..."
7580 (buffer-substring blinkpos (1+ blinkpos))))
7581 ;; There is nothing to show except the char itself.
7582 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7583 (minibuffer-message
7584 "Matches %s"
7585 (substring-no-properties open-paren-line-string))))))))
7587 (defvar blink-paren-function 'blink-matching-open
7588 "Function called, if non-nil, whenever a close parenthesis is inserted.
7589 More precisely, a char with closeparen syntax is self-inserted.")
7591 (defun blink-paren-post-self-insert-function ()
7592 (when (and (eq (char-before) last-command-event) ; Sanity check.
7593 (memq (char-syntax last-command-event) '(?\) ?\$))
7594 blink-paren-function
7595 (not executing-kbd-macro)
7596 (not noninteractive)
7597 ;; Verify an even number of quoting characters precede the close.
7598 ;; FIXME: Also check if this parenthesis closes a comment as
7599 ;; can happen in Pascal and SML.
7600 (= 1 (logand 1 (- (point)
7601 (save-excursion
7602 (forward-char -1)
7603 (skip-syntax-backward "/\\")
7604 (point))))))
7605 (funcall blink-paren-function)))
7607 (put 'blink-paren-post-self-insert-function 'priority 100)
7609 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7610 ;; Most likely, this hook is nil, so this arg doesn't matter,
7611 ;; but I use it as a reminder that this function usually
7612 ;; likes to be run after others since it does
7613 ;; `sit-for'. That's also the reason it get a `priority' prop
7614 ;; of 100.
7615 'append)
7617 ;; This executes C-g typed while Emacs is waiting for a command.
7618 ;; Quitting out of a program does not go through here;
7619 ;; that happens in the maybe_quit function at the C code level.
7620 (defun keyboard-quit ()
7621 "Signal a `quit' condition.
7622 During execution of Lisp code, this character causes a quit directly.
7623 At top-level, as an editor command, this simply beeps."
7624 (interactive)
7625 ;; Avoid adding the region to the window selection.
7626 (setq saved-region-selection nil)
7627 (let (select-active-regions)
7628 (deactivate-mark))
7629 (if (fboundp 'kmacro-keyboard-quit)
7630 (kmacro-keyboard-quit))
7631 (when completion-in-region-mode
7632 (completion-in-region-mode -1))
7633 ;; Force the next redisplay cycle to remove the "Def" indicator from
7634 ;; all the mode lines.
7635 (if defining-kbd-macro
7636 (force-mode-line-update t))
7637 (setq defining-kbd-macro nil)
7638 (let ((debug-on-quit nil))
7639 (signal 'quit nil)))
7641 (defvar buffer-quit-function nil
7642 "Function to call to \"quit\" the current buffer, or nil if none.
7643 \\[keyboard-escape-quit] calls this function when its more local actions
7644 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7646 (defun keyboard-escape-quit ()
7647 "Exit the current \"mode\" (in a generalized sense of the word).
7648 This command can exit an interactive command such as `query-replace',
7649 can clear out a prefix argument or a region,
7650 can get out of the minibuffer or other recursive edit,
7651 cancel the use of the current buffer (for special-purpose buffers),
7652 or go back to just one window (by deleting all but the selected window)."
7653 (interactive)
7654 (cond ((eq last-command 'mode-exited) nil)
7655 ((region-active-p)
7656 (deactivate-mark))
7657 ((> (minibuffer-depth) 0)
7658 (abort-recursive-edit))
7659 (current-prefix-arg
7660 nil)
7661 ((> (recursion-depth) 0)
7662 (exit-recursive-edit))
7663 (buffer-quit-function
7664 (funcall buffer-quit-function))
7665 ((not (one-window-p t))
7666 (delete-other-windows))
7667 ((string-match "^ \\*" (buffer-name (current-buffer)))
7668 (bury-buffer))))
7670 (defun play-sound-file (file &optional volume device)
7671 "Play sound stored in FILE.
7672 VOLUME and DEVICE correspond to the keywords of the sound
7673 specification for `play-sound'."
7674 (interactive "fPlay sound file: ")
7675 (let ((sound (list :file file)))
7676 (if volume
7677 (plist-put sound :volume volume))
7678 (if device
7679 (plist-put sound :device device))
7680 (push 'sound sound)
7681 (play-sound sound)))
7684 (defcustom read-mail-command 'rmail
7685 "Your preference for a mail reading package.
7686 This is used by some keybindings which support reading mail.
7687 See also `mail-user-agent' concerning sending mail."
7688 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7689 (function-item :tag "Gnus" :format "%t\n" gnus)
7690 (function-item :tag "Emacs interface to MH"
7691 :format "%t\n" mh-rmail)
7692 (function :tag "Other"))
7693 :version "21.1"
7694 :group 'mail)
7696 (defcustom mail-user-agent 'message-user-agent
7697 "Your preference for a mail composition package.
7698 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7699 outgoing email message. This variable lets you specify which
7700 mail-sending package you prefer.
7702 Valid values include:
7704 `message-user-agent' -- use the Message package.
7705 See Info node `(message)'.
7706 `sendmail-user-agent' -- use the Mail package.
7707 See Info node `(emacs)Sending Mail'.
7708 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7709 See Info node `(mh-e)'.
7710 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7711 paraphernalia if Gnus is running, particularly
7712 the Gcc: header for archiving.
7714 Additional valid symbols may be available; check with the author of
7715 your package for details. The function should return non-nil if it
7716 succeeds.
7718 See also `read-mail-command' concerning reading mail."
7719 :type '(radio (function-item :tag "Message package"
7720 :format "%t\n"
7721 message-user-agent)
7722 (function-item :tag "Mail package"
7723 :format "%t\n"
7724 sendmail-user-agent)
7725 (function-item :tag "Emacs interface to MH"
7726 :format "%t\n"
7727 mh-e-user-agent)
7728 (function-item :tag "Message with full Gnus features"
7729 :format "%t\n"
7730 gnus-user-agent)
7731 (function :tag "Other"))
7732 :version "23.2" ; sendmail->message
7733 :group 'mail)
7735 (defcustom compose-mail-user-agent-warnings t
7736 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7737 If the value of `mail-user-agent' is the default, and the user
7738 appears to have customizations applying to the old default,
7739 `compose-mail' issues a warning."
7740 :type 'boolean
7741 :version "23.2"
7742 :group 'mail)
7744 (defun rfc822-goto-eoh ()
7745 "If the buffer starts with a mail header, move point to the header's end.
7746 Otherwise, moves to `point-min'.
7747 The end of the header is the start of the next line, if there is one,
7748 else the end of the last line. This function obeys RFC822."
7749 (goto-char (point-min))
7750 (when (re-search-forward
7751 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7752 (goto-char (match-beginning 0))))
7754 ;; Used by Rmail (e.g., rmail-forward).
7755 (defvar mail-encode-mml nil
7756 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7757 the outgoing message before sending it.")
7759 (defun compose-mail (&optional to subject other-headers continue
7760 switch-function yank-action send-actions
7761 return-action)
7762 "Start composing a mail message to send.
7763 This uses the user's chosen mail composition package
7764 as selected with the variable `mail-user-agent'.
7765 The optional arguments TO and SUBJECT specify recipients
7766 and the initial Subject field, respectively.
7768 OTHER-HEADERS is an alist specifying additional
7769 header fields. Elements look like (HEADER . VALUE) where both
7770 HEADER and VALUE are strings.
7772 CONTINUE, if non-nil, says to continue editing a message already
7773 being composed. Interactively, CONTINUE is the prefix argument.
7775 SWITCH-FUNCTION, if non-nil, is a function to use to
7776 switch to and display the buffer used for mail composition.
7778 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7779 to insert the raw text of the message being replied to.
7780 It has the form (FUNCTION . ARGS). The user agent will apply
7781 FUNCTION to ARGS, to insert the raw text of the original message.
7782 \(The user agent will also run `mail-citation-hook', *after* the
7783 original text has been inserted in this way.)
7785 SEND-ACTIONS is a list of actions to call when the message is sent.
7786 Each action has the form (FUNCTION . ARGS).
7788 RETURN-ACTION, if non-nil, is an action for returning to the
7789 caller. It has the form (FUNCTION . ARGS). The function is
7790 called after the mail has been sent or put aside, and the mail
7791 buffer buried."
7792 (interactive
7793 (list nil nil nil current-prefix-arg))
7795 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7796 ;; from sendmail-user-agent to message-user-agent. Some users may
7797 ;; encounter incompatibilities. This hack tries to detect problems
7798 ;; and warn about them.
7799 (and compose-mail-user-agent-warnings
7800 (eq mail-user-agent 'message-user-agent)
7801 (let (warn-vars)
7802 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7803 mail-yank-hooks mail-archive-file-name
7804 mail-default-reply-to mail-mailing-lists
7805 mail-self-blind))
7806 (and (boundp var)
7807 (symbol-value var)
7808 (push var warn-vars)))
7809 (when warn-vars
7810 (display-warning 'mail
7811 (format-message "\
7812 The default mail mode is now Message mode.
7813 You have the following Mail mode variable%s customized:
7814 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7815 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7816 (if (> (length warn-vars) 1) "s" "")
7817 (mapconcat 'symbol-name
7818 warn-vars " "))))))
7820 (let ((function (get mail-user-agent 'composefunc)))
7821 (funcall function to subject other-headers continue switch-function
7822 yank-action send-actions return-action)))
7824 (defun compose-mail-other-window (&optional to subject other-headers continue
7825 yank-action send-actions
7826 return-action)
7827 "Like \\[compose-mail], but edit the outgoing message in another window."
7828 (interactive (list nil nil nil current-prefix-arg))
7829 (compose-mail to subject other-headers continue
7830 'switch-to-buffer-other-window yank-action send-actions
7831 return-action))
7833 (defun compose-mail-other-frame (&optional to subject other-headers continue
7834 yank-action send-actions
7835 return-action)
7836 "Like \\[compose-mail], but edit the outgoing message in another frame."
7837 (interactive (list nil nil nil current-prefix-arg))
7838 (compose-mail to subject other-headers continue
7839 'switch-to-buffer-other-frame yank-action send-actions
7840 return-action))
7843 (defvar set-variable-value-history nil
7844 "History of values entered with `set-variable'.
7846 Maximum length of the history list is determined by the value
7847 of `history-length', which see.")
7849 (defun set-variable (variable value &optional make-local)
7850 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7851 VARIABLE should be a user option variable name, a Lisp variable
7852 meant to be customized by users. You should enter VALUE in Lisp syntax,
7853 so if you want VALUE to be a string, you must surround it with doublequotes.
7854 VALUE is used literally, not evaluated.
7856 If VARIABLE has a `variable-interactive' property, that is used as if
7857 it were the arg to `interactive' (which see) to interactively read VALUE.
7859 If VARIABLE has been defined with `defcustom', then the type information
7860 in the definition is used to check that VALUE is valid.
7862 Note that this function is at heart equivalent to the basic `set' function.
7863 For a variable defined with `defcustom', it does not pay attention to
7864 any :set property that the variable might have (if you want that, use
7865 \\[customize-set-variable] instead).
7867 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7868 (interactive
7869 (let* ((default-var (variable-at-point))
7870 (var (if (custom-variable-p default-var)
7871 (read-variable (format "Set variable (default %s): " default-var)
7872 default-var)
7873 (read-variable "Set variable: ")))
7874 (minibuffer-help-form '(describe-variable var))
7875 (prop (get var 'variable-interactive))
7876 (obsolete (car (get var 'byte-obsolete-variable)))
7877 (prompt (format "Set %s %s to value: " var
7878 (cond ((local-variable-p var)
7879 "(buffer-local)")
7880 ((or current-prefix-arg
7881 (local-variable-if-set-p var))
7882 "buffer-locally")
7883 (t "globally"))))
7884 (val (progn
7885 (when obsolete
7886 (message (concat "`%S' is obsolete; "
7887 (if (symbolp obsolete) "use `%S' instead" "%s"))
7888 var obsolete)
7889 (sit-for 3))
7890 (if prop
7891 ;; Use VAR's `variable-interactive' property
7892 ;; as an interactive spec for prompting.
7893 (call-interactively `(lambda (arg)
7894 (interactive ,prop)
7895 arg))
7896 (read-from-minibuffer prompt nil
7897 read-expression-map t
7898 'set-variable-value-history
7899 (format "%S" (symbol-value var)))))))
7900 (list var val current-prefix-arg)))
7902 (and (custom-variable-p variable)
7903 (not (get variable 'custom-type))
7904 (custom-load-symbol variable))
7905 (let ((type (get variable 'custom-type)))
7906 (when type
7907 ;; Match with custom type.
7908 (require 'cus-edit)
7909 (setq type (widget-convert type))
7910 (unless (widget-apply type :match value)
7911 (user-error "Value `%S' does not match type %S of %S"
7912 value (car type) variable))))
7914 (if make-local
7915 (make-local-variable variable))
7917 (set variable value)
7919 ;; Force a thorough redisplay for the case that the variable
7920 ;; has an effect on the display, like `tab-width' has.
7921 (force-mode-line-update))
7923 ;; Define the major mode for lists of completions.
7925 (defvar completion-list-mode-map
7926 (let ((map (make-sparse-keymap)))
7927 (define-key map [mouse-2] 'choose-completion)
7928 (define-key map [follow-link] 'mouse-face)
7929 (define-key map [down-mouse-2] nil)
7930 (define-key map "\C-m" 'choose-completion)
7931 (define-key map "\e\e\e" 'delete-completion-window)
7932 (define-key map [left] 'previous-completion)
7933 (define-key map [right] 'next-completion)
7934 (define-key map [?\t] 'next-completion)
7935 (define-key map [backtab] 'previous-completion)
7936 (define-key map "q" 'quit-window)
7937 (define-key map "z" 'kill-current-buffer)
7938 map)
7939 "Local map for completion list buffers.")
7941 ;; Completion mode is suitable only for specially formatted data.
7942 (put 'completion-list-mode 'mode-class 'special)
7944 (defvar completion-reference-buffer nil
7945 "Record the buffer that was current when the completion list was requested.
7946 This is a local variable in the completion list buffer.
7947 Initial value is nil to avoid some compiler warnings.")
7949 (defvar completion-no-auto-exit nil
7950 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7951 This also applies to other functions such as `choose-completion'.")
7953 (defvar completion-base-position nil
7954 "Position of the base of the text corresponding to the shown completions.
7955 This variable is used in the *Completions* buffers.
7956 Its value is a list of the form (START END) where START is the place
7957 where the completion should be inserted and END (if non-nil) is the end
7958 of the text to replace. If END is nil, point is used instead.")
7960 (defvar completion-list-insert-choice-function #'completion--replace
7961 "Function to use to insert the text chosen in *Completions*.
7962 Called with three arguments (BEG END TEXT), it should replace the text
7963 between BEG and END with TEXT. Expected to be set buffer-locally
7964 in the *Completions* buffer.")
7966 (defvar completion-base-size nil
7967 "Number of chars before point not involved in completion.
7968 This is a local variable in the completion list buffer.
7969 It refers to the chars in the minibuffer if completing in the
7970 minibuffer, or in `completion-reference-buffer' otherwise.
7971 Only characters in the field at point are included.
7973 If nil, Emacs determines which part of the tail end of the
7974 buffer's text is involved in completion by comparing the text
7975 directly.")
7976 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7978 (defun delete-completion-window ()
7979 "Delete the completion list window.
7980 Go to the window from which completion was requested."
7981 (interactive)
7982 (let ((buf completion-reference-buffer))
7983 (if (one-window-p t)
7984 (if (window-dedicated-p) (delete-frame))
7985 (delete-window (selected-window))
7986 (if (get-buffer-window buf)
7987 (select-window (get-buffer-window buf))))))
7989 (defun previous-completion (n)
7990 "Move to the previous item in the completion list."
7991 (interactive "p")
7992 (next-completion (- n)))
7994 (defun next-completion (n)
7995 "Move to the next item in the completion list.
7996 With prefix argument N, move N items (negative N means move backward)."
7997 (interactive "p")
7998 (let ((beg (point-min)) (end (point-max)))
7999 (while (and (> n 0) (not (eobp)))
8000 ;; If in a completion, move to the end of it.
8001 (when (get-text-property (point) 'mouse-face)
8002 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8003 ;; Move to start of next one.
8004 (unless (get-text-property (point) 'mouse-face)
8005 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
8006 (setq n (1- n)))
8007 (while (and (< n 0) (not (bobp)))
8008 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
8009 ;; If in a completion, move to the start of it.
8010 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
8011 (goto-char (previous-single-property-change
8012 (point) 'mouse-face nil beg)))
8013 ;; Move to end of the previous completion.
8014 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
8015 (goto-char (previous-single-property-change
8016 (point) 'mouse-face nil beg)))
8017 ;; Move to the start of that one.
8018 (goto-char (previous-single-property-change
8019 (point) 'mouse-face nil beg))
8020 (setq n (1+ n))))))
8022 (defun choose-completion (&optional event)
8023 "Choose the completion at point.
8024 If EVENT, use EVENT's position to determine the starting position."
8025 (interactive (list last-nonmenu-event))
8026 ;; In case this is run via the mouse, give temporary modes such as
8027 ;; isearch a chance to turn off.
8028 (run-hooks 'mouse-leave-buffer-hook)
8029 (with-current-buffer (window-buffer (posn-window (event-start event)))
8030 (let ((buffer completion-reference-buffer)
8031 (base-size completion-base-size)
8032 (base-position completion-base-position)
8033 (insert-function completion-list-insert-choice-function)
8034 (choice
8035 (save-excursion
8036 (goto-char (posn-point (event-start event)))
8037 (let (beg end)
8038 (cond
8039 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
8040 (setq end (point) beg (1+ (point))))
8041 ((and (not (bobp))
8042 (get-text-property (1- (point)) 'mouse-face))
8043 (setq end (1- (point)) beg (point)))
8044 (t (error "No completion here")))
8045 (setq beg (previous-single-property-change beg 'mouse-face))
8046 (setq end (or (next-single-property-change end 'mouse-face)
8047 (point-max)))
8048 (buffer-substring-no-properties beg end)))))
8050 (unless (buffer-live-p buffer)
8051 (error "Destination buffer is dead"))
8052 (quit-window nil (posn-window (event-start event)))
8054 (with-current-buffer buffer
8055 (choose-completion-string
8056 choice buffer
8057 (or base-position
8058 (when base-size
8059 ;; Someone's using old completion code that doesn't know
8060 ;; about base-position yet.
8061 (list (+ base-size (field-beginning))))
8062 ;; If all else fails, just guess.
8063 (list (choose-completion-guess-base-position choice)))
8064 insert-function)))))
8066 ;; Delete the longest partial match for STRING
8067 ;; that can be found before POINT.
8068 (defun choose-completion-guess-base-position (string)
8069 (save-excursion
8070 (let ((opoint (point))
8071 len)
8072 ;; Try moving back by the length of the string.
8073 (goto-char (max (- (point) (length string))
8074 (minibuffer-prompt-end)))
8075 ;; See how far back we were actually able to move. That is the
8076 ;; upper bound on how much we can match and delete.
8077 (setq len (- opoint (point)))
8078 (if completion-ignore-case
8079 (setq string (downcase string)))
8080 (while (and (> len 0)
8081 (let ((tail (buffer-substring (point) opoint)))
8082 (if completion-ignore-case
8083 (setq tail (downcase tail)))
8084 (not (string= tail (substring string 0 len)))))
8085 (setq len (1- len))
8086 (forward-char 1))
8087 (point))))
8089 (defun choose-completion-delete-max-match (string)
8090 (declare (obsolete choose-completion-guess-base-position "23.2"))
8091 (delete-region (choose-completion-guess-base-position string) (point)))
8093 (defvar choose-completion-string-functions nil
8094 "Functions that may override the normal insertion of a completion choice.
8095 These functions are called in order with three arguments:
8096 CHOICE - the string to insert in the buffer,
8097 BUFFER - the buffer in which the choice should be inserted,
8098 BASE-POSITION - where to insert the completion.
8100 If a function in the list returns non-nil, that function is supposed
8101 to have inserted the CHOICE in the BUFFER, and possibly exited
8102 the minibuffer; no further functions will be called.
8104 If all functions in the list return nil, that means to use
8105 the default method of inserting the completion in BUFFER.")
8107 (defun choose-completion-string (choice &optional
8108 buffer base-position insert-function)
8109 "Switch to BUFFER and insert the completion choice CHOICE.
8110 BASE-POSITION says where to insert the completion.
8111 INSERT-FUNCTION says how to insert the completion and falls
8112 back on `completion-list-insert-choice-function' when nil."
8114 ;; If BUFFER is the minibuffer, exit the minibuffer
8115 ;; unless it is reading a file name and CHOICE is a directory,
8116 ;; or completion-no-auto-exit is non-nil.
8118 ;; Some older code may call us passing `base-size' instead of
8119 ;; `base-position'. It's difficult to make any use of `base-size',
8120 ;; so we just ignore it.
8121 (unless (consp base-position)
8122 (message "Obsolete `base-size' passed to choose-completion-string")
8123 (setq base-position nil))
8125 (let* ((buffer (or buffer completion-reference-buffer))
8126 (mini-p (minibufferp buffer)))
8127 ;; If BUFFER is a minibuffer, barf unless it's the currently
8128 ;; active minibuffer.
8129 (if (and mini-p
8130 (not (and (active-minibuffer-window)
8131 (equal buffer
8132 (window-buffer (active-minibuffer-window))))))
8133 (error "Minibuffer is not active for completion")
8134 ;; Set buffer so buffer-local choose-completion-string-functions works.
8135 (set-buffer buffer)
8136 (unless (run-hook-with-args-until-success
8137 'choose-completion-string-functions
8138 ;; The fourth arg used to be `mini-p' but was useless
8139 ;; (since minibufferp can be used on the `buffer' arg)
8140 ;; and indeed unused. The last used to be `base-size', so we
8141 ;; keep it to try and avoid breaking old code.
8142 choice buffer base-position nil)
8143 ;; This remove-text-properties should be unnecessary since `choice'
8144 ;; comes from buffer-substring-no-properties.
8145 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8146 ;; Insert the completion into the buffer where it was requested.
8147 (funcall (or insert-function completion-list-insert-choice-function)
8148 (or (car base-position) (point))
8149 (or (cadr base-position) (point))
8150 choice)
8151 ;; Update point in the window that BUFFER is showing in.
8152 (let ((window (get-buffer-window buffer t)))
8153 (set-window-point window (point)))
8154 ;; If completing for the minibuffer, exit it with this choice.
8155 (and (not completion-no-auto-exit)
8156 (minibufferp buffer)
8157 minibuffer-completion-table
8158 ;; If this is reading a file name, and the file name chosen
8159 ;; is a directory, don't exit the minibuffer.
8160 (let* ((result (buffer-substring (field-beginning) (point)))
8161 (bounds
8162 (completion-boundaries result minibuffer-completion-table
8163 minibuffer-completion-predicate
8164 "")))
8165 (if (eq (car bounds) (length result))
8166 ;; The completion chosen leads to a new set of completions
8167 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8168 (let ((mini (active-minibuffer-window)))
8169 (select-window mini)
8170 (when minibuffer-auto-raise
8171 (raise-frame (window-frame mini))))
8172 (exit-minibuffer))))))))
8174 (define-derived-mode completion-list-mode nil "Completion List"
8175 "Major mode for buffers showing lists of possible completions.
8176 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8177 to select the completion near point.
8178 Or click to select one with the mouse.
8180 \\{completion-list-mode-map}"
8181 (set (make-local-variable 'completion-base-size) nil))
8183 (defun completion-list-mode-finish ()
8184 "Finish setup of the completions buffer.
8185 Called from `temp-buffer-show-hook'."
8186 (when (eq major-mode 'completion-list-mode)
8187 (setq buffer-read-only t)))
8189 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8192 ;; Variables and faces used in `completion-setup-function'.
8194 (defcustom completion-show-help t
8195 "Non-nil means show help message in *Completions* buffer."
8196 :type 'boolean
8197 :version "22.1"
8198 :group 'completion)
8200 ;; This function goes in completion-setup-hook, so that it is called
8201 ;; after the text of the completion list buffer is written.
8202 (defun completion-setup-function ()
8203 (let* ((mainbuf (current-buffer))
8204 (base-dir
8205 ;; FIXME: This is a bad hack. We try to set the default-directory
8206 ;; in the *Completions* buffer so that the relative file names
8207 ;; displayed there can be treated as valid file names, independently
8208 ;; from the completion context. But this suffers from many problems:
8209 ;; - It's not clear when the completions are file names. With some
8210 ;; completion tables (e.g. bzr revision specs), the listed
8211 ;; completions can mix file names and other things.
8212 ;; - It doesn't pay attention to possible quoting.
8213 ;; - With fancy completion styles, the code below will not always
8214 ;; find the right base directory.
8215 (if minibuffer-completing-file-name
8216 (file-name-as-directory
8217 (expand-file-name
8218 (buffer-substring (minibuffer-prompt-end)
8219 (- (point) (or completion-base-size 0))))))))
8220 (with-current-buffer standard-output
8221 (let ((base-size completion-base-size) ;Read before killing localvars.
8222 (base-position completion-base-position)
8223 (insert-fun completion-list-insert-choice-function))
8224 (completion-list-mode)
8225 (set (make-local-variable 'completion-base-size) base-size)
8226 (set (make-local-variable 'completion-base-position) base-position)
8227 (set (make-local-variable 'completion-list-insert-choice-function)
8228 insert-fun))
8229 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8230 (if base-dir (setq default-directory base-dir))
8231 ;; Maybe insert help string.
8232 (when completion-show-help
8233 (goto-char (point-min))
8234 (if (display-mouse-p)
8235 (insert "Click on a completion to select it.\n"))
8236 (insert (substitute-command-keys
8237 "In this buffer, type \\[choose-completion] to \
8238 select the completion near point.\n\n"))))))
8240 (add-hook 'completion-setup-hook 'completion-setup-function)
8242 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8243 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8245 (defun switch-to-completions ()
8246 "Select the completion list window."
8247 (interactive)
8248 (let ((window (or (get-buffer-window "*Completions*" 0)
8249 ;; Make sure we have a completions window.
8250 (progn (minibuffer-completion-help)
8251 (get-buffer-window "*Completions*" 0)))))
8252 (when window
8253 (select-window window)
8254 ;; In the new buffer, go to the first completion.
8255 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8256 (when (bobp)
8257 (next-completion 1)))))
8259 ;;; Support keyboard commands to turn on various modifiers.
8261 ;; These functions -- which are not commands -- each add one modifier
8262 ;; to the following event.
8264 (defun event-apply-alt-modifier (_ignore-prompt)
8265 "\\<function-key-map>Add the Alt modifier to the following event.
8266 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8267 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8268 (defun event-apply-super-modifier (_ignore-prompt)
8269 "\\<function-key-map>Add the Super modifier to the following event.
8270 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8271 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8272 (defun event-apply-hyper-modifier (_ignore-prompt)
8273 "\\<function-key-map>Add the Hyper modifier to the following event.
8274 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8275 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8276 (defun event-apply-shift-modifier (_ignore-prompt)
8277 "\\<function-key-map>Add the Shift modifier to the following event.
8278 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8279 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8280 (defun event-apply-control-modifier (_ignore-prompt)
8281 "\\<function-key-map>Add the Ctrl modifier to the following event.
8282 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8283 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8284 (defun event-apply-meta-modifier (_ignore-prompt)
8285 "\\<function-key-map>Add the Meta modifier to the following event.
8286 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8287 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8289 (defun event-apply-modifier (event symbol lshiftby prefix)
8290 "Apply a modifier flag to event EVENT.
8291 SYMBOL is the name of this modifier, as a symbol.
8292 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8293 PREFIX is the string that represents this modifier in an event type symbol."
8294 (if (numberp event)
8295 (cond ((eq symbol 'control)
8296 (if (and (<= (downcase event) ?z)
8297 (>= (downcase event) ?a))
8298 (- (downcase event) ?a -1)
8299 (if (and (<= (downcase event) ?Z)
8300 (>= (downcase event) ?A))
8301 (- (downcase event) ?A -1)
8302 (logior (lsh 1 lshiftby) event))))
8303 ((eq symbol 'shift)
8304 (if (and (<= (downcase event) ?z)
8305 (>= (downcase event) ?a))
8306 (upcase event)
8307 (logior (lsh 1 lshiftby) event)))
8309 (logior (lsh 1 lshiftby) event)))
8310 (if (memq symbol (event-modifiers event))
8311 event
8312 (let ((event-type (if (symbolp event) event (car event))))
8313 (setq event-type (intern (concat prefix (symbol-name event-type))))
8314 (if (symbolp event)
8315 event-type
8316 (cons event-type (cdr event)))))))
8318 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8319 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8320 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8321 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8322 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8323 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8325 ;;;; Keypad support.
8327 ;; Make the keypad keys act like ordinary typing keys. If people add
8328 ;; bindings for the function key symbols, then those bindings will
8329 ;; override these, so this shouldn't interfere with any existing
8330 ;; bindings.
8332 ;; Also tell read-char how to handle these keys.
8333 (mapc
8334 (lambda (keypad-normal)
8335 (let ((keypad (nth 0 keypad-normal))
8336 (normal (nth 1 keypad-normal)))
8337 (put keypad 'ascii-character normal)
8338 (define-key function-key-map (vector keypad) (vector normal))))
8339 ;; See also kp-keys bound in bindings.el.
8340 '((kp-space ?\s)
8341 (kp-tab ?\t)
8342 (kp-enter ?\r)
8343 (kp-separator ?,)
8344 (kp-equal ?=)
8345 ;; Do the same for various keys that are represented as symbols under
8346 ;; GUIs but naturally correspond to characters.
8347 (backspace 127)
8348 (delete 127)
8349 (tab ?\t)
8350 (linefeed ?\n)
8351 (clear ?\C-l)
8352 (return ?\C-m)
8353 (escape ?\e)
8356 ;;;;
8357 ;;;; forking a twin copy of a buffer.
8358 ;;;;
8360 (defvar clone-buffer-hook nil
8361 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8363 (defvar clone-indirect-buffer-hook nil
8364 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8366 (defun clone-process (process &optional newname)
8367 "Create a twin copy of PROCESS.
8368 If NEWNAME is nil, it defaults to PROCESS' name;
8369 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8370 If PROCESS is associated with a buffer, the new process will be associated
8371 with the current buffer instead.
8372 Returns nil if PROCESS has already terminated."
8373 (setq newname (or newname (process-name process)))
8374 (if (string-match "<[0-9]+>\\'" newname)
8375 (setq newname (substring newname 0 (match-beginning 0))))
8376 (when (memq (process-status process) '(run stop open))
8377 (let* ((process-connection-type (process-tty-name process))
8378 (new-process
8379 (if (memq (process-status process) '(open))
8380 (let ((args (process-contact process t)))
8381 (setq args (plist-put args :name newname))
8382 (setq args (plist-put args :buffer
8383 (if (process-buffer process)
8384 (current-buffer))))
8385 (apply 'make-network-process args))
8386 (apply 'start-process newname
8387 (if (process-buffer process) (current-buffer))
8388 (process-command process)))))
8389 (set-process-query-on-exit-flag
8390 new-process (process-query-on-exit-flag process))
8391 (set-process-inherit-coding-system-flag
8392 new-process (process-inherit-coding-system-flag process))
8393 (set-process-filter new-process (process-filter process))
8394 (set-process-sentinel new-process (process-sentinel process))
8395 (set-process-plist new-process (copy-sequence (process-plist process)))
8396 new-process)))
8398 ;; things to maybe add (currently partly covered by `funcall mode'):
8399 ;; - syntax-table
8400 ;; - overlays
8401 (defun clone-buffer (&optional newname display-flag)
8402 "Create and return a twin copy of the current buffer.
8403 Unlike an indirect buffer, the new buffer can be edited
8404 independently of the old one (if it is not read-only).
8405 NEWNAME is the name of the new buffer. It may be modified by
8406 adding or incrementing <N> at the end as necessary to create a
8407 unique buffer name. If nil, it defaults to the name of the
8408 current buffer, with the proper suffix. If DISPLAY-FLAG is
8409 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8410 clone a file-visiting buffer, or a buffer whose major mode symbol
8411 has a non-nil `no-clone' property, results in an error.
8413 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8414 current buffer with appropriate suffix. However, if a prefix
8415 argument is given, then the command prompts for NEWNAME in the
8416 minibuffer.
8418 This runs the normal hook `clone-buffer-hook' in the new buffer
8419 after it has been set up properly in other respects."
8420 (interactive
8421 (progn
8422 (if buffer-file-name
8423 (error "Cannot clone a file-visiting buffer"))
8424 (if (get major-mode 'no-clone)
8425 (error "Cannot clone a buffer in %s mode" mode-name))
8426 (list (if current-prefix-arg
8427 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8428 t)))
8429 (if buffer-file-name
8430 (error "Cannot clone a file-visiting buffer"))
8431 (if (get major-mode 'no-clone)
8432 (error "Cannot clone a buffer in %s mode" mode-name))
8433 (setq newname (or newname (buffer-name)))
8434 (if (string-match "<[0-9]+>\\'" newname)
8435 (setq newname (substring newname 0 (match-beginning 0))))
8436 (let ((buf (current-buffer))
8437 (ptmin (point-min))
8438 (ptmax (point-max))
8439 (pt (point))
8440 (mk (if mark-active (mark t)))
8441 (modified (buffer-modified-p))
8442 (mode major-mode)
8443 (lvars (buffer-local-variables))
8444 (process (get-buffer-process (current-buffer)))
8445 (new (generate-new-buffer (or newname (buffer-name)))))
8446 (save-restriction
8447 (widen)
8448 (with-current-buffer new
8449 (insert-buffer-substring buf)))
8450 (with-current-buffer new
8451 (narrow-to-region ptmin ptmax)
8452 (goto-char pt)
8453 (if mk (set-mark mk))
8454 (set-buffer-modified-p modified)
8456 ;; Clone the old buffer's process, if any.
8457 (when process (clone-process process))
8459 ;; Now set up the major mode.
8460 (funcall mode)
8462 ;; Set up other local variables.
8463 (mapc (lambda (v)
8464 (condition-case () ;in case var is read-only
8465 (if (symbolp v)
8466 (makunbound v)
8467 (set (make-local-variable (car v)) (cdr v)))
8468 (error nil)))
8469 lvars)
8471 ;; Run any hooks (typically set up by the major mode
8472 ;; for cloning to work properly).
8473 (run-hooks 'clone-buffer-hook))
8474 (if display-flag
8475 ;; Presumably the current buffer is shown in the selected frame, so
8476 ;; we want to display the clone elsewhere.
8477 (let ((same-window-regexps nil)
8478 (same-window-buffer-names))
8479 (pop-to-buffer new)))
8480 new))
8483 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8484 "Create an indirect buffer that is a twin copy of the current buffer.
8486 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8487 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8488 or if not called with a prefix arg, NEWNAME defaults to the current
8489 buffer's name. The name is modified by adding a `<N>' suffix to it
8490 or by incrementing the N in an existing suffix. Trying to clone a
8491 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8492 property results in an error.
8494 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8495 This is always done when called interactively.
8497 Optional third arg NORECORD non-nil means do not put this buffer at the
8498 front of the list of recently selected ones.
8500 Returns the newly created indirect buffer."
8501 (interactive
8502 (progn
8503 (if (get major-mode 'no-clone-indirect)
8504 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8505 (list (if current-prefix-arg
8506 (read-buffer "Name of indirect buffer: " (current-buffer)))
8507 t)))
8508 (if (get major-mode 'no-clone-indirect)
8509 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8510 (setq newname (or newname (buffer-name)))
8511 (if (string-match "<[0-9]+>\\'" newname)
8512 (setq newname (substring newname 0 (match-beginning 0))))
8513 (let* ((name (generate-new-buffer-name newname))
8514 (buffer (make-indirect-buffer (current-buffer) name t)))
8515 (with-current-buffer buffer
8516 (run-hooks 'clone-indirect-buffer-hook))
8517 (when display-flag
8518 (pop-to-buffer buffer nil norecord))
8519 buffer))
8522 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8523 "Like `clone-indirect-buffer' but display in another window."
8524 (interactive
8525 (progn
8526 (if (get major-mode 'no-clone-indirect)
8527 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8528 (list (if current-prefix-arg
8529 (read-buffer "Name of indirect buffer: " (current-buffer)))
8530 t)))
8531 (let ((pop-up-windows t))
8532 (clone-indirect-buffer newname display-flag norecord)))
8535 ;;; Handling of Backspace and Delete keys.
8537 (defcustom normal-erase-is-backspace 'maybe
8538 "Set the default behavior of the Delete and Backspace keys.
8540 If set to t, Delete key deletes forward and Backspace key deletes
8541 backward.
8543 If set to nil, both Delete and Backspace keys delete backward.
8545 If set to `maybe' (which is the default), Emacs automatically
8546 selects a behavior. On window systems, the behavior depends on
8547 the keyboard used. If the keyboard has both a Backspace key and
8548 a Delete key, and both are mapped to their usual meanings, the
8549 option's default value is set to t, so that Backspace can be used
8550 to delete backward, and Delete can be used to delete forward.
8552 If not running under a window system, customizing this option
8553 accomplishes a similar effect by mapping C-h, which is usually
8554 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8555 via `keyboard-translate'. The former functionality of C-h is
8556 available on the F1 key. You should probably not use this
8557 setting if you don't have both Backspace, Delete and F1 keys.
8559 Setting this variable with setq doesn't take effect. Programmatically,
8560 call `normal-erase-is-backspace-mode' (which see) instead."
8561 :type '(choice (const :tag "Off" nil)
8562 (const :tag "Maybe" maybe)
8563 (other :tag "On" t))
8564 :group 'editing-basics
8565 :version "21.1"
8566 :set (lambda (symbol value)
8567 ;; The fboundp is because of a problem with :set when
8568 ;; dumping Emacs. It doesn't really matter.
8569 (if (fboundp 'normal-erase-is-backspace-mode)
8570 (normal-erase-is-backspace-mode (or value 0))
8571 (set-default symbol value))))
8573 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8574 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8575 (unless frame (setq frame (selected-frame)))
8576 (with-selected-frame frame
8577 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8578 (normal-erase-is-backspace-mode
8579 (if (if (eq normal-erase-is-backspace 'maybe)
8580 (and (not noninteractive)
8581 (or (memq system-type '(ms-dos windows-nt))
8582 (memq window-system '(w32 ns))
8583 (and (memq window-system '(x))
8584 (fboundp 'x-backspace-delete-keys-p)
8585 (x-backspace-delete-keys-p))
8586 ;; If the terminal Emacs is running on has erase char
8587 ;; set to ^H, use the Backspace key for deleting
8588 ;; backward, and the Delete key for deleting forward.
8589 (and (null window-system)
8590 (eq tty-erase-char ?\^H))))
8591 normal-erase-is-backspace)
8592 1 0)))))
8594 (define-minor-mode normal-erase-is-backspace-mode
8595 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8596 With a prefix argument ARG, enable this feature if ARG is
8597 positive, and disable it otherwise. If called from Lisp, enable
8598 the mode if ARG is omitted or nil.
8600 On window systems, when this mode is on, Delete is mapped to C-d
8601 and Backspace is mapped to DEL; when this mode is off, both
8602 Delete and Backspace are mapped to DEL. (The remapping goes via
8603 `local-function-key-map', so binding Delete or Backspace in the
8604 global or local keymap will override that.)
8606 In addition, on window systems, the bindings of C-Delete, M-Delete,
8607 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8608 the global keymap in accordance with the functionality of Delete and
8609 Backspace. For example, if Delete is remapped to C-d, which deletes
8610 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8611 to DEL, which deletes backward, C-Delete is bound to
8612 `backward-kill-word'.
8614 If not running on a window system, a similar effect is accomplished by
8615 remapping C-h (normally produced by the Backspace key) and DEL via
8616 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8617 to C-d; if it's off, the keys are not remapped.
8619 When not running on a window system, and this mode is turned on, the
8620 former functionality of C-h is available on the F1 key. You should
8621 probably not turn on this mode on a text-only terminal if you don't
8622 have both Backspace, Delete and F1 keys.
8624 See also `normal-erase-is-backspace'."
8625 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8626 . (lambda (v)
8627 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8628 (if v 1 0))))
8629 (let ((enabled (eq 1 (terminal-parameter
8630 nil 'normal-erase-is-backspace))))
8632 (cond ((or (memq window-system '(x w32 ns pc))
8633 (memq system-type '(ms-dos windows-nt)))
8634 (let ((bindings
8635 `(([M-delete] [M-backspace])
8636 ([C-M-delete] [C-M-backspace])
8637 ([?\e C-delete] [?\e C-backspace]))))
8639 (if enabled
8640 (progn
8641 (define-key local-function-key-map [delete] [deletechar])
8642 (define-key local-function-key-map [kp-delete] [deletechar])
8643 (define-key local-function-key-map [backspace] [?\C-?])
8644 (dolist (b bindings)
8645 ;; Not sure if input-decode-map is really right, but
8646 ;; keyboard-translate-table (used below) only works
8647 ;; for integer events, and key-translation-table is
8648 ;; global (like the global-map, used earlier).
8649 (define-key input-decode-map (car b) nil)
8650 (define-key input-decode-map (cadr b) nil)))
8651 (define-key local-function-key-map [delete] [?\C-?])
8652 (define-key local-function-key-map [kp-delete] [?\C-?])
8653 (define-key local-function-key-map [backspace] [?\C-?])
8654 (dolist (b bindings)
8655 (define-key input-decode-map (car b) (cadr b))
8656 (define-key input-decode-map (cadr b) (car b))))))
8658 (if enabled
8659 (progn
8660 (keyboard-translate ?\C-h ?\C-?)
8661 (keyboard-translate ?\C-? ?\C-d))
8662 (keyboard-translate ?\C-h ?\C-h)
8663 (keyboard-translate ?\C-? ?\C-?))))
8665 (if (called-interactively-p 'interactive)
8666 (message "Delete key deletes %s"
8667 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8668 "forward" "backward")))))
8670 (defvar vis-mode-saved-buffer-invisibility-spec nil
8671 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8673 (define-minor-mode read-only-mode
8674 "Change whether the current buffer is read-only.
8675 With prefix argument ARG, make the buffer read-only if ARG is
8676 positive, otherwise make it writable. If buffer is read-only
8677 and `view-read-only' is non-nil, enter view mode.
8679 Do not call this from a Lisp program unless you really intend to
8680 do the same thing as the \\[read-only-mode] command, including
8681 possibly enabling or disabling View mode. Also, note that this
8682 command works by setting the variable `buffer-read-only', which
8683 does not affect read-only regions caused by text properties. To
8684 ignore read-only status in a Lisp program (whether due to text
8685 properties or buffer state), bind `inhibit-read-only' temporarily
8686 to a non-nil value."
8687 :variable buffer-read-only
8688 (cond
8689 ((and (not buffer-read-only) view-mode)
8690 (View-exit-and-edit)
8691 (make-local-variable 'view-read-only)
8692 (setq view-read-only t)) ; Must leave view mode.
8693 ((and buffer-read-only view-read-only
8694 ;; If view-mode is already active, `view-mode-enter' is a nop.
8695 (not view-mode)
8696 (not (eq (get major-mode 'mode-class) 'special)))
8697 (view-mode-enter))))
8699 (define-minor-mode visible-mode
8700 "Toggle making all invisible text temporarily visible (Visible mode).
8701 With a prefix argument ARG, enable Visible mode if ARG is
8702 positive, and disable it otherwise. If called from Lisp, enable
8703 the mode if ARG is omitted or nil.
8705 This mode works by saving the value of `buffer-invisibility-spec'
8706 and setting it to nil."
8707 :lighter " Vis"
8708 :group 'editing-basics
8709 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8710 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8711 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8712 (when visible-mode
8713 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8714 buffer-invisibility-spec)
8715 (setq buffer-invisibility-spec nil)))
8717 (defvar messages-buffer-mode-map
8718 (let ((map (make-sparse-keymap)))
8719 (set-keymap-parent map special-mode-map)
8720 (define-key map "g" nil) ; nothing to revert
8721 map))
8723 (define-derived-mode messages-buffer-mode special-mode "Messages"
8724 "Major mode used in the \"*Messages*\" buffer.")
8726 (defun messages-buffer ()
8727 "Return the \"*Messages*\" buffer.
8728 If it does not exist, create and it switch it to `messages-buffer-mode'."
8729 (or (get-buffer "*Messages*")
8730 (with-current-buffer (get-buffer-create "*Messages*")
8731 (messages-buffer-mode)
8732 (current-buffer))))
8735 ;; Minibuffer prompt stuff.
8737 ;;(defun minibuffer-prompt-modification (start end)
8738 ;; (error "You cannot modify the prompt"))
8741 ;;(defun minibuffer-prompt-insertion (start end)
8742 ;; (let ((inhibit-modification-hooks t))
8743 ;; (delete-region start end)
8744 ;; ;; Discard undo information for the text insertion itself
8745 ;; ;; and for the text deletion.above.
8746 ;; (when (consp buffer-undo-list)
8747 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8748 ;; (message "You cannot modify the prompt")))
8751 ;;(setq minibuffer-prompt-properties
8752 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8753 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8756 ;;;; Problematic external packages.
8758 ;; rms says this should be done by specifying symbols that define
8759 ;; versions together with bad values. This is therefore not as
8760 ;; flexible as it could be. See the thread:
8761 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8762 (defconst bad-packages-alist
8763 ;; Not sure exactly which semantic versions have problems.
8764 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8765 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8766 "The version of `semantic' loaded does not work in Emacs 22.
8767 It can cause constant high CPU load.
8768 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8769 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8770 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8771 ;; provided the `CUA-mode' feature. Since this is no longer true,
8772 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8773 (CUA-mode t nil
8774 "CUA-mode is now part of the standard GNU Emacs distribution,
8775 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8777 You have loaded an older version of CUA-mode which does not work
8778 correctly with this version of Emacs. You should remove the old
8779 version and use the one distributed with Emacs."))
8780 "Alist of packages known to cause problems in this version of Emacs.
8781 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8782 PACKAGE is either a regular expression to match file names, or a
8783 symbol (a feature name), like for `with-eval-after-load'.
8784 SYMBOL is either the name of a string variable, or t. Upon
8785 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8786 warning using STRING as the message.")
8788 (defun bad-package-check (package)
8789 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8790 (condition-case nil
8791 (let* ((list (assoc package bad-packages-alist))
8792 (symbol (nth 1 list)))
8793 (and list
8794 (boundp symbol)
8795 (or (eq symbol t)
8796 (and (stringp (setq symbol (eval symbol)))
8797 (string-match-p (nth 2 list) symbol)))
8798 (display-warning package (nth 3 list) :warning)))
8799 (error nil)))
8801 (dolist (elem bad-packages-alist)
8802 (let ((pkg (car elem)))
8803 (with-eval-after-load pkg
8804 (bad-package-check pkg))))
8807 ;;; Generic dispatcher commands
8809 ;; Macro `define-alternatives' is used to create generic commands.
8810 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8811 ;; that can have different alternative implementations where choosing
8812 ;; among them is exclusively a matter of user preference.
8814 ;; (define-alternatives COMMAND) creates a new interactive command
8815 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8816 ;; Typically, the user will not need to customize this variable; packages
8817 ;; wanting to add alternative implementations should use
8819 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8821 (defmacro define-alternatives (command &rest customizations)
8822 "Define the new command `COMMAND'.
8824 The argument `COMMAND' should be a symbol.
8826 Running `M-x COMMAND RET' for the first time prompts for which
8827 alternative to use and records the selected command as a custom
8828 variable.
8830 Running `C-u M-x COMMAND RET' prompts again for an alternative
8831 and overwrites the previous choice.
8833 The variable `COMMAND-alternatives' contains an alist with
8834 alternative implementations of COMMAND. `define-alternatives'
8835 does not have any effect until this variable is set.
8837 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8838 `defcustom' keywords and values to add to the declaration of
8839 `COMMAND-alternatives' (typically :group and :version)."
8840 (let* ((command-name (symbol-name command))
8841 (varalt-name (concat command-name "-alternatives"))
8842 (varalt-sym (intern varalt-name))
8843 (varimp-sym (intern (concat command-name "--implementation"))))
8844 `(progn
8846 (defcustom ,varalt-sym nil
8847 ,(format "Alist of alternative implementations for the `%s' command.
8849 Each entry must be a pair (ALTNAME . ALTFUN), where:
8850 ALTNAME - The name shown at user to describe the alternative implementation.
8851 ALTFUN - The function called to implement this alternative."
8852 command-name)
8853 :type '(alist :key-type string :value-type function)
8854 ,@customizations)
8856 (put ',varalt-sym 'definition-name ',command)
8857 (defvar ,varimp-sym nil "Internal use only.")
8859 (defun ,command (&optional arg)
8860 ,(format "Run generic command `%s'.
8861 If used for the first time, or with interactive ARG, ask the user which
8862 implementation to use for `%s'. The variable `%s'
8863 contains the list of implementations currently supported for this command."
8864 command-name command-name varalt-name)
8865 (interactive "P")
8866 (when (or arg (null ,varimp-sym))
8867 (let ((val (completing-read
8868 ,(format-message
8869 "Select implementation for command `%s': "
8870 command-name)
8871 ,varalt-sym nil t)))
8872 (unless (string-equal val "")
8873 (when (null ,varimp-sym)
8874 (message
8875 "Use C-u M-x %s RET`to select another implementation"
8876 ,command-name)
8877 (sit-for 3))
8878 (customize-save-variable ',varimp-sym
8879 (cdr (assoc-string val ,varalt-sym))))))
8880 (if ,varimp-sym
8881 (call-interactively ,varimp-sym)
8882 (message "%s" ,(format-message
8883 "No implementation selected for command `%s'"
8884 command-name)))))))
8887 ;;; Functions for changing capitalization that Do What I Mean
8888 (defun upcase-dwim (arg)
8889 "Upcase words in the region, if active; if not, upcase word at point.
8890 If the region is active, this function calls `upcase-region'.
8891 Otherwise, it calls `upcase-word', with prefix argument passed to it
8892 to upcase ARG words."
8893 (interactive "*p")
8894 (if (use-region-p)
8895 (upcase-region (region-beginning) (region-end))
8896 (upcase-word arg)))
8898 (defun downcase-dwim (arg)
8899 "Downcase words in the region, if active; if not, downcase word at point.
8900 If the region is active, this function calls `downcase-region'.
8901 Otherwise, it calls `downcase-word', with prefix argument passed to it
8902 to downcase ARG words."
8903 (interactive "*p")
8904 (if (use-region-p)
8905 (downcase-region (region-beginning) (region-end))
8906 (downcase-word arg)))
8908 (defun capitalize-dwim (arg)
8909 "Capitalize words in the region, if active; if not, capitalize word at point.
8910 If the region is active, this function calls `capitalize-region'.
8911 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8912 to capitalize ARG words."
8913 (interactive "*p")
8914 (if (use-region-p)
8915 (capitalize-region (region-beginning) (region-end))
8916 (capitalize-word arg)))
8920 (provide 'simple)
8922 ;;; simple.el ends here