* src/gfilenotify.c (Fgfile_monitor_name): Return a symbol.
[emacs.git] / lisp / simple.el
blob0ee2f060e5e6b9919d3c1d543ef9b5b59eedcfe8
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2016 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: internal
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
29 ;;; Code:
31 (eval-when-compile (require 'cl-lib))
33 (declare-function widget-convert "wid-edit" (type &rest args))
34 (declare-function shell-mode "shell" ())
36 ;;; From compile.el
37 (defvar compilation-current-error)
38 (defvar compilation-context-lines)
40 (defcustom shell-command-dont-erase-buffer nil
41 "If non-nil, output buffer is not erased between shell commands.
42 Also, a non-nil value set the point in the output buffer
43 once the command complete.
44 The value `beg-last-out' set point at the beginning of the output,
45 `end-last-out' set point at the end of the buffer, `save-point'
46 restore the buffer position before the command."
47 :type '(choice
48 (const :tag "Erase buffer" nil)
49 (const :tag "Set point to beginning of last output" beg-last-out)
50 (const :tag "Set point to end of last output" end-last-out)
51 (const :tag "Save point" save-point))
52 :group 'shell
53 :version "26.1")
55 (defvar shell-command-saved-pos nil
56 "Point position in the output buffer after command complete.
57 It is an alist (BUFFER . POS), where BUFFER is the output
58 buffer, and POS is the point position in BUFFER once the command finish.
59 This variable is used when `shell-command-dont-erase-buffer' is non-nil.")
61 (defcustom idle-update-delay 0.5
62 "Idle time delay before updating various things on the screen.
63 Various Emacs features that update auxiliary information when point moves
64 wait this many seconds after Emacs becomes idle before doing an update."
65 :type 'number
66 :group 'display
67 :version "22.1")
69 (defgroup killing nil
70 "Killing and yanking commands."
71 :group 'editing)
73 (defgroup paren-matching nil
74 "Highlight (un)matching of parens and expressions."
75 :group 'matching)
77 ;;; next-error support framework
79 (defgroup next-error nil
80 "`next-error' support framework."
81 :group 'compilation
82 :version "22.1")
84 (defface next-error
85 '((t (:inherit region)))
86 "Face used to highlight next error locus."
87 :group 'next-error
88 :version "22.1")
90 (defcustom next-error-highlight 0.5
91 "Highlighting of locations in selected source buffers.
92 If a number, highlight the locus in `next-error' face for the given time
93 in seconds, or until the next command is executed.
94 If t, highlight the locus until the next command is executed, or until
95 some other locus replaces it.
96 If nil, don't highlight the locus in the source buffer.
97 If `fringe-arrow', indicate the locus by the fringe arrow
98 indefinitely until some other locus replaces it."
99 :type '(choice (number :tag "Highlight for specified time")
100 (const :tag "Semipermanent highlighting" t)
101 (const :tag "No highlighting" nil)
102 (const :tag "Fringe arrow" fringe-arrow))
103 :group 'next-error
104 :version "22.1")
106 (defcustom next-error-highlight-no-select 0.5
107 "Highlighting of locations in `next-error-no-select'.
108 If number, highlight the locus in `next-error' face for given time in seconds.
109 If t, highlight the locus indefinitely until some other locus replaces it.
110 If nil, don't highlight the locus in the source buffer.
111 If `fringe-arrow', indicate the locus by the fringe arrow
112 indefinitely until some other locus replaces it."
113 :type '(choice (number :tag "Highlight for specified time")
114 (const :tag "Semipermanent highlighting" t)
115 (const :tag "No highlighting" nil)
116 (const :tag "Fringe arrow" fringe-arrow))
117 :group 'next-error
118 :version "22.1")
120 (defcustom next-error-recenter nil
121 "Display the line in the visited source file recentered as specified.
122 If non-nil, the value is passed directly to `recenter'."
123 :type '(choice (integer :tag "Line to recenter to")
124 (const :tag "Center of window" (4))
125 (const :tag "No recentering" nil))
126 :group 'next-error
127 :version "23.1")
129 (defcustom next-error-hook nil
130 "List of hook functions run by `next-error' after visiting source file."
131 :type 'hook
132 :group 'next-error)
134 (defvar next-error-highlight-timer nil)
136 (defvar next-error-overlay-arrow-position nil)
137 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
138 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
140 (defvar next-error-last-buffer nil
141 "The most recent `next-error' buffer.
142 A buffer becomes most recent when its compilation, grep, or
143 similar mode is started, or when it is used with \\[next-error]
144 or \\[compile-goto-error].")
146 (defvar next-error-function nil
147 "Function to use to find the next error in the current buffer.
148 The function is called with 2 parameters:
149 ARG is an integer specifying by how many errors to move.
150 RESET is a boolean which, if non-nil, says to go back to the beginning
151 of the errors before moving.
152 Major modes providing compile-like functionality should set this variable
153 to indicate to `next-error' that this is a candidate buffer and how
154 to navigate in it.")
155 (make-variable-buffer-local 'next-error-function)
157 (defvar next-error-move-function nil
158 "Function to use to move to an error locus.
159 It takes two arguments, a buffer position in the error buffer
160 and a buffer position in the error locus buffer.
161 The buffer for the error locus should already be current.
162 nil means use goto-char using the second argument position.")
163 (make-variable-buffer-local 'next-error-move-function)
165 (defsubst next-error-buffer-p (buffer
166 &optional avoid-current
167 extra-test-inclusive
168 extra-test-exclusive)
169 "Return non-nil if BUFFER is a `next-error' capable buffer.
170 If AVOID-CURRENT is non-nil, and BUFFER is the current buffer,
171 return nil.
173 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called if
174 BUFFER would not normally qualify. If it returns non-nil, BUFFER
175 is considered `next-error' capable, anyway, and the function
176 returns non-nil.
178 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called if the
179 buffer would normally qualify. If it returns nil, BUFFER is
180 rejected, and the function returns nil."
181 (and (buffer-name buffer) ;First make sure it's live.
182 (not (and avoid-current (eq buffer (current-buffer))))
183 (with-current-buffer buffer
184 (if next-error-function ; This is the normal test.
185 ;; Optionally reject some buffers.
186 (if extra-test-exclusive
187 (funcall extra-test-exclusive)
189 ;; Optionally accept some other buffers.
190 (and extra-test-inclusive
191 (funcall extra-test-inclusive))))))
193 (defun next-error-find-buffer (&optional avoid-current
194 extra-test-inclusive
195 extra-test-exclusive)
196 "Return a `next-error' capable buffer.
198 If AVOID-CURRENT is non-nil, treat the current buffer
199 as an absolute last resort only.
201 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
202 that normally would not qualify. If it returns t, the buffer
203 in question is treated as usable.
205 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
206 that would normally be considered usable. If it returns nil,
207 that buffer is rejected."
209 ;; 1. If one window on the selected frame displays such buffer, return it.
210 (let ((window-buffers
211 (delete-dups
212 (delq nil (mapcar (lambda (w)
213 (if (next-error-buffer-p
214 (window-buffer w)
215 avoid-current
216 extra-test-inclusive extra-test-exclusive)
217 (window-buffer w)))
218 (window-list))))))
219 (if (eq (length window-buffers) 1)
220 (car window-buffers)))
221 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
222 (if (and next-error-last-buffer
223 (next-error-buffer-p next-error-last-buffer avoid-current
224 extra-test-inclusive extra-test-exclusive))
225 next-error-last-buffer)
226 ;; 3. If the current buffer is acceptable, choose it.
227 (if (next-error-buffer-p (current-buffer) avoid-current
228 extra-test-inclusive extra-test-exclusive)
229 (current-buffer))
230 ;; 4. Look for any acceptable buffer.
231 (let ((buffers (buffer-list)))
232 (while (and buffers
233 (not (next-error-buffer-p
234 (car buffers) avoid-current
235 extra-test-inclusive extra-test-exclusive)))
236 (setq buffers (cdr buffers)))
237 (car buffers))
238 ;; 5. Use the current buffer as a last resort if it qualifies,
239 ;; even despite AVOID-CURRENT.
240 (and avoid-current
241 (next-error-buffer-p (current-buffer) nil
242 extra-test-inclusive extra-test-exclusive)
243 (progn
244 (message "This is the only buffer with error message locations")
245 (current-buffer)))
246 ;; 6. Give up.
247 (error "No buffers contain error message locations")))
249 (defun next-error (&optional arg reset)
250 "Visit next `next-error' message and corresponding source code.
252 If all the error messages parsed so far have been processed already,
253 the message buffer is checked for new ones.
255 A prefix ARG specifies how many error messages to move;
256 negative means move back to previous error messages.
257 Just \\[universal-argument] as a prefix means reparse the error message buffer
258 and start at the first error.
260 The RESET argument specifies that we should restart from the beginning.
262 \\[next-error] normally uses the most recently started
263 compilation, grep, or occur buffer. It can also operate on any
264 buffer with output from the \\[compile], \\[grep] commands, or,
265 more generally, on any buffer in Compilation mode or with
266 Compilation Minor mode enabled, or any buffer in which
267 `next-error-function' is bound to an appropriate function.
268 To specify use of a particular buffer for error messages, type
269 \\[next-error] in that buffer when it is the only one displayed
270 in the current frame.
272 Once \\[next-error] has chosen the buffer for error messages, it
273 runs `next-error-hook' with `run-hooks', and stays with that buffer
274 until you use it in some other buffer which uses Compilation mode
275 or Compilation Minor mode.
277 To control which errors are matched, customize the variable
278 `compilation-error-regexp-alist'."
279 (interactive "P")
280 (if (consp arg) (setq reset t arg nil))
281 (when (setq next-error-last-buffer (next-error-find-buffer))
282 ;; we know here that next-error-function is a valid symbol we can funcall
283 (with-current-buffer next-error-last-buffer
284 (funcall next-error-function (prefix-numeric-value arg) reset)
285 (when next-error-recenter
286 (recenter next-error-recenter))
287 (run-hooks 'next-error-hook))))
289 (defun next-error-internal ()
290 "Visit the source code corresponding to the `next-error' message at point."
291 (setq next-error-last-buffer (current-buffer))
292 ;; we know here that next-error-function is a valid symbol we can funcall
293 (with-current-buffer next-error-last-buffer
294 (funcall next-error-function 0 nil)
295 (when next-error-recenter
296 (recenter next-error-recenter))
297 (run-hooks 'next-error-hook)))
299 (defalias 'goto-next-locus 'next-error)
300 (defalias 'next-match 'next-error)
302 (defun previous-error (&optional n)
303 "Visit previous `next-error' message and corresponding source code.
305 Prefix arg N says how many error messages to move backwards (or
306 forwards, if negative).
308 This operates on the output from the \\[compile] and \\[grep] commands."
309 (interactive "p")
310 (next-error (- (or n 1))))
312 (defun first-error (&optional n)
313 "Restart at the first error.
314 Visit corresponding source code.
315 With prefix arg N, visit the source code of the Nth error.
316 This operates on the output from the \\[compile] command, for instance."
317 (interactive "p")
318 (next-error n t))
320 (defun next-error-no-select (&optional n)
321 "Move point to the next error in the `next-error' buffer and highlight match.
322 Prefix arg N says how many error messages to move forwards (or
323 backwards, if negative).
324 Finds and highlights the source line like \\[next-error], but does not
325 select the source buffer."
326 (interactive "p")
327 (let ((next-error-highlight next-error-highlight-no-select))
328 (next-error n))
329 (pop-to-buffer next-error-last-buffer))
331 (defun previous-error-no-select (&optional n)
332 "Move point to the previous error in the `next-error' buffer and highlight match.
333 Prefix arg N says how many error messages to move backwards (or
334 forwards, if negative).
335 Finds and highlights the source line like \\[previous-error], but does not
336 select the source buffer."
337 (interactive "p")
338 (next-error-no-select (- (or n 1))))
340 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
341 (defvar next-error-follow-last-line nil)
343 (define-minor-mode next-error-follow-minor-mode
344 "Minor mode for compilation, occur and diff modes.
345 With a prefix argument ARG, enable mode if ARG is positive, and
346 disable it otherwise. If called from Lisp, enable mode if ARG is
347 omitted or nil.
348 When turned on, cursor motion in the compilation, grep, occur or diff
349 buffer causes automatic display of the corresponding source code location."
350 :group 'next-error :init-value nil :lighter " Fol"
351 (if (not next-error-follow-minor-mode)
352 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
353 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
354 (make-local-variable 'next-error-follow-last-line)))
356 ;; Used as a `post-command-hook' by `next-error-follow-mode'
357 ;; for the *Compilation* *grep* and *Occur* buffers.
358 (defun next-error-follow-mode-post-command-hook ()
359 (unless (equal next-error-follow-last-line (line-number-at-pos))
360 (setq next-error-follow-last-line (line-number-at-pos))
361 (condition-case nil
362 (let ((compilation-context-lines nil))
363 (setq compilation-current-error (point))
364 (next-error-no-select 0))
365 (error t))))
370 (defun fundamental-mode ()
371 "Major mode not specialized for anything in particular.
372 Other major modes are defined by comparison with this one."
373 (interactive)
374 (kill-all-local-variables)
375 (run-mode-hooks))
377 ;; Special major modes to view specially formatted data rather than files.
379 (defvar special-mode-map
380 (let ((map (make-sparse-keymap)))
381 (suppress-keymap map)
382 (define-key map "q" 'quit-window)
383 (define-key map " " 'scroll-up-command)
384 (define-key map [?\S-\ ] 'scroll-down-command)
385 (define-key map "\C-?" 'scroll-down-command)
386 (define-key map "?" 'describe-mode)
387 (define-key map "h" 'describe-mode)
388 (define-key map ">" 'end-of-buffer)
389 (define-key map "<" 'beginning-of-buffer)
390 (define-key map "g" 'revert-buffer)
391 map))
393 (put 'special-mode 'mode-class 'special)
394 (define-derived-mode special-mode nil "Special"
395 "Parent major mode from which special major modes should inherit."
396 (setq buffer-read-only t))
398 ;; Making and deleting lines.
400 (defvar self-insert-uses-region-functions nil
401 "Special hook to tell if `self-insert-command' will use the region.
402 It must be called via `run-hook-with-args-until-success' with no arguments.
403 Any `post-self-insert-command' which consumes the region should
404 register a function on this hook so that things like `delete-selection-mode'
405 can refrain from consuming the region.")
407 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
408 "Propertized string representing a hard newline character.")
410 (defun newline (&optional arg interactive)
411 "Insert a newline, and move to left margin of the new line if it's blank.
412 If option `use-hard-newlines' is non-nil, the newline is marked with the
413 text-property `hard'.
414 With ARG, insert that many newlines.
416 If `electric-indent-mode' is enabled, this indents the final new line
417 that it adds, and reindents the preceding line. To just insert
418 a newline, use \\[electric-indent-just-newline].
420 Calls `auto-fill-function' if the current column number is greater
421 than the value of `fill-column' and ARG is nil.
422 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
423 (interactive "*P\np")
424 (barf-if-buffer-read-only)
425 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
426 ;; Set last-command-event to tell self-insert what to insert.
427 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
428 (beforepos (point))
429 (last-command-event ?\n)
430 ;; Don't auto-fill if we have a numeric argument.
431 (auto-fill-function (if arg nil auto-fill-function))
432 (arg (prefix-numeric-value arg))
433 (postproc
434 ;; Do the rest in post-self-insert-hook, because we want to do it
435 ;; *before* other functions on that hook.
436 (lambda ()
437 ;; We are not going to insert any newlines if arg is
438 ;; non-positive.
439 (or (and (numberp arg) (<= arg 0))
440 (cl-assert (eq ?\n (char-before))))
441 ;; Mark the newline(s) `hard'.
442 (if use-hard-newlines
443 (set-hard-newline-properties
444 (- (point) arg) (point)))
445 ;; If the newline leaves the previous line blank, and we
446 ;; have a left margin, delete that from the blank line.
447 (save-excursion
448 (goto-char beforepos)
449 (beginning-of-line)
450 (and (looking-at "[ \t]$")
451 (> (current-left-margin) 0)
452 (delete-region (point)
453 (line-end-position))))
454 ;; Indent the line after the newline, except in one case:
455 ;; when we added the newline at the beginning of a line which
456 ;; starts a page.
457 (or was-page-start
458 (move-to-left-margin nil t)))))
459 (unwind-protect
460 (if (not interactive)
461 ;; FIXME: For non-interactive uses, many calls actually
462 ;; just want (insert "\n"), so maybe we should do just
463 ;; that, so as to avoid the risk of filling or running
464 ;; abbrevs unexpectedly.
465 (let ((post-self-insert-hook (list postproc)))
466 (self-insert-command arg))
467 (unwind-protect
468 (progn
469 (add-hook 'post-self-insert-hook postproc nil t)
470 (self-insert-command arg))
471 ;; We first used let-binding to protect the hook, but that
472 ;; was naive since add-hook affects the symbol-default
473 ;; value of the variable, whereas the let-binding might
474 ;; only protect the buffer-local value.
475 (remove-hook 'post-self-insert-hook postproc t)))
476 (cl-assert (not (member postproc post-self-insert-hook)))
477 (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
478 nil)
480 (defun set-hard-newline-properties (from to)
481 (let ((sticky (get-text-property from 'rear-nonsticky)))
482 (put-text-property from to 'hard 't)
483 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
484 (if (and (listp sticky) (not (memq 'hard sticky)))
485 (put-text-property from (point) 'rear-nonsticky
486 (cons 'hard sticky)))))
488 (defun open-line (n)
489 "Insert a newline and leave point before it.
490 If there is a fill prefix and/or a `left-margin', insert them on
491 the new line if the line would have been blank.
492 With arg N, insert N newlines."
493 (interactive "*p")
494 (let* ((do-fill-prefix (and fill-prefix (bolp)))
495 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
496 (loc (point-marker))
497 ;; Don't expand an abbrev before point.
498 (abbrev-mode nil))
499 (newline n)
500 (goto-char loc)
501 (while (> n 0)
502 (cond ((bolp)
503 (if do-left-margin (indent-to (current-left-margin)))
504 (if do-fill-prefix (insert-and-inherit fill-prefix))))
505 (forward-line 1)
506 (setq n (1- n)))
507 (goto-char loc)
508 ;; Necessary in case a margin or prefix was inserted.
509 (end-of-line)))
511 (defun split-line (&optional arg)
512 "Split current line, moving portion beyond point vertically down.
513 If the current line starts with `fill-prefix', insert it on the new
514 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
516 When called from Lisp code, ARG may be a prefix string to copy."
517 (interactive "*P")
518 (skip-chars-forward " \t")
519 (let* ((col (current-column))
520 (pos (point))
521 ;; What prefix should we check for (nil means don't).
522 (prefix (cond ((stringp arg) arg)
523 (arg nil)
524 (t fill-prefix)))
525 ;; Does this line start with it?
526 (have-prfx (and prefix
527 (save-excursion
528 (beginning-of-line)
529 (looking-at (regexp-quote prefix))))))
530 (newline 1)
531 (if have-prfx (insert-and-inherit prefix))
532 (indent-to col 0)
533 (goto-char pos)))
535 (defun delete-indentation (&optional arg)
536 "Join this line to previous and fix up whitespace at join.
537 If there is a fill prefix, delete it from the beginning of this line.
538 With argument, join this line to following line."
539 (interactive "*P")
540 (beginning-of-line)
541 (if arg (forward-line 1))
542 (if (eq (preceding-char) ?\n)
543 (progn
544 (delete-region (point) (1- (point)))
545 ;; If the second line started with the fill prefix,
546 ;; delete the prefix.
547 (if (and fill-prefix
548 (<= (+ (point) (length fill-prefix)) (point-max))
549 (string= fill-prefix
550 (buffer-substring (point)
551 (+ (point) (length fill-prefix)))))
552 (delete-region (point) (+ (point) (length fill-prefix))))
553 (fixup-whitespace))))
555 (defalias 'join-line #'delete-indentation) ; easier to find
557 (defun delete-blank-lines ()
558 "On blank line, delete all surrounding blank lines, leaving just one.
559 On isolated blank line, delete that one.
560 On nonblank line, delete any immediately following blank lines."
561 (interactive "*")
562 (let (thisblank singleblank)
563 (save-excursion
564 (beginning-of-line)
565 (setq thisblank (looking-at "[ \t]*$"))
566 ;; Set singleblank if there is just one blank line here.
567 (setq singleblank
568 (and thisblank
569 (not (looking-at "[ \t]*\n[ \t]*$"))
570 (or (bobp)
571 (progn (forward-line -1)
572 (not (looking-at "[ \t]*$")))))))
573 ;; Delete preceding blank lines, and this one too if it's the only one.
574 (if thisblank
575 (progn
576 (beginning-of-line)
577 (if singleblank (forward-line 1))
578 (delete-region (point)
579 (if (re-search-backward "[^ \t\n]" nil t)
580 (progn (forward-line 1) (point))
581 (point-min)))))
582 ;; Delete following blank lines, unless the current line is blank
583 ;; and there are no following blank lines.
584 (if (not (and thisblank singleblank))
585 (save-excursion
586 (end-of-line)
587 (forward-line 1)
588 (delete-region (point)
589 (if (re-search-forward "[^ \t\n]" nil t)
590 (progn (beginning-of-line) (point))
591 (point-max)))))
592 ;; Handle the special case where point is followed by newline and eob.
593 ;; Delete the line, leaving point at eob.
594 (if (looking-at "^[ \t]*\n\\'")
595 (delete-region (point) (point-max)))))
597 (defcustom delete-trailing-lines t
598 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
599 Trailing lines are deleted only if `delete-trailing-whitespace'
600 is called on the entire buffer (rather than an active region)."
601 :type 'boolean
602 :group 'editing
603 :version "24.3")
605 (defun region-modifiable-p (start end)
606 "Return non-nil if the region contains no read-only text."
607 (and (not (get-text-property start 'read-only))
608 (eq end (next-single-property-change start 'read-only nil end))))
610 (defun delete-trailing-whitespace (&optional start end)
611 "Delete trailing whitespace between START and END.
612 If called interactively, START and END are the start/end of the
613 region if the mark is active, or of the buffer's accessible
614 portion if the mark is inactive.
616 This command deletes whitespace characters after the last
617 non-whitespace character in each line between START and END. It
618 does not consider formfeed characters to be whitespace.
620 If this command acts on the entire buffer (i.e. if called
621 interactively with the mark inactive, or called from Lisp with
622 END nil), it also deletes all trailing lines at the end of the
623 buffer if the variable `delete-trailing-lines' is non-nil."
624 (interactive (progn
625 (barf-if-buffer-read-only)
626 (if (use-region-p)
627 (list (region-beginning) (region-end))
628 (list nil nil))))
629 (save-match-data
630 (save-excursion
631 (let ((end-marker (and end (copy-marker end))))
632 (goto-char (or start (point-min)))
633 (with-syntax-table (make-syntax-table (syntax-table))
634 ;; Don't delete formfeeds, even if they are considered whitespace.
635 (modify-syntax-entry ?\f "_")
636 ;; Treating \n as non-whitespace makes things easier.
637 (modify-syntax-entry ?\n "_")
638 (while (re-search-forward "\\s-+$" end-marker t)
639 (let ((b (match-beginning 0)) (e (match-end 0)))
640 (when (region-modifiable-p b e)
641 (delete-region b e)))))
642 (if end
643 (set-marker end-marker nil)
644 ;; Delete trailing empty lines.
645 (and delete-trailing-lines
646 ;; Really the end of buffer.
647 (= (goto-char (point-max)) (1+ (buffer-size)))
648 (<= (skip-chars-backward "\n") -2)
649 (region-modifiable-p (1+ (point)) (point-max))
650 (delete-region (1+ (point)) (point-max)))))))
651 ;; Return nil for the benefit of `write-file-functions'.
652 nil)
654 (defun newline-and-indent ()
655 "Insert a newline, then indent according to major mode.
656 Indentation is done using the value of `indent-line-function'.
657 In programming language modes, this is the same as TAB.
658 In some text modes, where TAB inserts a tab, this command indents to the
659 column specified by the function `current-left-margin'."
660 (interactive "*")
661 (delete-horizontal-space t)
662 (newline nil t)
663 (indent-according-to-mode))
665 (defun reindent-then-newline-and-indent ()
666 "Reindent current line, insert newline, then indent the new line.
667 Indentation of both lines is done according to the current major mode,
668 which means calling the current value of `indent-line-function'.
669 In programming language modes, this is the same as TAB.
670 In some text modes, where TAB inserts a tab, this indents to the
671 column specified by the function `current-left-margin'."
672 (interactive "*")
673 (let ((pos (point)))
674 ;; Be careful to insert the newline before indenting the line.
675 ;; Otherwise, the indentation might be wrong.
676 (newline)
677 (save-excursion
678 (goto-char pos)
679 ;; We are at EOL before the call to indent-according-to-mode, and
680 ;; after it we usually are as well, but not always. We tried to
681 ;; address it with `save-excursion' but that uses a normal marker
682 ;; whereas we need `move after insertion', so we do the save/restore
683 ;; by hand.
684 (setq pos (copy-marker pos t))
685 (indent-according-to-mode)
686 (goto-char pos)
687 ;; Remove the trailing white-space after indentation because
688 ;; indentation may introduce the whitespace.
689 (delete-horizontal-space t))
690 (indent-according-to-mode)))
692 (defcustom read-quoted-char-radix 8
693 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
694 Legitimate radix values are 8, 10 and 16."
695 :type '(choice (const 8) (const 10) (const 16))
696 :group 'editing-basics)
698 (defun read-quoted-char (&optional prompt)
699 "Like `read-char', but do not allow quitting.
700 Also, if the first character read is an octal digit,
701 we read any number of octal digits and return the
702 specified character code. Any nondigit terminates the sequence.
703 If the terminator is RET, it is discarded;
704 any other terminator is used itself as input.
706 The optional argument PROMPT specifies a string to use to prompt the user.
707 The variable `read-quoted-char-radix' controls which radix to use
708 for numeric input."
709 (let ((message-log-max nil)
710 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
711 help-event-list)))
712 done (first t) (code 0) char translated)
713 (while (not done)
714 (let ((inhibit-quit first)
715 ;; Don't let C-h or other help chars get the help
716 ;; message--only help function keys. See bug#16617.
717 (help-char nil)
718 (help-event-list help-events)
719 (help-form
720 "Type the special character you want to use,
721 or the octal character code.
722 RET terminates the character code and is discarded;
723 any other non-digit terminates the character code and is then used as input."))
724 (setq char (read-event (and prompt (format "%s-" prompt)) t))
725 (if inhibit-quit (setq quit-flag nil)))
726 ;; Translate TAB key into control-I ASCII character, and so on.
727 ;; Note: `read-char' does it using the `ascii-character' property.
728 ;; We tried using read-key instead, but that disables the keystroke
729 ;; echo produced by 'C-q', see bug#24635.
730 (let ((translation (lookup-key local-function-key-map (vector char))))
731 (setq translated (if (arrayp translation)
732 (aref translation 0)
733 char)))
734 (if (integerp translated)
735 (setq translated (char-resolve-modifiers translated)))
736 (cond ((null translated))
737 ((not (integerp translated))
738 (setq unread-command-events (list char)
739 done t))
740 ((/= (logand translated ?\M-\^@) 0)
741 ;; Turn a meta-character into a character with the 0200 bit set.
742 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
743 done t))
744 ((and (<= ?0 translated)
745 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
746 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
747 (and prompt (setq prompt (message "%s %c" prompt translated))))
748 ((and (<= ?a (downcase translated))
749 (< (downcase translated)
750 (+ ?a -10 (min 36 read-quoted-char-radix))))
751 (setq code (+ (* code read-quoted-char-radix)
752 (+ 10 (- (downcase translated) ?a))))
753 (and prompt (setq prompt (message "%s %c" prompt translated))))
754 ((and (not first) (eq translated ?\C-m))
755 (setq done t))
756 ((not first)
757 (setq unread-command-events (list char)
758 done t))
759 (t (setq code translated
760 done t)))
761 (setq first nil))
762 code))
764 (defun quoted-insert (arg)
765 "Read next input character and insert it.
766 This is useful for inserting control characters.
767 With argument, insert ARG copies of the character.
769 If the first character you type after this command is an octal digit,
770 you should type a sequence of octal digits which specify a character code.
771 Any nondigit terminates the sequence. If the terminator is a RET,
772 it is discarded; any other terminator is used itself as input.
773 The variable `read-quoted-char-radix' specifies the radix for this feature;
774 set it to 10 or 16 to use decimal or hex instead of octal.
776 In overwrite mode, this function inserts the character anyway, and
777 does not handle octal digits specially. This means that if you use
778 overwrite as your normal editing mode, you can use this function to
779 insert characters when necessary.
781 In binary overwrite mode, this function does overwrite, and octal
782 digits are interpreted as a character code. This is intended to be
783 useful for editing binary files."
784 (interactive "*p")
785 (let* ((char
786 ;; Avoid "obsolete" warnings for translation-table-for-input.
787 (with-no-warnings
788 (let (translation-table-for-input input-method-function)
789 (if (or (not overwrite-mode)
790 (eq overwrite-mode 'overwrite-mode-binary))
791 (read-quoted-char)
792 (read-char))))))
793 ;; This used to assume character codes 0240 - 0377 stand for
794 ;; characters in some single-byte character set, and converted them
795 ;; to Emacs characters. But in 23.1 this feature is deprecated
796 ;; in favor of inserting the corresponding Unicode characters.
797 ;; (if (and enable-multibyte-characters
798 ;; (>= char ?\240)
799 ;; (<= char ?\377))
800 ;; (setq char (unibyte-char-to-multibyte char)))
801 (unless (characterp char)
802 (user-error "%s is not a valid character"
803 (key-description (vector char))))
804 (if (> arg 0)
805 (if (eq overwrite-mode 'overwrite-mode-binary)
806 (delete-char arg)))
807 (while (> arg 0)
808 (insert-and-inherit char)
809 (setq arg (1- arg)))))
811 (defun forward-to-indentation (&optional arg)
812 "Move forward ARG lines and position at first nonblank character."
813 (interactive "^p")
814 (forward-line (or arg 1))
815 (skip-chars-forward " \t"))
817 (defun backward-to-indentation (&optional arg)
818 "Move backward ARG lines and position at first nonblank character."
819 (interactive "^p")
820 (forward-line (- (or arg 1)))
821 (skip-chars-forward " \t"))
823 (defun back-to-indentation ()
824 "Move point to the first non-whitespace character on this line."
825 (interactive "^")
826 (beginning-of-line 1)
827 (skip-syntax-forward " " (line-end-position))
828 ;; Move back over chars that have whitespace syntax but have the p flag.
829 (backward-prefix-chars))
831 (defun fixup-whitespace ()
832 "Fixup white space between objects around point.
833 Leave one space or none, according to the context."
834 (interactive "*")
835 (save-excursion
836 (delete-horizontal-space)
837 (if (or (looking-at "^\\|\\s)")
838 (save-excursion (forward-char -1)
839 (looking-at "$\\|\\s(\\|\\s'")))
841 (insert ?\s))))
843 (defun delete-horizontal-space (&optional backward-only)
844 "Delete all spaces and tabs around point.
845 If BACKWARD-ONLY is non-nil, only delete them before point."
846 (interactive "*P")
847 (let ((orig-pos (point)))
848 (delete-region
849 (if backward-only
850 orig-pos
851 (progn
852 (skip-chars-forward " \t")
853 (constrain-to-field nil orig-pos t)))
854 (progn
855 (skip-chars-backward " \t")
856 (constrain-to-field nil orig-pos)))))
858 (defun just-one-space (&optional n)
859 "Delete all spaces and tabs around point, leaving one space (or N spaces).
860 If N is negative, delete newlines as well, leaving -N spaces.
861 See also `cycle-spacing'."
862 (interactive "*p")
863 (cycle-spacing n nil 'single-shot))
865 (defvar cycle-spacing--context nil
866 "Store context used in consecutive calls to `cycle-spacing' command.
867 The first time `cycle-spacing' runs, it saves in this variable:
868 its N argument, the original point position, and the original spacing
869 around point.")
871 (defun cycle-spacing (&optional n preserve-nl-back mode)
872 "Manipulate whitespace around point in a smart way.
873 In interactive use, this function behaves differently in successive
874 consecutive calls.
876 The first call in a sequence acts like `just-one-space'.
877 It deletes all spaces and tabs around point, leaving one space
878 \(or N spaces). N is the prefix argument. If N is negative,
879 it deletes newlines as well, leaving -N spaces.
880 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
882 The second call in a sequence deletes all spaces.
884 The third call in a sequence restores the original whitespace (and point).
886 If MODE is `single-shot', it only performs the first step in the sequence.
887 If MODE is `fast' and the first step would not result in any change
888 \(i.e., there are exactly (abs N) spaces around point),
889 the function goes straight to the second step.
891 Repeatedly calling the function with different values of N starts a
892 new sequence each time."
893 (interactive "*p")
894 (let ((orig-pos (point))
895 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
896 (num (abs (or n 1))))
897 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
898 (constrain-to-field nil orig-pos)
899 (cond
900 ;; Command run for the first time, single-shot mode or different argument
901 ((or (eq 'single-shot mode)
902 (not (equal last-command this-command))
903 (not cycle-spacing--context)
904 (not (eq (car cycle-spacing--context) n)))
905 (let* ((start (point))
906 (num (- num (skip-chars-forward " " (+ num (point)))))
907 (mid (point))
908 (end (progn
909 (skip-chars-forward skip-characters)
910 (constrain-to-field nil orig-pos t))))
911 (setq cycle-spacing--context ;; Save for later.
912 ;; Special handling for case where there was no space at all.
913 (unless (= start end)
914 (cons n (cons orig-pos (buffer-substring start (point))))))
915 ;; If this run causes no change in buffer content, delete all spaces,
916 ;; otherwise delete all excess spaces.
917 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
918 start mid) end)
919 (insert (make-string num ?\s))))
921 ;; Command run for the second time.
922 ((not (equal orig-pos (point)))
923 (delete-region (point) orig-pos))
925 ;; Command run for the third time.
927 (insert (cddr cycle-spacing--context))
928 (goto-char (cadr cycle-spacing--context))
929 (setq cycle-spacing--context nil)))))
931 (defun beginning-of-buffer (&optional arg)
932 "Move point to the beginning of the buffer.
933 With numeric arg N, put point N/10 of the way from the beginning.
934 If the buffer is narrowed, this command uses the beginning of the
935 accessible part of the buffer.
937 Push mark at previous position, unless either a \\[universal-argument] prefix
938 is supplied, or Transient Mark mode is enabled and the mark is active."
939 (declare (interactive-only "use `(goto-char (point-min))' instead."))
940 (interactive "^P")
941 (or (consp arg)
942 (region-active-p)
943 (push-mark))
944 (let ((size (- (point-max) (point-min))))
945 (goto-char (if (and arg (not (consp arg)))
946 (+ (point-min)
947 (if (> size 10000)
948 ;; Avoid overflow for large buffer sizes!
949 (* (prefix-numeric-value arg)
950 (/ size 10))
951 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
952 (point-min))))
953 (if (and arg (not (consp arg))) (forward-line 1)))
955 (defun end-of-buffer (&optional arg)
956 "Move point to the end of the buffer.
957 With numeric arg N, put point N/10 of the way from the end.
958 If the buffer is narrowed, this command uses the end of the
959 accessible part of the buffer.
961 Push mark at previous position, unless either a \\[universal-argument] prefix
962 is supplied, or Transient Mark mode is enabled and the mark is active."
963 (declare (interactive-only "use `(goto-char (point-max))' instead."))
964 (interactive "^P")
965 (or (consp arg) (region-active-p) (push-mark))
966 (let ((size (- (point-max) (point-min))))
967 (goto-char (if (and arg (not (consp arg)))
968 (- (point-max)
969 (if (> size 10000)
970 ;; Avoid overflow for large buffer sizes!
971 (* (prefix-numeric-value arg)
972 (/ size 10))
973 (/ (* size (prefix-numeric-value arg)) 10)))
974 (point-max))))
975 ;; If we went to a place in the middle of the buffer,
976 ;; adjust it to the beginning of a line.
977 (cond ((and arg (not (consp arg))) (forward-line 1))
978 ((and (eq (current-buffer) (window-buffer))
979 (> (point) (window-end nil t)))
980 ;; If the end of the buffer is not already on the screen,
981 ;; then scroll specially to put it near, but not at, the bottom.
982 (overlay-recenter (point))
983 (recenter -3))))
985 (defcustom delete-active-region t
986 "Whether single-char deletion commands delete an active region.
987 This has an effect only if Transient Mark mode is enabled, and
988 affects `delete-forward-char' and `delete-backward-char', though
989 not `delete-char'.
991 If the value is the symbol `kill', the active region is killed
992 instead of deleted."
993 :type '(choice (const :tag "Delete active region" t)
994 (const :tag "Kill active region" kill)
995 (const :tag "Do ordinary deletion" nil))
996 :group 'killing
997 :version "24.1")
999 (defvar region-extract-function
1000 (lambda (delete)
1001 (when (region-beginning)
1002 (cond
1003 ((eq delete 'bounds)
1004 (list (cons (region-beginning) (region-end))))
1005 ((eq delete 'delete-only)
1006 (delete-region (region-beginning) (region-end)))
1008 (filter-buffer-substring (region-beginning) (region-end) delete)))))
1009 "Function to get the region's content.
1010 Called with one argument DELETE.
1011 If DELETE is `delete-only', then only delete the region and the return value
1012 is undefined. If DELETE is nil, just return the content as a string.
1013 If DELETE is `bounds', then don't delete, but just return the
1014 boundaries of the region as a list of (START . END) positions.
1015 If anything else, delete the region and return its content as a string,
1016 after filtering it with `filter-buffer-substring'.")
1018 (defvar region-insert-function
1019 (lambda (lines)
1020 (let ((first t))
1021 (while lines
1022 (or first
1023 (insert ?\n))
1024 (insert-for-yank (car lines))
1025 (setq lines (cdr lines)
1026 first nil))))
1027 "Function to insert the region's content.
1028 Called with one argument LINES.
1029 Insert the region as a list of lines.")
1031 (defun delete-backward-char (n &optional killflag)
1032 "Delete the previous N characters (following if N is negative).
1033 If Transient Mark mode is enabled, the mark is active, and N is 1,
1034 delete the text in the region and deactivate the mark instead.
1035 To disable this, set option `delete-active-region' to nil.
1037 Optional second arg KILLFLAG, if non-nil, means to kill (save in
1038 kill ring) instead of delete. Interactively, N is the prefix
1039 arg, and KILLFLAG is set if N is explicitly specified.
1041 When killing, the killed text is filtered by
1042 `filter-buffer-substring' before it is saved in the kill ring, so
1043 the actual saved text might be different from what was killed.
1045 In Overwrite mode, single character backward deletion may replace
1046 tabs with spaces so as to back over columns, unless point is at
1047 the end of the line."
1048 (declare (interactive-only delete-char))
1049 (interactive "p\nP")
1050 (unless (integerp n)
1051 (signal 'wrong-type-argument (list 'integerp n)))
1052 (cond ((and (use-region-p)
1053 delete-active-region
1054 (= n 1))
1055 ;; If a region is active, kill or delete it.
1056 (if (eq delete-active-region 'kill)
1057 (kill-region (region-beginning) (region-end) 'region)
1058 (funcall region-extract-function 'delete-only)))
1059 ;; In Overwrite mode, maybe untabify while deleting
1060 ((null (or (null overwrite-mode)
1061 (<= n 0)
1062 (memq (char-before) '(?\t ?\n))
1063 (eobp)
1064 (eq (char-after) ?\n)))
1065 (let ((ocol (current-column)))
1066 (delete-char (- n) killflag)
1067 (save-excursion
1068 (insert-char ?\s (- ocol (current-column)) nil))))
1069 ;; Otherwise, do simple deletion.
1070 (t (delete-char (- n) killflag))))
1072 (defun delete-forward-char (n &optional killflag)
1073 "Delete the following N characters (previous if N is negative).
1074 If Transient Mark mode is enabled, the mark is active, and N is 1,
1075 delete the text in the region and deactivate the mark instead.
1076 To disable this, set variable `delete-active-region' to nil.
1078 Optional second arg KILLFLAG non-nil means to kill (save in kill
1079 ring) instead of delete. Interactively, N is the prefix arg, and
1080 KILLFLAG is set if N was explicitly specified.
1082 When killing, the killed text is filtered by
1083 `filter-buffer-substring' before it is saved in the kill ring, so
1084 the actual saved text might be different from what was killed."
1085 (declare (interactive-only delete-char))
1086 (interactive "p\nP")
1087 (unless (integerp n)
1088 (signal 'wrong-type-argument (list 'integerp n)))
1089 (cond ((and (use-region-p)
1090 delete-active-region
1091 (= n 1))
1092 ;; If a region is active, kill or delete it.
1093 (if (eq delete-active-region 'kill)
1094 (kill-region (region-beginning) (region-end) 'region)
1095 (funcall region-extract-function 'delete-only)))
1097 ;; Otherwise, do simple deletion.
1098 (t (delete-char n killflag))))
1100 (defun mark-whole-buffer ()
1101 "Put point at beginning and mark at end of buffer.
1102 If narrowing is in effect, only uses the accessible part of the buffer.
1103 You probably should not use this function in Lisp programs;
1104 it is usually a mistake for a Lisp function to use any subroutine
1105 that uses or sets the mark."
1106 (declare (interactive-only t))
1107 (interactive)
1108 (push-mark (point))
1109 (push-mark (point-max) nil t)
1110 ;; This is really `point-min' in most cases, but if we're in the
1111 ;; minibuffer, this is at the end of the prompt.
1112 (goto-char (minibuffer-prompt-end)))
1115 ;; Counting lines, one way or another.
1117 (defun goto-line (line &optional buffer)
1118 "Go to LINE, counting from line 1 at beginning of buffer.
1119 If called interactively, a numeric prefix argument specifies
1120 LINE; without a numeric prefix argument, read LINE from the
1121 minibuffer.
1123 If optional argument BUFFER is non-nil, switch to that buffer and
1124 move to line LINE there. If called interactively with \\[universal-argument]
1125 as argument, BUFFER is the most recently selected other buffer.
1127 Prior to moving point, this function sets the mark (without
1128 activating it), unless Transient Mark mode is enabled and the
1129 mark is already active.
1131 This function is usually the wrong thing to use in a Lisp program.
1132 What you probably want instead is something like:
1133 (goto-char (point-min))
1134 (forward-line (1- N))
1135 If at all possible, an even better solution is to use char counts
1136 rather than line counts."
1137 (declare (interactive-only forward-line))
1138 (interactive
1139 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1140 (list (prefix-numeric-value current-prefix-arg))
1141 ;; Look for a default, a number in the buffer at point.
1142 (let* ((default
1143 (save-excursion
1144 (skip-chars-backward "0-9")
1145 (if (looking-at "[0-9]")
1146 (string-to-number
1147 (buffer-substring-no-properties
1148 (point)
1149 (progn (skip-chars-forward "0-9")
1150 (point)))))))
1151 ;; Decide if we're switching buffers.
1152 (buffer
1153 (if (consp current-prefix-arg)
1154 (other-buffer (current-buffer) t)))
1155 (buffer-prompt
1156 (if buffer
1157 (concat " in " (buffer-name buffer))
1158 "")))
1159 ;; Read the argument, offering that number (if any) as default.
1160 (list (read-number (format "Goto line%s: " buffer-prompt)
1161 (list default (line-number-at-pos)))
1162 buffer))))
1163 ;; Switch to the desired buffer, one way or another.
1164 (if buffer
1165 (let ((window (get-buffer-window buffer)))
1166 (if window (select-window window)
1167 (switch-to-buffer-other-window buffer))))
1168 ;; Leave mark at previous position
1169 (or (region-active-p) (push-mark))
1170 ;; Move to the specified line number in that buffer.
1171 (save-restriction
1172 (widen)
1173 (goto-char (point-min))
1174 (if (eq selective-display t)
1175 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1176 (forward-line (1- line)))))
1178 (defun count-words-region (start end &optional arg)
1179 "Count the number of words in the region.
1180 If called interactively, print a message reporting the number of
1181 lines, words, and characters in the region (whether or not the
1182 region is active); with prefix ARG, report for the entire buffer
1183 rather than the region.
1185 If called from Lisp, return the number of words between positions
1186 START and END."
1187 (interactive (if current-prefix-arg
1188 (list nil nil current-prefix-arg)
1189 (list (region-beginning) (region-end) nil)))
1190 (cond ((not (called-interactively-p 'any))
1191 (count-words start end))
1192 (arg
1193 (count-words--buffer-message))
1195 (count-words--message "Region" start end))))
1197 (defun count-words (start end)
1198 "Count words between START and END.
1199 If called interactively, START and END are normally the start and
1200 end of the buffer; but if the region is active, START and END are
1201 the start and end of the region. Print a message reporting the
1202 number of lines, words, and chars.
1204 If called from Lisp, return the number of words between START and
1205 END, without printing any message."
1206 (interactive (list nil nil))
1207 (cond ((not (called-interactively-p 'any))
1208 (let ((words 0))
1209 (save-excursion
1210 (save-restriction
1211 (narrow-to-region start end)
1212 (goto-char (point-min))
1213 (while (forward-word-strictly 1)
1214 (setq words (1+ words)))))
1215 words))
1216 ((use-region-p)
1217 (call-interactively 'count-words-region))
1219 (count-words--buffer-message))))
1221 (defun count-words--buffer-message ()
1222 (count-words--message
1223 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1224 (point-min) (point-max)))
1226 (defun count-words--message (str start end)
1227 (let ((lines (count-lines start end))
1228 (words (count-words start end))
1229 (chars (- end start)))
1230 (message "%s has %d line%s, %d word%s, and %d character%s."
1232 lines (if (= lines 1) "" "s")
1233 words (if (= words 1) "" "s")
1234 chars (if (= chars 1) "" "s"))))
1236 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1238 (defun what-line ()
1239 "Print the current buffer line number and narrowed line number of point."
1240 (interactive)
1241 (let ((start (point-min))
1242 (n (line-number-at-pos)))
1243 (if (= start 1)
1244 (message "Line %d" n)
1245 (save-excursion
1246 (save-restriction
1247 (widen)
1248 (message "line %d (narrowed line %d)"
1249 (+ n (line-number-at-pos start) -1) n))))))
1251 (defun count-lines (start end)
1252 "Return number of lines between START and END.
1253 This is usually the number of newlines between them,
1254 but can be one more if START is not equal to END
1255 and the greater of them is not at the start of a line."
1256 (save-excursion
1257 (save-restriction
1258 (narrow-to-region start end)
1259 (goto-char (point-min))
1260 (if (eq selective-display t)
1261 (save-match-data
1262 (let ((done 0))
1263 (while (re-search-forward "[\n\C-m]" nil t 40)
1264 (setq done (+ 40 done)))
1265 (while (re-search-forward "[\n\C-m]" nil t 1)
1266 (setq done (+ 1 done)))
1267 (goto-char (point-max))
1268 (if (and (/= start end)
1269 (not (bolp)))
1270 (1+ done)
1271 done)))
1272 (- (buffer-size) (forward-line (buffer-size)))))))
1274 (defun line-number-at-pos (&optional pos)
1275 "Return (narrowed) buffer line number at position POS.
1276 If POS is nil, use current buffer location.
1277 Counting starts at (point-min), so the value refers
1278 to the contents of the accessible portion of the buffer."
1279 (let ((opoint (or pos (point))) start)
1280 (save-excursion
1281 (goto-char (point-min))
1282 (setq start (point))
1283 (goto-char opoint)
1284 (forward-line 0)
1285 (1+ (count-lines start (point))))))
1287 (defun what-cursor-position (&optional detail)
1288 "Print info on cursor position (on screen and within buffer).
1289 Also describe the character after point, and give its character code
1290 in octal, decimal and hex.
1292 For a non-ASCII multibyte character, also give its encoding in the
1293 buffer's selected coding system if the coding system encodes the
1294 character safely. If the character is encoded into one byte, that
1295 code is shown in hex. If the character is encoded into more than one
1296 byte, just \"...\" is shown.
1298 In addition, with prefix argument, show details about that character
1299 in *Help* buffer. See also the command `describe-char'."
1300 (interactive "P")
1301 (let* ((char (following-char))
1302 (bidi-fixer
1303 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1304 ;; start a directional embedding, which could completely
1305 ;; disrupt the rest of the line (e.g., RLO will display the
1306 ;; rest of the line right-to-left). So we put an invisible
1307 ;; PDF character after these characters, to end the
1308 ;; embedding, which eliminates any effects on the rest of
1309 ;; the line. For RLE and RLO we also append an invisible
1310 ;; LRM, to avoid reordering the following numerical
1311 ;; characters. For LRI/RLI/FSI we append a PDI.
1312 (cond ((memq char '(?\x202a ?\x202d))
1313 (propertize (string ?\x202c) 'invisible t))
1314 ((memq char '(?\x202b ?\x202e))
1315 (propertize (string ?\x202c ?\x200e) 'invisible t))
1316 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1317 (propertize (string ?\x2069) 'invisible t))
1318 ;; Strong right-to-left characters cause reordering of
1319 ;; the following numerical characters which show the
1320 ;; codepoint, so append LRM to countermand that.
1321 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1322 (propertize (string ?\x200e) 'invisible t))
1324 "")))
1325 (beg (point-min))
1326 (end (point-max))
1327 (pos (point))
1328 (total (buffer-size))
1329 (percent (round (* 100.0 (1- pos)) (max 1 total)))
1330 (hscroll (if (= (window-hscroll) 0)
1332 (format " Hscroll=%d" (window-hscroll))))
1333 (col (current-column)))
1334 (if (= pos end)
1335 (if (or (/= beg 1) (/= end (1+ total)))
1336 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1337 pos total percent beg end col hscroll)
1338 (message "point=%d of %d (EOB) column=%d%s"
1339 pos total col hscroll))
1340 (let ((coding buffer-file-coding-system)
1341 encoded encoding-msg display-prop under-display)
1342 (if (or (not coding)
1343 (eq (coding-system-type coding) t))
1344 (setq coding (default-value 'buffer-file-coding-system)))
1345 (if (eq (char-charset char) 'eight-bit)
1346 (setq encoding-msg
1347 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1348 ;; Check if the character is displayed with some `display'
1349 ;; text property. In that case, set under-display to the
1350 ;; buffer substring covered by that property.
1351 (setq display-prop (get-char-property pos 'display))
1352 (if display-prop
1353 (let ((to (or (next-single-char-property-change pos 'display)
1354 (point-max))))
1355 (if (< to (+ pos 4))
1356 (setq under-display "")
1357 (setq under-display "..."
1358 to (+ pos 4)))
1359 (setq under-display
1360 (concat (buffer-substring-no-properties pos to)
1361 under-display)))
1362 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1363 (setq encoding-msg
1364 (if display-prop
1365 (if (not (stringp display-prop))
1366 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1367 char char char under-display)
1368 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1369 char char char under-display display-prop))
1370 (if encoded
1371 (format "(%d, #o%o, #x%x, file %s)"
1372 char char char
1373 (if (> (length encoded) 1)
1374 "..."
1375 (encoded-string-description encoded coding)))
1376 (format "(%d, #o%o, #x%x)" char char char)))))
1377 (if detail
1378 ;; We show the detailed information about CHAR.
1379 (describe-char (point)))
1380 (if (or (/= beg 1) (/= end (1+ total)))
1381 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1382 (if (< char 256)
1383 (single-key-description char)
1384 (buffer-substring-no-properties (point) (1+ (point))))
1385 bidi-fixer
1386 encoding-msg pos total percent beg end col hscroll)
1387 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1388 (if enable-multibyte-characters
1389 (if (< char 128)
1390 (single-key-description char)
1391 (buffer-substring-no-properties (point) (1+ (point))))
1392 (single-key-description char))
1393 bidi-fixer encoding-msg pos total percent col hscroll))))))
1395 ;; Initialize read-expression-map. It is defined at C level.
1396 (defvar read-expression-map
1397 (let ((m (make-sparse-keymap)))
1398 (define-key m "\M-\t" 'completion-at-point)
1399 ;; Might as well bind TAB to completion, since inserting a TAB char is
1400 ;; much too rarely useful.
1401 (define-key m "\t" 'completion-at-point)
1402 (set-keymap-parent m minibuffer-local-map)
1405 (defun read-minibuffer (prompt &optional initial-contents)
1406 "Return a Lisp object read using the minibuffer, unevaluated.
1407 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1408 is a string to insert in the minibuffer before reading.
1409 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1410 Such arguments are used as in `read-from-minibuffer'.)"
1411 ;; Used for interactive spec `x'.
1412 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1413 t 'minibuffer-history))
1415 (defun eval-minibuffer (prompt &optional initial-contents)
1416 "Return value of Lisp expression read using the minibuffer.
1417 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1418 is a string to insert in the minibuffer before reading.
1419 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1420 Such arguments are used as in `read-from-minibuffer'.)"
1421 ;; Used for interactive spec `X'.
1422 (eval (read--expression prompt initial-contents)))
1424 (defvar minibuffer-completing-symbol nil
1425 "Non-nil means completing a Lisp symbol in the minibuffer.")
1426 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1428 (defvar minibuffer-default nil
1429 "The current default value or list of default values in the minibuffer.
1430 The functions `read-from-minibuffer' and `completing-read' bind
1431 this variable locally.")
1433 (defcustom eval-expression-print-level 4
1434 "Value for `print-level' while printing value in `eval-expression'.
1435 A value of nil means no limit."
1436 :group 'lisp
1437 :type '(choice (const :tag "No Limit" nil) integer)
1438 :version "21.1")
1440 (defcustom eval-expression-print-length 12
1441 "Value for `print-length' while printing value in `eval-expression'.
1442 A value of nil means no limit."
1443 :group 'lisp
1444 :type '(choice (const :tag "No Limit" nil) integer)
1445 :version "21.1")
1447 (defcustom eval-expression-debug-on-error t
1448 "If non-nil set `debug-on-error' to t in `eval-expression'.
1449 If nil, don't change the value of `debug-on-error'."
1450 :group 'lisp
1451 :type 'boolean
1452 :version "21.1")
1454 (defun eval-expression-print-format (value)
1455 "If VALUE in an integer, return a specially formatted string.
1456 This string will typically look like \" (#o1, #x1, ?\\C-a)\".
1457 If VALUE is not an integer, nil is returned.
1458 This function is used by functions like `prin1' that display the
1459 result of expression evaluation."
1460 (if (and (integerp value)
1461 (or (eq standard-output t)
1462 (zerop (prefix-numeric-value current-prefix-arg))))
1463 (let ((char-string
1464 (if (and (characterp value)
1465 (char-displayable-p value))
1466 (prin1-char value))))
1467 (if char-string
1468 (format " (#o%o, #x%x, %s)" value value char-string)
1469 (format " (#o%o, #x%x)" value value)))))
1471 (defvar eval-expression-minibuffer-setup-hook nil
1472 "Hook run by `eval-expression' when entering the minibuffer.")
1474 (defun read--expression (prompt &optional initial-contents)
1475 (let ((minibuffer-completing-symbol t))
1476 (minibuffer-with-setup-hook
1477 (lambda ()
1478 ;; FIXME: call emacs-lisp-mode?
1479 (add-function :before-until (local 'eldoc-documentation-function)
1480 #'elisp-eldoc-documentation-function)
1481 (add-hook 'completion-at-point-functions
1482 #'elisp-completion-at-point nil t)
1483 (run-hooks 'eval-expression-minibuffer-setup-hook))
1484 (read-from-minibuffer prompt initial-contents
1485 read-expression-map t
1486 'read-expression-history))))
1488 ;; We define this, rather than making `eval' interactive,
1489 ;; for the sake of completion of names like eval-region, eval-buffer.
1490 (defun eval-expression (exp &optional insert-value)
1491 "Evaluate EXP and print value in the echo area.
1492 When called interactively, read an Emacs Lisp expression and evaluate it.
1493 Value is also consed on to front of the variable `values'.
1494 If the resulting value is an integer, it will be printed in
1495 several additional formats (octal, hexadecimal, and character).
1496 Optional argument INSERT-VALUE non-nil (interactively, with
1497 prefix argument) means insert the result into the current buffer
1498 instead of printing it in the echo area.
1500 Normally, this function truncates long output according to the value
1501 of the variables `eval-expression-print-length' and
1502 `eval-expression-print-level'. With a prefix argument of zero,
1503 however, there is no such truncation.
1505 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1506 minibuffer.
1508 If `eval-expression-debug-on-error' is non-nil, which is the default,
1509 this command arranges for all errors to enter the debugger."
1510 (interactive
1511 (list (read--expression "Eval: ")
1512 current-prefix-arg))
1514 (if (null eval-expression-debug-on-error)
1515 (push (eval exp lexical-binding) values)
1516 (let ((old-value (make-symbol "t")) new-value)
1517 ;; Bind debug-on-error to something unique so that we can
1518 ;; detect when evalled code changes it.
1519 (let ((debug-on-error old-value))
1520 (push (eval (macroexpand-all exp) lexical-binding) values)
1521 (setq new-value debug-on-error))
1522 ;; If evalled code has changed the value of debug-on-error,
1523 ;; propagate that change to the global binding.
1524 (unless (eq old-value new-value)
1525 (setq debug-on-error new-value))))
1527 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
1528 eval-expression-print-length))
1529 (print-level (and (not (zerop (prefix-numeric-value insert-value)))
1530 eval-expression-print-level))
1531 (deactivate-mark))
1532 (if insert-value
1533 (with-no-warnings
1534 (let ((standard-output (current-buffer)))
1535 (prog1
1536 (prin1 (car values))
1537 (when (zerop (prefix-numeric-value insert-value))
1538 (let ((str (eval-expression-print-format (car values))))
1539 (if str (princ str)))))))
1540 (prog1
1541 (prin1 (car values) t)
1542 (let ((str (eval-expression-print-format (car values))))
1543 (if str (princ str t)))))))
1545 (defun edit-and-eval-command (prompt command)
1546 "Prompting with PROMPT, let user edit COMMAND and eval result.
1547 COMMAND is a Lisp expression. Let user edit that expression in
1548 the minibuffer, then read and evaluate the result."
1549 (let ((command
1550 (let ((print-level nil)
1551 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1552 (unwind-protect
1553 (read-from-minibuffer prompt
1554 (prin1-to-string command)
1555 read-expression-map t
1556 'command-history)
1557 ;; If command was added to command-history as a string,
1558 ;; get rid of that. We want only evaluable expressions there.
1559 (if (stringp (car command-history))
1560 (setq command-history (cdr command-history)))))))
1562 ;; If command to be redone does not match front of history,
1563 ;; add it to the history.
1564 (or (equal command (car command-history))
1565 (setq command-history (cons command command-history)))
1566 (eval command)))
1568 (defun repeat-complex-command (arg)
1569 "Edit and re-evaluate last complex command, or ARGth from last.
1570 A complex command is one which used the minibuffer.
1571 The command is placed in the minibuffer as a Lisp form for editing.
1572 The result is executed, repeating the command as changed.
1573 If the command has been changed or is not the most recent previous
1574 command it is added to the front of the command history.
1575 You can use the minibuffer history commands \
1576 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1577 to get different commands to edit and resubmit."
1578 (interactive "p")
1579 (let ((elt (nth (1- arg) command-history))
1580 newcmd)
1581 (if elt
1582 (progn
1583 (setq newcmd
1584 (let ((print-level nil)
1585 (minibuffer-history-position arg)
1586 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1587 (unwind-protect
1588 (read-from-minibuffer
1589 "Redo: " (prin1-to-string elt) read-expression-map t
1590 (cons 'command-history arg))
1592 ;; If command was added to command-history as a
1593 ;; string, get rid of that. We want only
1594 ;; evaluable expressions there.
1595 (if (stringp (car command-history))
1596 (setq command-history (cdr command-history))))))
1598 ;; If command to be redone does not match front of history,
1599 ;; add it to the history.
1600 (or (equal newcmd (car command-history))
1601 (setq command-history (cons newcmd command-history)))
1602 (apply #'funcall-interactively
1603 (car newcmd)
1604 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1605 (if command-history
1606 (error "Argument %d is beyond length of command history" arg)
1607 (error "There are no previous complex commands to repeat")))))
1610 (defvar extended-command-history nil)
1611 (defvar execute-extended-command--last-typed nil)
1613 (defun read-extended-command ()
1614 "Read command name to invoke in `execute-extended-command'."
1615 (minibuffer-with-setup-hook
1616 (lambda ()
1617 (add-hook 'post-self-insert-hook
1618 (lambda ()
1619 (setq execute-extended-command--last-typed
1620 (minibuffer-contents)))
1621 nil 'local)
1622 (set (make-local-variable 'minibuffer-default-add-function)
1623 (lambda ()
1624 ;; Get a command name at point in the original buffer
1625 ;; to propose it after M-n.
1626 (with-current-buffer (window-buffer (minibuffer-selected-window))
1627 (and (commandp (function-called-at-point))
1628 (format "%S" (function-called-at-point)))))))
1629 ;; Read a string, completing from and restricting to the set of
1630 ;; all defined commands. Don't provide any initial input.
1631 ;; Save the command read on the extended-command history list.
1632 (completing-read
1633 (concat (cond
1634 ((eq current-prefix-arg '-) "- ")
1635 ((and (consp current-prefix-arg)
1636 (eq (car current-prefix-arg) 4)) "C-u ")
1637 ((and (consp current-prefix-arg)
1638 (integerp (car current-prefix-arg)))
1639 (format "%d " (car current-prefix-arg)))
1640 ((integerp current-prefix-arg)
1641 (format "%d " current-prefix-arg)))
1642 ;; This isn't strictly correct if `execute-extended-command'
1643 ;; is bound to anything else (e.g. [menu]).
1644 ;; It could use (key-description (this-single-command-keys)),
1645 ;; but actually a prompt other than "M-x" would be confusing,
1646 ;; because "M-x" is a well-known prompt to read a command
1647 ;; and it serves as a shorthand for "Extended command: ".
1648 "M-x ")
1649 (lambda (string pred action)
1650 (let ((pred
1651 (if (memq action '(nil t))
1652 ;; Exclude obsolete commands from completions.
1653 (lambda (sym)
1654 (and (funcall pred sym)
1655 (or (equal string (symbol-name sym))
1656 (not (get sym 'byte-obsolete-info)))))
1657 pred)))
1658 (complete-with-action action obarray string pred)))
1659 #'commandp t nil 'extended-command-history)))
1661 (defcustom suggest-key-bindings t
1662 "Non-nil means show the equivalent key-binding when M-x command has one.
1663 The value can be a length of time to show the message for.
1664 If the value is non-nil and not a number, we wait 2 seconds."
1665 :group 'keyboard
1666 :type '(choice (const :tag "off" nil)
1667 (integer :tag "time" 2)
1668 (other :tag "on")))
1670 (defcustom extended-command-suggest-shorter t
1671 "If non-nil, show a shorter M-x invocation when there is one."
1672 :group 'keyboard
1673 :type 'boolean
1674 :version "26.1")
1676 (defun execute-extended-command--shorter-1 (name length)
1677 (cond
1678 ((zerop length) (list ""))
1679 ((equal name "") nil)
1681 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1682 (execute-extended-command--shorter-1
1683 (substring name 1) (1- length)))
1684 (when (string-match "\\`\\(-\\)?[^-]*" name)
1685 (execute-extended-command--shorter-1
1686 (substring name (match-end 0)) length))))))
1688 (defun execute-extended-command--shorter (name typed)
1689 (let ((candidates '())
1690 (max (length typed))
1691 (len 1)
1692 binding)
1693 (while (and (not binding)
1694 (progn
1695 (unless candidates
1696 (setq len (1+ len))
1697 (setq candidates (execute-extended-command--shorter-1
1698 name len)))
1699 ;; Don't show the help message if the binding isn't
1700 ;; significantly shorter than the M-x command the user typed.
1701 (< len (- max 5))))
1702 (let ((candidate (pop candidates)))
1703 (when (equal name
1704 (car-safe (completion-try-completion
1705 candidate obarray 'commandp len)))
1706 (setq binding candidate))))
1707 binding))
1709 (defun execute-extended-command (prefixarg &optional command-name typed)
1710 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1711 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1712 "Read a command name, then read the arguments and call the command.
1713 To pass a prefix argument to the command you are
1714 invoking, give a prefix argument to `execute-extended-command'."
1715 (declare (interactive-only command-execute))
1716 ;; FIXME: Remember the actual text typed by the user before completion,
1717 ;; so that we don't later on suggest the same shortening.
1718 (interactive
1719 (let ((execute-extended-command--last-typed nil))
1720 (list current-prefix-arg
1721 (read-extended-command)
1722 execute-extended-command--last-typed)))
1723 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1724 (unless command-name
1725 (let ((current-prefix-arg prefixarg) ; for prompt
1726 (execute-extended-command--last-typed nil))
1727 (setq command-name (read-extended-command))
1728 (setq typed execute-extended-command--last-typed)))
1729 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1730 (binding (and suggest-key-bindings
1731 (not executing-kbd-macro)
1732 (where-is-internal function overriding-local-map t))))
1733 (unless (commandp function)
1734 (error "`%s' is not a valid command name" command-name))
1735 (setq this-command function)
1736 ;; Normally `real-this-command' should never be changed, but here we really
1737 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1738 ;; binding" for <cmd>, so the command the user really wanted to run is
1739 ;; `function' and not `execute-extended-command'. The difference is
1740 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1741 (setq real-this-command function)
1742 (let ((prefix-arg prefixarg))
1743 (command-execute function 'record))
1744 ;; If enabled, show which key runs this command.
1745 ;; But first wait, and skip the message if there is input.
1746 (let* ((waited
1747 ;; If this command displayed something in the echo area;
1748 ;; wait a few seconds, then display our suggestion message.
1749 ;; FIXME: Wait *after* running post-command-hook!
1750 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1751 ;; find a better answer anyway!
1752 (when suggest-key-bindings
1753 (sit-for (cond
1754 ((zerop (length (current-message))) 0)
1755 ((numberp suggest-key-bindings) suggest-key-bindings)
1756 (t 2))))))
1757 (when (and waited (not (consp unread-command-events)))
1758 (unless (or (not extended-command-suggest-shorter)
1759 binding executing-kbd-macro (not (symbolp function))
1760 (<= (length (symbol-name function)) 2))
1761 ;; There's no binding for CMD. Let's try and find the shortest
1762 ;; string to use in M-x.
1763 ;; FIXME: Can be slow. Cache it maybe?
1764 (while-no-input
1765 (setq binding (execute-extended-command--shorter
1766 (symbol-name function) typed))))
1767 (when binding
1768 (with-temp-message
1769 (format-message "You can run the command `%s' with %s"
1770 function
1771 (if (stringp binding)
1772 (concat "M-x " binding " RET")
1773 (key-description binding)))
1774 (sit-for (if (numberp suggest-key-bindings)
1775 suggest-key-bindings
1776 2))))))))
1778 (defun command-execute (cmd &optional record-flag keys special)
1779 ;; BEWARE: Called directly from the C code.
1780 "Execute CMD as an editor command.
1781 CMD must be a symbol that satisfies the `commandp' predicate.
1782 Optional second arg RECORD-FLAG non-nil
1783 means unconditionally put this command in the variable `command-history'.
1784 Otherwise, that is done only if an arg is read using the minibuffer.
1785 The argument KEYS specifies the value to use instead of (this-command-keys)
1786 when reading the arguments; if it is nil, (this-command-keys) is used.
1787 The argument SPECIAL, if non-nil, means that this command is executing
1788 a special event, so ignore the prefix argument and don't clear it."
1789 (setq debug-on-next-call nil)
1790 (let ((prefixarg (unless special
1791 ;; FIXME: This should probably be done around
1792 ;; pre-command-hook rather than here!
1793 (prog1 prefix-arg
1794 (setq current-prefix-arg prefix-arg)
1795 (setq prefix-arg nil)
1796 (when current-prefix-arg
1797 (prefix-command-update))))))
1798 (if (and (symbolp cmd)
1799 (get cmd 'disabled)
1800 disabled-command-function)
1801 ;; FIXME: Weird calling convention!
1802 (run-hooks 'disabled-command-function)
1803 (let ((final cmd))
1804 (while
1805 (progn
1806 (setq final (indirect-function final))
1807 (if (autoloadp final)
1808 (setq final (autoload-do-load final cmd)))))
1809 (cond
1810 ((arrayp final)
1811 ;; If requested, place the macro in the command history. For
1812 ;; other sorts of commands, call-interactively takes care of this.
1813 (when record-flag
1814 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1815 ;; Don't keep command history around forever.
1816 (when (and (numberp history-length) (> history-length 0))
1817 (let ((cell (nthcdr history-length command-history)))
1818 (if (consp cell) (setcdr cell nil)))))
1819 (execute-kbd-macro final prefixarg))
1821 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1822 (prog1 (call-interactively cmd record-flag keys)
1823 (when (and (symbolp cmd)
1824 (get cmd 'byte-obsolete-info)
1825 (not (get cmd 'command-execute-obsolete-warned)))
1826 (put cmd 'command-execute-obsolete-warned t)
1827 (message "%s" (macroexp--obsolete-warning
1828 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1830 (defvar minibuffer-history nil
1831 "Default minibuffer history list.
1832 This is used for all minibuffer input
1833 except when an alternate history list is specified.
1835 Maximum length of the history list is determined by the value
1836 of `history-length', which see.")
1837 (defvar minibuffer-history-sexp-flag nil
1838 "Control whether history list elements are expressions or strings.
1839 If the value of this variable equals current minibuffer depth,
1840 they are expressions; otherwise they are strings.
1841 \(That convention is designed to do the right thing for
1842 recursive uses of the minibuffer.)")
1843 (setq minibuffer-history-variable 'minibuffer-history)
1844 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1845 (defvar minibuffer-history-search-history nil)
1847 (defvar minibuffer-text-before-history nil
1848 "Text that was in this minibuffer before any history commands.
1849 This is nil if there have not yet been any history commands
1850 in this use of the minibuffer.")
1852 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1854 (defun minibuffer-history-initialize ()
1855 (setq minibuffer-text-before-history nil))
1857 (defun minibuffer-avoid-prompt (_new _old)
1858 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1859 (declare (obsolete cursor-intangible-mode "25.1"))
1860 (constrain-to-field nil (point-max)))
1862 (defcustom minibuffer-history-case-insensitive-variables nil
1863 "Minibuffer history variables for which matching should ignore case.
1864 If a history variable is a member of this list, then the
1865 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1866 commands ignore case when searching it, regardless of `case-fold-search'."
1867 :type '(repeat variable)
1868 :group 'minibuffer)
1870 (defun previous-matching-history-element (regexp n)
1871 "Find the previous history element that matches REGEXP.
1872 \(Previous history elements refer to earlier actions.)
1873 With prefix argument N, search for Nth previous match.
1874 If N is negative, find the next or Nth next match.
1875 Normally, history elements are matched case-insensitively if
1876 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1877 makes the search case-sensitive.
1878 See also `minibuffer-history-case-insensitive-variables'."
1879 (interactive
1880 (let* ((enable-recursive-minibuffers t)
1881 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1883 minibuffer-local-map
1885 'minibuffer-history-search-history
1886 (car minibuffer-history-search-history))))
1887 ;; Use the last regexp specified, by default, if input is empty.
1888 (list (if (string= regexp "")
1889 (if minibuffer-history-search-history
1890 (car minibuffer-history-search-history)
1891 (user-error "No previous history search regexp"))
1892 regexp)
1893 (prefix-numeric-value current-prefix-arg))))
1894 (unless (zerop n)
1895 (if (and (zerop minibuffer-history-position)
1896 (null minibuffer-text-before-history))
1897 (setq minibuffer-text-before-history
1898 (minibuffer-contents-no-properties)))
1899 (let ((history (symbol-value minibuffer-history-variable))
1900 (case-fold-search
1901 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1902 ;; On some systems, ignore case for file names.
1903 (if (memq minibuffer-history-variable
1904 minibuffer-history-case-insensitive-variables)
1906 ;; Respect the user's setting for case-fold-search:
1907 case-fold-search)
1908 nil))
1909 prevpos
1910 match-string
1911 match-offset
1912 (pos minibuffer-history-position))
1913 (while (/= n 0)
1914 (setq prevpos pos)
1915 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1916 (when (= pos prevpos)
1917 (user-error (if (= pos 1)
1918 "No later matching history item"
1919 "No earlier matching history item")))
1920 (setq match-string
1921 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1922 (let ((print-level nil))
1923 (prin1-to-string (nth (1- pos) history)))
1924 (nth (1- pos) history)))
1925 (setq match-offset
1926 (if (< n 0)
1927 (and (string-match regexp match-string)
1928 (match-end 0))
1929 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1930 (match-beginning 1))))
1931 (when match-offset
1932 (setq n (+ n (if (< n 0) 1 -1)))))
1933 (setq minibuffer-history-position pos)
1934 (goto-char (point-max))
1935 (delete-minibuffer-contents)
1936 (insert match-string)
1937 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1938 (if (memq (car (car command-history)) '(previous-matching-history-element
1939 next-matching-history-element))
1940 (setq command-history (cdr command-history))))
1942 (defun next-matching-history-element (regexp n)
1943 "Find the next history element that matches REGEXP.
1944 \(The next history element refers to a more recent action.)
1945 With prefix argument N, search for Nth next match.
1946 If N is negative, find the previous or Nth previous match.
1947 Normally, history elements are matched case-insensitively if
1948 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1949 makes the search case-sensitive."
1950 (interactive
1951 (let* ((enable-recursive-minibuffers t)
1952 (regexp (read-from-minibuffer "Next element matching (regexp): "
1954 minibuffer-local-map
1956 'minibuffer-history-search-history
1957 (car minibuffer-history-search-history))))
1958 ;; Use the last regexp specified, by default, if input is empty.
1959 (list (if (string= regexp "")
1960 (if minibuffer-history-search-history
1961 (car minibuffer-history-search-history)
1962 (user-error "No previous history search regexp"))
1963 regexp)
1964 (prefix-numeric-value current-prefix-arg))))
1965 (previous-matching-history-element regexp (- n)))
1967 (defvar minibuffer-temporary-goal-position nil)
1969 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1970 "Function run by `goto-history-element' before consuming default values.
1971 This is useful to dynamically add more elements to the list of default values
1972 when `goto-history-element' reaches the end of this list.
1973 Before calling this function `goto-history-element' sets the variable
1974 `minibuffer-default-add-done' to t, so it will call this function only
1975 once. In special cases, when this function needs to be called more
1976 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1977 overriding the setting of this variable to t in `goto-history-element'.")
1979 (defvar minibuffer-default-add-done nil
1980 "When nil, add more elements to the end of the list of default values.
1981 The value nil causes `goto-history-element' to add more elements to
1982 the list of defaults when it reaches the end of this list. It does
1983 this by calling a function defined by `minibuffer-default-add-function'.")
1985 (make-variable-buffer-local 'minibuffer-default-add-done)
1987 (defun minibuffer-default-add-completions ()
1988 "Return a list of all completions without the default value.
1989 This function is used to add all elements of the completion table to
1990 the end of the list of defaults just after the default value."
1991 (let ((def minibuffer-default)
1992 (all (all-completions ""
1993 minibuffer-completion-table
1994 minibuffer-completion-predicate)))
1995 (if (listp def)
1996 (append def all)
1997 (cons def (delete def all)))))
1999 (defun goto-history-element (nabs)
2000 "Puts element of the minibuffer history in the minibuffer.
2001 The argument NABS specifies the absolute history position."
2002 (interactive "p")
2003 (when (and (not minibuffer-default-add-done)
2004 (functionp minibuffer-default-add-function)
2005 (< nabs (- (if (listp minibuffer-default)
2006 (length minibuffer-default)
2007 1))))
2008 (setq minibuffer-default-add-done t
2009 minibuffer-default (funcall minibuffer-default-add-function)))
2010 (let ((minimum (if minibuffer-default
2011 (- (if (listp minibuffer-default)
2012 (length minibuffer-default)
2015 elt minibuffer-returned-to-present)
2016 (if (and (zerop minibuffer-history-position)
2017 (null minibuffer-text-before-history))
2018 (setq minibuffer-text-before-history
2019 (minibuffer-contents-no-properties)))
2020 (if (< nabs minimum)
2021 (user-error (if minibuffer-default
2022 "End of defaults; no next item"
2023 "End of history; no default available")))
2024 (if (> nabs (if (listp (symbol-value minibuffer-history-variable))
2025 (length (symbol-value minibuffer-history-variable))
2027 (user-error "Beginning of history; no preceding item"))
2028 (unless (memq last-command '(next-history-element
2029 previous-history-element))
2030 (let ((prompt-end (minibuffer-prompt-end)))
2031 (set (make-local-variable 'minibuffer-temporary-goal-position)
2032 (cond ((<= (point) prompt-end) prompt-end)
2033 ((eobp) nil)
2034 (t (point))))))
2035 (goto-char (point-max))
2036 (delete-minibuffer-contents)
2037 (setq minibuffer-history-position nabs)
2038 (cond ((< nabs 0)
2039 (setq elt (if (listp minibuffer-default)
2040 (nth (1- (abs nabs)) minibuffer-default)
2041 minibuffer-default)))
2042 ((= nabs 0)
2043 (setq elt (or minibuffer-text-before-history ""))
2044 (setq minibuffer-returned-to-present t)
2045 (setq minibuffer-text-before-history nil))
2046 (t (setq elt (nth (1- minibuffer-history-position)
2047 (symbol-value minibuffer-history-variable)))))
2048 (insert
2049 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
2050 (not minibuffer-returned-to-present))
2051 (let ((print-level nil))
2052 (prin1-to-string elt))
2053 elt))
2054 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
2056 (defun next-history-element (n)
2057 "Puts next element of the minibuffer history in the minibuffer.
2058 With argument N, it uses the Nth following element."
2059 (interactive "p")
2060 (or (zerop n)
2061 (goto-history-element (- minibuffer-history-position n))))
2063 (defun previous-history-element (n)
2064 "Puts previous element of the minibuffer history in the minibuffer.
2065 With argument N, it uses the Nth previous element."
2066 (interactive "p")
2067 (or (zerop n)
2068 (goto-history-element (+ minibuffer-history-position n))))
2070 (defun next-line-or-history-element (&optional arg)
2071 "Move cursor vertically down ARG lines, or to the next history element.
2072 When point moves over the bottom line of multi-line minibuffer, puts ARGth
2073 next element of the minibuffer history in the minibuffer."
2074 (interactive "^p")
2075 (or arg (setq arg 1))
2076 (let* ((old-point (point))
2077 ;; Remember the original goal column of possibly multi-line input
2078 ;; excluding the length of the prompt on the first line.
2079 (prompt-end (minibuffer-prompt-end))
2080 (old-column (unless (and (eolp) (> (point) prompt-end))
2081 (if (= (line-number-at-pos) 1)
2082 (max (- (current-column) (1- prompt-end)) 0)
2083 (current-column)))))
2084 (condition-case nil
2085 (with-no-warnings
2086 (next-line arg))
2087 (end-of-buffer
2088 ;; Restore old position since `line-move-visual' moves point to
2089 ;; the end of the line when it fails to go to the next line.
2090 (goto-char old-point)
2091 (next-history-element arg)
2092 ;; Reset `temporary-goal-column' because a correct value is not
2093 ;; calculated when `next-line' above fails by bumping against
2094 ;; the bottom of the minibuffer (bug#22544).
2095 (setq temporary-goal-column 0)
2096 ;; Restore the original goal column on the last line
2097 ;; of possibly multi-line input.
2098 (goto-char (point-max))
2099 (when old-column
2100 (if (= (line-number-at-pos) 1)
2101 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2102 (move-to-column old-column)))))))
2104 (defun previous-line-or-history-element (&optional arg)
2105 "Move cursor vertically up ARG lines, or to the previous history element.
2106 When point moves over the top line of multi-line minibuffer, puts ARGth
2107 previous element of the minibuffer history in the minibuffer."
2108 (interactive "^p")
2109 (or arg (setq arg 1))
2110 (let* ((old-point (point))
2111 ;; Remember the original goal column of possibly multi-line input
2112 ;; excluding the length of the prompt on the first line.
2113 (prompt-end (minibuffer-prompt-end))
2114 (old-column (unless (and (eolp) (> (point) prompt-end))
2115 (if (= (line-number-at-pos) 1)
2116 (max (- (current-column) (1- prompt-end)) 0)
2117 (current-column)))))
2118 (condition-case nil
2119 (with-no-warnings
2120 (previous-line arg))
2121 (beginning-of-buffer
2122 ;; Restore old position since `line-move-visual' moves point to
2123 ;; the beginning of the line when it fails to go to the previous line.
2124 (goto-char old-point)
2125 (previous-history-element arg)
2126 ;; Reset `temporary-goal-column' because a correct value is not
2127 ;; calculated when `previous-line' above fails by bumping against
2128 ;; the top of the minibuffer (bug#22544).
2129 (setq temporary-goal-column 0)
2130 ;; Restore the original goal column on the first line
2131 ;; of possibly multi-line input.
2132 (goto-char (minibuffer-prompt-end))
2133 (if old-column
2134 (if (= (line-number-at-pos) 1)
2135 (move-to-column (+ old-column (1- (minibuffer-prompt-end))))
2136 (move-to-column old-column))
2137 ;; Put the cursor at the end of the visual line instead of the
2138 ;; logical line, so the next `previous-line-or-history-element'
2139 ;; would move to the previous history element, not to a possible upper
2140 ;; visual line from the end of logical line in `line-move-visual' mode.
2141 (end-of-visual-line)
2142 ;; Since `end-of-visual-line' puts the cursor at the beginning
2143 ;; of the next visual line, move it one char back to the end
2144 ;; of the first visual line (bug#22544).
2145 (unless (eolp) (backward-char 1)))))))
2147 (defun next-complete-history-element (n)
2148 "Get next history element which completes the minibuffer before the point.
2149 The contents of the minibuffer after the point are deleted, and replaced
2150 by the new completion."
2151 (interactive "p")
2152 (let ((point-at-start (point)))
2153 (next-matching-history-element
2154 (concat
2155 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
2157 ;; next-matching-history-element always puts us at (point-min).
2158 ;; Move to the position we were at before changing the buffer contents.
2159 ;; This is still sensible, because the text before point has not changed.
2160 (goto-char point-at-start)))
2162 (defun previous-complete-history-element (n)
2164 Get previous history element which completes the minibuffer before the point.
2165 The contents of the minibuffer after the point are deleted, and replaced
2166 by the new completion."
2167 (interactive "p")
2168 (next-complete-history-element (- n)))
2170 ;; For compatibility with the old subr of the same name.
2171 (defun minibuffer-prompt-width ()
2172 "Return the display width of the minibuffer prompt.
2173 Return 0 if current buffer is not a minibuffer."
2174 ;; Return the width of everything before the field at the end of
2175 ;; the buffer; this should be 0 for normal buffers.
2176 (1- (minibuffer-prompt-end)))
2178 ;; isearch minibuffer history
2179 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2181 (defvar minibuffer-history-isearch-message-overlay)
2182 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2184 (defun minibuffer-history-isearch-setup ()
2185 "Set up a minibuffer for using isearch to search the minibuffer history.
2186 Intended to be added to `minibuffer-setup-hook'."
2187 (set (make-local-variable 'isearch-search-fun-function)
2188 'minibuffer-history-isearch-search)
2189 (set (make-local-variable 'isearch-message-function)
2190 'minibuffer-history-isearch-message)
2191 (set (make-local-variable 'isearch-wrap-function)
2192 'minibuffer-history-isearch-wrap)
2193 (set (make-local-variable 'isearch-push-state-function)
2194 'minibuffer-history-isearch-push-state)
2195 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2197 (defun minibuffer-history-isearch-end ()
2198 "Clean up the minibuffer after terminating isearch in the minibuffer."
2199 (if minibuffer-history-isearch-message-overlay
2200 (delete-overlay minibuffer-history-isearch-message-overlay)))
2202 (defun minibuffer-history-isearch-search ()
2203 "Return the proper search function, for isearch in minibuffer history."
2204 (lambda (string bound noerror)
2205 (let ((search-fun
2206 ;; Use standard functions to search within minibuffer text
2207 (isearch-search-fun-default))
2208 found)
2209 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2210 ;; searching forward. Lazy-highlight calls this lambda with the
2211 ;; bound arg, so skip the minibuffer prompt.
2212 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2213 (goto-char (minibuffer-prompt-end)))
2215 ;; 1. First try searching in the initial minibuffer text
2216 (funcall search-fun string
2217 (if isearch-forward bound (minibuffer-prompt-end))
2218 noerror)
2219 ;; 2. If the above search fails, start putting next/prev history
2220 ;; elements in the minibuffer successively, and search the string
2221 ;; in them. Do this only when bound is nil (i.e. not while
2222 ;; lazy-highlighting search strings in the current minibuffer text).
2223 (unless bound
2224 (condition-case nil
2225 (progn
2226 (while (not found)
2227 (cond (isearch-forward
2228 (next-history-element 1)
2229 (goto-char (minibuffer-prompt-end)))
2231 (previous-history-element 1)
2232 (goto-char (point-max))))
2233 (setq isearch-barrier (point) isearch-opoint (point))
2234 ;; After putting the next/prev history element, search
2235 ;; the string in them again, until next-history-element
2236 ;; or previous-history-element raises an error at the
2237 ;; beginning/end of history.
2238 (setq found (funcall search-fun string
2239 (unless isearch-forward
2240 ;; For backward search, don't search
2241 ;; in the minibuffer prompt
2242 (minibuffer-prompt-end))
2243 noerror)))
2244 ;; Return point of the new search result
2245 (point))
2246 ;; Return nil when next(prev)-history-element fails
2247 (error nil)))))))
2249 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2250 "Display the minibuffer history search prompt.
2251 If there are no search errors, this function displays an overlay with
2252 the isearch prompt which replaces the original minibuffer prompt.
2253 Otherwise, it displays the standard isearch message returned from
2254 the function `isearch-message'."
2255 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2256 ;; Use standard function `isearch-message' when not in the minibuffer,
2257 ;; or search fails, or has an error (like incomplete regexp).
2258 ;; This function overwrites minibuffer text with isearch message,
2259 ;; so it's possible to see what is wrong in the search string.
2260 (isearch-message c-q-hack ellipsis)
2261 ;; Otherwise, put the overlay with the standard isearch prompt over
2262 ;; the initial minibuffer prompt.
2263 (if (overlayp minibuffer-history-isearch-message-overlay)
2264 (move-overlay minibuffer-history-isearch-message-overlay
2265 (point-min) (minibuffer-prompt-end))
2266 (setq minibuffer-history-isearch-message-overlay
2267 (make-overlay (point-min) (minibuffer-prompt-end)))
2268 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2269 (overlay-put minibuffer-history-isearch-message-overlay
2270 'display (isearch-message-prefix c-q-hack ellipsis))
2271 ;; And clear any previous isearch message.
2272 (message "")))
2274 (defun minibuffer-history-isearch-wrap ()
2275 "Wrap the minibuffer history search when search fails.
2276 Move point to the first history element for a forward search,
2277 or to the last history element for a backward search."
2278 ;; When `minibuffer-history-isearch-search' fails on reaching the
2279 ;; beginning/end of the history, wrap the search to the first/last
2280 ;; minibuffer history element.
2281 (if isearch-forward
2282 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2283 (goto-history-element 0))
2284 (setq isearch-success t)
2285 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2287 (defun minibuffer-history-isearch-push-state ()
2288 "Save a function restoring the state of minibuffer history search.
2289 Save `minibuffer-history-position' to the additional state parameter
2290 in the search status stack."
2291 (let ((pos minibuffer-history-position))
2292 (lambda (cmd)
2293 (minibuffer-history-isearch-pop-state cmd pos))))
2295 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2296 "Restore the minibuffer history search state.
2297 Go to the history element by the absolute history position HIST-POS."
2298 (goto-history-element hist-pos))
2301 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2302 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2304 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2305 "Table mapping redo records to the corresponding undo one.
2306 A redo record for undo-in-region maps to t.
2307 A redo record for ordinary undo maps to the following (earlier) undo.")
2309 (defvar undo-in-region nil
2310 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2312 (defvar undo-no-redo nil
2313 "If t, `undo' doesn't go through redo entries.")
2315 (defvar pending-undo-list nil
2316 "Within a run of consecutive undo commands, list remaining to be undone.
2317 If t, we undid all the way to the end of it.")
2319 (defun undo (&optional arg)
2320 "Undo some previous changes.
2321 Repeat this command to undo more changes.
2322 A numeric ARG serves as a repeat count.
2324 In Transient Mark mode when the mark is active, only undo changes within
2325 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2326 as an argument limits undo to changes within the current region."
2327 (interactive "*P")
2328 ;; Make last-command indicate for the next command that this was an undo.
2329 ;; That way, another undo will undo more.
2330 ;; If we get to the end of the undo history and get an error,
2331 ;; another undo command will find the undo history empty
2332 ;; and will get another error. To begin undoing the undos,
2333 ;; you must type some other command.
2334 (let* ((modified (buffer-modified-p))
2335 ;; For an indirect buffer, look in the base buffer for the
2336 ;; auto-save data.
2337 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2338 (recent-save (with-current-buffer base-buffer
2339 (recent-auto-save-p)))
2340 message)
2341 ;; If we get an error in undo-start,
2342 ;; the next command should not be a "consecutive undo".
2343 ;; So set `this-command' to something other than `undo'.
2344 (setq this-command 'undo-start)
2346 (unless (and (eq last-command 'undo)
2347 (or (eq pending-undo-list t)
2348 ;; If something (a timer or filter?) changed the buffer
2349 ;; since the previous command, don't continue the undo seq.
2350 (let ((list buffer-undo-list))
2351 (while (eq (car list) nil)
2352 (setq list (cdr list)))
2353 ;; If the last undo record made was made by undo
2354 ;; it shows nothing else happened in between.
2355 (gethash list undo-equiv-table))))
2356 (setq undo-in-region
2357 (or (region-active-p) (and arg (not (numberp arg)))))
2358 (if undo-in-region
2359 (undo-start (region-beginning) (region-end))
2360 (undo-start))
2361 ;; get rid of initial undo boundary
2362 (undo-more 1))
2363 ;; If we got this far, the next command should be a consecutive undo.
2364 (setq this-command 'undo)
2365 ;; Check to see whether we're hitting a redo record, and if
2366 ;; so, ask the user whether she wants to skip the redo/undo pair.
2367 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2368 (or (eq (selected-window) (minibuffer-window))
2369 (setq message (format "%s%s!"
2370 (if (or undo-no-redo (not equiv))
2371 "Undo" "Redo")
2372 (if undo-in-region " in region" ""))))
2373 (when (and (consp equiv) undo-no-redo)
2374 ;; The equiv entry might point to another redo record if we have done
2375 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2376 (while (let ((next (gethash equiv undo-equiv-table)))
2377 (if next (setq equiv next))))
2378 (setq pending-undo-list equiv)))
2379 (undo-more
2380 (if (numberp arg)
2381 (prefix-numeric-value arg)
2383 ;; Record the fact that the just-generated undo records come from an
2384 ;; undo operation--that is, they are redo records.
2385 ;; In the ordinary case (not within a region), map the redo
2386 ;; record to the following undos.
2387 ;; I don't know how to do that in the undo-in-region case.
2388 (let ((list buffer-undo-list))
2389 ;; Strip any leading undo boundaries there might be, like we do
2390 ;; above when checking.
2391 (while (eq (car list) nil)
2392 (setq list (cdr list)))
2393 (puthash list
2394 ;; Prevent identity mapping. This can happen if
2395 ;; consecutive nils are erroneously in undo list.
2396 (if (or undo-in-region (eq list pending-undo-list))
2398 pending-undo-list)
2399 undo-equiv-table))
2400 ;; Don't specify a position in the undo record for the undo command.
2401 ;; Instead, undoing this should move point to where the change is.
2402 (let ((tail buffer-undo-list)
2403 (prev nil))
2404 (while (car tail)
2405 (when (integerp (car tail))
2406 (let ((pos (car tail)))
2407 (if prev
2408 (setcdr prev (cdr tail))
2409 (setq buffer-undo-list (cdr tail)))
2410 (setq tail (cdr tail))
2411 (while (car tail)
2412 (if (eq pos (car tail))
2413 (if prev
2414 (setcdr prev (cdr tail))
2415 (setq buffer-undo-list (cdr tail)))
2416 (setq prev tail))
2417 (setq tail (cdr tail)))
2418 (setq tail nil)))
2419 (setq prev tail tail (cdr tail))))
2420 ;; Record what the current undo list says,
2421 ;; so the next command can tell if the buffer was modified in between.
2422 (and modified (not (buffer-modified-p))
2423 (with-current-buffer base-buffer
2424 (delete-auto-save-file-if-necessary recent-save)))
2425 ;; Display a message announcing success.
2426 (if message
2427 (message "%s" message))))
2429 (defun buffer-disable-undo (&optional buffer)
2430 "Make BUFFER stop keeping undo information.
2431 No argument or nil as argument means do this for the current buffer."
2432 (interactive)
2433 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2434 (setq buffer-undo-list t)))
2436 (defun undo-only (&optional arg)
2437 "Undo some previous changes.
2438 Repeat this command to undo more changes.
2439 A numeric ARG serves as a repeat count.
2440 Contrary to `undo', this will not redo a previous undo."
2441 (interactive "*p")
2442 (let ((undo-no-redo t)) (undo arg)))
2444 (defvar undo-in-progress nil
2445 "Non-nil while performing an undo.
2446 Some change-hooks test this variable to do something different.")
2448 (defun undo-more (n)
2449 "Undo back N undo-boundaries beyond what was already undone recently.
2450 Call `undo-start' to get ready to undo recent changes,
2451 then call `undo-more' one or more times to undo them."
2452 (or (listp pending-undo-list)
2453 (user-error (concat "No further undo information"
2454 (and undo-in-region " for region"))))
2455 (let ((undo-in-progress t))
2456 ;; Note: The following, while pulling elements off
2457 ;; `pending-undo-list' will call primitive change functions which
2458 ;; will push more elements onto `buffer-undo-list'.
2459 (setq pending-undo-list (primitive-undo n pending-undo-list))
2460 (if (null pending-undo-list)
2461 (setq pending-undo-list t))))
2463 (defun primitive-undo (n list)
2464 "Undo N records from the front of the list LIST.
2465 Return what remains of the list."
2467 ;; This is a good feature, but would make undo-start
2468 ;; unable to do what is expected.
2469 ;;(when (null (car (list)))
2470 ;; ;; If the head of the list is a boundary, it is the boundary
2471 ;; ;; preceding this command. Get rid of it and don't count it.
2472 ;; (setq list (cdr list))))
2474 (let ((arg n)
2475 ;; In a writable buffer, enable undoing read-only text that is
2476 ;; so because of text properties.
2477 (inhibit-read-only t)
2478 ;; Don't let `intangible' properties interfere with undo.
2479 (inhibit-point-motion-hooks t)
2480 ;; We use oldlist only to check for EQ. ++kfs
2481 (oldlist buffer-undo-list)
2482 (did-apply nil)
2483 (next nil))
2484 (while (> arg 0)
2485 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2486 ;; Handle an integer by setting point to that value.
2487 (pcase next
2488 ((pred integerp) (goto-char next))
2489 ;; Element (t . TIME) records previous modtime.
2490 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2491 ;; UNKNOWN_MODTIME_NSECS.
2492 (`(t . ,time)
2493 ;; If this records an obsolete save
2494 ;; (not matching the actual disk file)
2495 ;; then don't mark unmodified.
2496 (when (or (equal time (visited-file-modtime))
2497 (and (consp time)
2498 (equal (list (car time) (cdr time))
2499 (visited-file-modtime))))
2500 (when (fboundp 'unlock-buffer)
2501 (unlock-buffer))
2502 (set-buffer-modified-p nil)))
2503 ;; Element (nil PROP VAL BEG . END) is property change.
2504 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2505 (when (or (> (point-min) beg) (< (point-max) end))
2506 (error "Changes to be undone are outside visible portion of buffer"))
2507 (put-text-property beg end prop val))
2508 ;; Element (BEG . END) means range was inserted.
2509 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2510 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2511 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2512 (when (or (> (point-min) beg) (< (point-max) end))
2513 (error "Changes to be undone are outside visible portion of buffer"))
2514 ;; Set point first thing, so that undoing this undo
2515 ;; does not send point back to where it is now.
2516 (goto-char beg)
2517 (delete-region beg end))
2518 ;; Element (apply FUN . ARGS) means call FUN to undo.
2519 (`(apply . ,fun-args)
2520 (let ((currbuff (current-buffer)))
2521 (if (integerp (car fun-args))
2522 ;; Long format: (apply DELTA START END FUN . ARGS).
2523 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2524 (start-mark (copy-marker start nil))
2525 (end-mark (copy-marker end t)))
2526 (when (or (> (point-min) start) (< (point-max) end))
2527 (error "Changes to be undone are outside visible portion of buffer"))
2528 (apply fun args) ;; Use `save-current-buffer'?
2529 ;; Check that the function did what the entry
2530 ;; said it would do.
2531 (unless (and (= start start-mark)
2532 (= (+ delta end) end-mark))
2533 (error "Changes to be undone by function different than announced"))
2534 (set-marker start-mark nil)
2535 (set-marker end-mark nil))
2536 (apply fun-args))
2537 (unless (eq currbuff (current-buffer))
2538 (error "Undo function switched buffer"))
2539 (setq did-apply t)))
2540 ;; Element (STRING . POS) means STRING was deleted.
2541 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2542 (when (let ((apos (abs pos)))
2543 (or (< apos (point-min)) (> apos (point-max))))
2544 (error "Changes to be undone are outside visible portion of buffer"))
2545 (let (valid-marker-adjustments)
2546 ;; Check that marker adjustments which were recorded
2547 ;; with the (STRING . POS) record are still valid, ie
2548 ;; the markers haven't moved. We check their validity
2549 ;; before reinserting the string so as we don't need to
2550 ;; mind marker insertion-type.
2551 (while (and (markerp (car-safe (car list)))
2552 (integerp (cdr-safe (car list))))
2553 (let* ((marker-adj (pop list))
2554 (m (car marker-adj)))
2555 (and (eq (marker-buffer m) (current-buffer))
2556 (= pos m)
2557 (push marker-adj valid-marker-adjustments))))
2558 ;; Insert string and adjust point
2559 (if (< pos 0)
2560 (progn
2561 (goto-char (- pos))
2562 (insert string))
2563 (goto-char pos)
2564 (insert string)
2565 (goto-char pos))
2566 ;; Adjust the valid marker adjustments
2567 (dolist (adj valid-marker-adjustments)
2568 (set-marker (car adj)
2569 (- (car adj) (cdr adj))))))
2570 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2571 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2572 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2573 next)
2574 ;; Even though these elements are not expected in the undo
2575 ;; list, adjust them to be conservative for the 24.4
2576 ;; release. (Bug#16818)
2577 (when (marker-buffer marker)
2578 (set-marker marker
2579 (- marker offset)
2580 (marker-buffer marker))))
2581 (_ (error "Unrecognized entry in undo list %S" next))))
2582 (setq arg (1- arg)))
2583 ;; Make sure an apply entry produces at least one undo entry,
2584 ;; so the test in `undo' for continuing an undo series
2585 ;; will work right.
2586 (if (and did-apply
2587 (eq oldlist buffer-undo-list))
2588 (setq buffer-undo-list
2589 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2590 list)
2592 ;; Deep copy of a list
2593 (defun undo-copy-list (list)
2594 "Make a copy of undo list LIST."
2595 (mapcar 'undo-copy-list-1 list))
2597 (defun undo-copy-list-1 (elt)
2598 (if (consp elt)
2599 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2600 elt))
2602 (defun undo-start (&optional beg end)
2603 "Set `pending-undo-list' to the front of the undo list.
2604 The next call to `undo-more' will undo the most recently made change.
2605 If BEG and END are specified, then only undo elements
2606 that apply to text between BEG and END are used; other undo elements
2607 are ignored. If BEG and END are nil, all undo elements are used."
2608 (if (eq buffer-undo-list t)
2609 (user-error "No undo information in this buffer"))
2610 (setq pending-undo-list
2611 (if (and beg end (not (= beg end)))
2612 (undo-make-selective-list (min beg end) (max beg end))
2613 buffer-undo-list)))
2615 ;; The positions given in elements of the undo list are the positions
2616 ;; as of the time that element was recorded to undo history. In
2617 ;; general, subsequent buffer edits render those positions invalid in
2618 ;; the current buffer, unless adjusted according to the intervening
2619 ;; undo elements.
2621 ;; Undo in region is a use case that requires adjustments to undo
2622 ;; elements. It must adjust positions of elements in the region based
2623 ;; on newer elements not in the region so as they may be correctly
2624 ;; applied in the current buffer. undo-make-selective-list
2625 ;; accomplishes this with its undo-deltas list of adjustments. An
2626 ;; example undo history from oldest to newest:
2628 ;; buf pos:
2629 ;; 123456789 buffer-undo-list undo-deltas
2630 ;; --------- ---------------- -----------
2631 ;; aaa (1 . 4) (1 . -3)
2632 ;; aaba (3 . 4) N/A (in region)
2633 ;; ccaaba (1 . 3) (1 . -2)
2634 ;; ccaabaddd (7 . 10) (7 . -3)
2635 ;; ccaabdd ("ad" . 6) (6 . 2)
2636 ;; ccaabaddd (6 . 8) (6 . -2)
2637 ;; | |<-- region: "caab", from 2 to 6
2639 ;; When the user starts a run of undos in region,
2640 ;; undo-make-selective-list is called to create the full list of in
2641 ;; region elements. Each element is adjusted forward chronologically
2642 ;; through undo-deltas to determine if it is in the region.
2644 ;; In the above example, the insertion of "b" is (3 . 4) in the
2645 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2646 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2647 ;; . 6) is assessed as in the region and placed in the selective list.
2648 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2649 ;; due to the selected element. The "b" insertion is the only element
2650 ;; fully in the region, so in this example undo-make-selective-list
2651 ;; returns (nil (5 . 6)).
2653 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2654 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2655 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2656 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2657 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2659 ;; More interesting is how to adjust the "ddd" insertion due to the
2660 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2661 ;; If the reinsertion was a manual retyping of "ad", then the total
2662 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2663 ;; the reinsertion was due to undo, one might expect the first "d"
2664 ;; character would again be a part of the "ddd" text, meaning its
2665 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2667 ;; undo-make-selective-list assumes in this situation that "ad" was a
2668 ;; new edit, even if it was inserted because of an undo.
2669 ;; Consequently, if the user undos in region "8 to 10" of the
2670 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2671 ;; "ccaabad", as though the first "d" became detached from the
2672 ;; original "ddd" insertion. This quirk is a FIXME.
2674 (defun undo-make-selective-list (start end)
2675 "Return a list of undo elements for the region START to END.
2676 The elements come from `buffer-undo-list', but we keep only the
2677 elements inside this region, and discard those outside this
2678 region. The elements' positions are adjusted so as the returned
2679 list can be applied to the current buffer."
2680 (let ((ulist buffer-undo-list)
2681 ;; A list of position adjusted undo elements in the region.
2682 (selective-list (list nil))
2683 ;; A list of undo-deltas for out of region undo elements.
2684 undo-deltas
2685 undo-elt)
2686 (while ulist
2687 (when undo-no-redo
2688 (while (gethash ulist undo-equiv-table)
2689 (setq ulist (gethash ulist undo-equiv-table))))
2690 (setq undo-elt (car ulist))
2691 (cond
2692 ((null undo-elt)
2693 ;; Don't put two nils together in the list
2694 (when (car selective-list)
2695 (push nil selective-list)))
2696 ((and (consp undo-elt) (eq (car undo-elt) t))
2697 ;; This is a "was unmodified" element. Keep it
2698 ;; if we have kept everything thus far.
2699 (when (not undo-deltas)
2700 (push undo-elt selective-list)))
2701 ;; Skip over marker adjustments, instead relying
2702 ;; on finding them after (TEXT . POS) elements
2703 ((markerp (car-safe undo-elt))
2704 nil)
2706 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2707 undo-deltas)))
2708 (if (undo-elt-in-region adjusted-undo-elt start end)
2709 (progn
2710 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2711 (push adjusted-undo-elt selective-list)
2712 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2713 ;; kept. primitive-undo may discard them later.
2714 (when (and (stringp (car-safe adjusted-undo-elt))
2715 (integerp (cdr-safe adjusted-undo-elt)))
2716 (let ((list-i (cdr ulist)))
2717 (while (markerp (car-safe (car list-i)))
2718 (push (pop list-i) selective-list)))))
2719 (let ((delta (undo-delta undo-elt)))
2720 (when (/= 0 (cdr delta))
2721 (push delta undo-deltas)))))))
2722 (pop ulist))
2723 (nreverse selective-list)))
2725 (defun undo-elt-in-region (undo-elt start end)
2726 "Determine whether UNDO-ELT falls inside the region START ... END.
2727 If it crosses the edge, we return nil.
2729 Generally this function is not useful for determining
2730 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2731 because markers can be arbitrarily relocated. Instead, pass the
2732 marker adjustment's corresponding (TEXT . POS) element."
2733 (cond ((integerp undo-elt)
2734 (and (>= undo-elt start)
2735 (<= undo-elt end)))
2736 ((eq undo-elt nil)
2738 ((atom undo-elt)
2739 nil)
2740 ((stringp (car undo-elt))
2741 ;; (TEXT . POSITION)
2742 (and (>= (abs (cdr undo-elt)) start)
2743 (<= (abs (cdr undo-elt)) end)))
2744 ((and (consp undo-elt) (markerp (car undo-elt)))
2745 ;; (MARKER . ADJUSTMENT)
2746 (<= start (car undo-elt) end))
2747 ((null (car undo-elt))
2748 ;; (nil PROPERTY VALUE BEG . END)
2749 (let ((tail (nthcdr 3 undo-elt)))
2750 (and (>= (car tail) start)
2751 (<= (cdr tail) end))))
2752 ((integerp (car undo-elt))
2753 ;; (BEGIN . END)
2754 (and (>= (car undo-elt) start)
2755 (<= (cdr undo-elt) end)))))
2757 (defun undo-elt-crosses-region (undo-elt start end)
2758 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2759 This assumes we have already decided that UNDO-ELT
2760 is not *inside* the region START...END."
2761 (declare (obsolete nil "25.1"))
2762 (cond ((atom undo-elt) nil)
2763 ((null (car undo-elt))
2764 ;; (nil PROPERTY VALUE BEG . END)
2765 (let ((tail (nthcdr 3 undo-elt)))
2766 (and (< (car tail) end)
2767 (> (cdr tail) start))))
2768 ((integerp (car undo-elt))
2769 ;; (BEGIN . END)
2770 (and (< (car undo-elt) end)
2771 (> (cdr undo-elt) start)))))
2773 (defun undo-adjust-elt (elt deltas)
2774 "Return adjustment of undo element ELT by the undo DELTAS
2775 list."
2776 (pcase elt
2777 ;; POSITION
2778 ((pred integerp)
2779 (undo-adjust-pos elt deltas))
2780 ;; (BEG . END)
2781 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2782 (undo-adjust-beg-end beg end deltas))
2783 ;; (TEXT . POSITION)
2784 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2785 (cons text (* (if (< pos 0) -1 1)
2786 (undo-adjust-pos (abs pos) deltas))))
2787 ;; (nil PROPERTY VALUE BEG . END)
2788 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2789 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2790 ;; (apply DELTA START END FUN . ARGS)
2791 ;; FIXME
2792 ;; All others return same elt
2793 (_ elt)))
2795 ;; (BEG . END) can adjust to the same positions, commonly when an
2796 ;; insertion was undone and they are out of region, for example:
2798 ;; buf pos:
2799 ;; 123456789 buffer-undo-list undo-deltas
2800 ;; --------- ---------------- -----------
2801 ;; [...]
2802 ;; abbaa (2 . 4) (2 . -2)
2803 ;; aaa ("bb" . 2) (2 . 2)
2804 ;; [...]
2806 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2807 ;; undo. Further adjustments to such an element should be the same as
2808 ;; for (TEXT . POSITION) elements. The options are:
2810 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2811 ;; analogous to marker insertion-type t.
2813 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2814 ;; marker insertion-type nil.
2816 ;; There was no strong reason to prefer one or the other, except that
2817 ;; the first is more consistent with prior undo in region behavior.
2818 (defun undo-adjust-beg-end (beg end deltas)
2819 "Return cons of adjustments to BEG and END by the undo DELTAS
2820 list."
2821 (let ((adj-beg (undo-adjust-pos beg deltas)))
2822 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2823 (cons adj-beg
2824 (max adj-beg (undo-adjust-pos end deltas t)))))
2826 (defun undo-adjust-pos (pos deltas &optional use-<)
2827 "Return adjustment of POS by the undo DELTAS list, comparing
2828 with < or <= based on USE-<."
2829 (dolist (d deltas pos)
2830 (when (if use-<
2831 (< (car d) pos)
2832 (<= (car d) pos))
2833 (setq pos
2834 ;; Don't allow pos to become less than the undo-delta
2835 ;; position. This edge case is described in the overview
2836 ;; comments.
2837 (max (car d) (- pos (cdr d)))))))
2839 ;; Return the first affected buffer position and the delta for an undo element
2840 ;; delta is defined as the change in subsequent buffer positions if we *did*
2841 ;; the undo.
2842 (defun undo-delta (undo-elt)
2843 (if (consp undo-elt)
2844 (cond ((stringp (car undo-elt))
2845 ;; (TEXT . POSITION)
2846 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2847 ((integerp (car undo-elt))
2848 ;; (BEGIN . END)
2849 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2851 '(0 . 0)))
2852 '(0 . 0)))
2854 ;;; Default undo-boundary addition
2856 ;; This section adds a new undo-boundary at either after a command is
2857 ;; called or in some cases on a timer called after a change is made in
2858 ;; any buffer.
2859 (defvar-local undo-auto--last-boundary-cause nil
2860 "Describe the cause of the last undo-boundary.
2862 If `explicit', the last boundary was caused by an explicit call to
2863 `undo-boundary', that is one not called by the code in this
2864 section.
2866 If it is equal to `timer', then the last boundary was inserted
2867 by `undo-auto--boundary-timer'.
2869 If it is equal to `command', then the last boundary was inserted
2870 automatically after a command, that is by the code defined in
2871 this section.
2873 If it is equal to a list, then the last boundary was inserted by
2874 an amalgamating command. The car of the list is the number of
2875 times an amalgamating command has been called, and the cdr are the
2876 buffers that were changed during the last command.")
2878 (defvar undo-auto-current-boundary-timer nil
2879 "Current timer which will run `undo-auto--boundary-timer' or nil.
2881 If set to non-nil, this will effectively disable the timer.")
2883 (defvar undo-auto--this-command-amalgamating nil
2884 "Non-nil if `this-command' should be amalgamated.
2885 This variable is set to nil by `undo-auto--boundaries' and is set
2886 by `undo-auto-amalgamate'." )
2888 (defun undo-auto--needs-boundary-p ()
2889 "Return non-nil if `buffer-undo-list' needs a boundary at the start."
2890 (car-safe buffer-undo-list))
2892 (defun undo-auto--last-boundary-amalgamating-number ()
2893 "Return the number of amalgamating last commands or nil.
2894 Amalgamating commands are, by default, either
2895 `self-insert-command' and `delete-char', but can be any command
2896 that calls `undo-auto-amalgamate'."
2897 (car-safe undo-auto--last-boundary-cause))
2899 (defun undo-auto--ensure-boundary (cause)
2900 "Add an `undo-boundary' to the current buffer if needed.
2901 REASON describes the reason that the boundary is being added; see
2902 `undo-auto--last-boundary' for more information."
2903 (when (and
2904 (undo-auto--needs-boundary-p))
2905 (let ((last-amalgamating
2906 (undo-auto--last-boundary-amalgamating-number)))
2907 (undo-boundary)
2908 (setq undo-auto--last-boundary-cause
2909 (if (eq 'amalgamate cause)
2910 (cons
2911 (if last-amalgamating (1+ last-amalgamating) 0)
2912 undo-auto--undoably-changed-buffers)
2913 cause)))))
2915 (defun undo-auto--boundaries (cause)
2916 "Check recently changed buffers and add a boundary if necessary.
2917 REASON describes the reason that the boundary is being added; see
2918 `undo-last-boundary' for more information."
2919 ;; (Bug #23785) All commands should ensure that there is an undo
2920 ;; boundary whether they have changed the current buffer or not.
2921 (when (eq cause 'command)
2922 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer)))
2923 (dolist (b undo-auto--undoably-changed-buffers)
2924 (when (buffer-live-p b)
2925 (with-current-buffer b
2926 (undo-auto--ensure-boundary cause))))
2927 (setq undo-auto--undoably-changed-buffers nil))
2929 (defun undo-auto--boundary-timer ()
2930 "Timer which will run `undo--auto-boundary-timer'."
2931 (setq undo-auto-current-boundary-timer nil)
2932 (undo-auto--boundaries 'timer))
2934 (defun undo-auto--boundary-ensure-timer ()
2935 "Ensure that the `undo-auto-boundary-timer' is set."
2936 (unless undo-auto-current-boundary-timer
2937 (setq undo-auto-current-boundary-timer
2938 (run-at-time 10 nil #'undo-auto--boundary-timer))))
2940 (defvar undo-auto--undoably-changed-buffers nil
2941 "List of buffers that have changed recently.
2943 This list is maintained by `undo-auto--undoable-change' and
2944 `undo-auto--boundaries' and can be affected by changes to their
2945 default values.")
2947 (defun undo-auto--add-boundary ()
2948 "Add an `undo-boundary' in appropriate buffers."
2949 (undo-auto--boundaries
2950 (let ((amal undo-auto--this-command-amalgamating))
2951 (setq undo-auto--this-command-amalgamating nil)
2952 (if amal
2953 'amalgamate
2954 'command))))
2956 (defun undo-auto-amalgamate ()
2957 "Amalgamate undo if necessary.
2958 This function can be called before an amalgamating command. It
2959 removes the previous `undo-boundary' if a series of such calls
2960 have been made. By default `self-insert-command' and
2961 `delete-char' are the only amalgamating commands, although this
2962 function could be called by any command wishing to have this
2963 behavior."
2964 (let ((last-amalgamating-count
2965 (undo-auto--last-boundary-amalgamating-number)))
2966 (setq undo-auto--this-command-amalgamating t)
2967 (when
2968 last-amalgamating-count
2970 (and
2971 (< last-amalgamating-count 20)
2972 (eq this-command last-command))
2973 ;; Amalgamate all buffers that have changed.
2974 (dolist (b (cdr undo-auto--last-boundary-cause))
2975 (when (buffer-live-p b)
2976 (with-current-buffer
2978 (when
2979 ;; The head of `buffer-undo-list' is nil.
2980 ;; `car-safe' doesn't work because
2981 ;; `buffer-undo-list' need not be a list!
2982 (and (listp buffer-undo-list)
2983 (not (car buffer-undo-list)))
2984 (setq buffer-undo-list
2985 (cdr buffer-undo-list))))))
2986 (setq undo-auto--last-boundary-cause 0)))))
2988 (defun undo-auto--undoable-change ()
2989 "Called after every undoable buffer change."
2990 (add-to-list 'undo-auto--undoably-changed-buffers (current-buffer))
2991 (undo-auto--boundary-ensure-timer))
2992 ;; End auto-boundary section
2994 (defun undo-amalgamate-change-group (handle)
2995 "Amalgamate changes in change-group since HANDLE.
2996 Remove all undo boundaries between the state of HANDLE and now.
2997 HANDLE is as returned by `prepare-change-group'."
2998 (dolist (elt handle)
2999 (with-current-buffer (car elt)
3000 (setq elt (cdr elt))
3001 (when (consp buffer-undo-list)
3002 (let ((old-car (car-safe elt))
3003 (old-cdr (cdr-safe elt)))
3004 (unwind-protect
3005 (progn
3006 ;; Temporarily truncate the undo log at ELT.
3007 (when (consp elt)
3008 (setcar elt t) (setcdr elt nil))
3009 (when
3010 (or (null elt) ;The undo-log was empty.
3011 ;; `elt' is still in the log: normal case.
3012 (eq elt (last buffer-undo-list))
3013 ;; `elt' is not in the log any more, but that's because
3014 ;; the log is "all new", so we should remove all
3015 ;; boundaries from it.
3016 (not (eq (last buffer-undo-list) (last old-cdr))))
3017 (cl-callf (lambda (x) (delq nil x))
3018 (if (car buffer-undo-list)
3019 buffer-undo-list
3020 ;; Preserve the undo-boundaries at either ends of the
3021 ;; change-groups.
3022 (cdr buffer-undo-list)))))
3023 ;; Reset the modified cons cell ELT to its original content.
3024 (when (consp elt)
3025 (setcar elt old-car)
3026 (setcdr elt old-cdr))))))))
3029 (defcustom undo-ask-before-discard nil
3030 "If non-nil ask about discarding undo info for the current command.
3031 Normally, Emacs discards the undo info for the current command if
3032 it exceeds `undo-outer-limit'. But if you set this option
3033 non-nil, it asks in the echo area whether to discard the info.
3034 If you answer no, there is a slight risk that Emacs might crash, so
3035 only do it if you really want to undo the command.
3037 This option is mainly intended for debugging. You have to be
3038 careful if you use it for other purposes. Garbage collection is
3039 inhibited while the question is asked, meaning that Emacs might
3040 leak memory. So you should make sure that you do not wait
3041 excessively long before answering the question."
3042 :type 'boolean
3043 :group 'undo
3044 :version "22.1")
3046 (defvar undo-extra-outer-limit nil
3047 "If non-nil, an extra level of size that's ok in an undo item.
3048 We don't ask the user about truncating the undo list until the
3049 current item gets bigger than this amount.
3051 This variable only matters if `undo-ask-before-discard' is non-nil.")
3052 (make-variable-buffer-local 'undo-extra-outer-limit)
3054 ;; When the first undo batch in an undo list is longer than
3055 ;; undo-outer-limit, this function gets called to warn the user that
3056 ;; the undo info for the current command was discarded. Garbage
3057 ;; collection is inhibited around the call, so it had better not do a
3058 ;; lot of consing.
3059 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
3060 (defun undo-outer-limit-truncate (size)
3061 (if undo-ask-before-discard
3062 (when (or (null undo-extra-outer-limit)
3063 (> size undo-extra-outer-limit))
3064 ;; Don't ask the question again unless it gets even bigger.
3065 ;; This applies, in particular, if the user quits from the question.
3066 ;; Such a quit quits out of GC, but something else will call GC
3067 ;; again momentarily. It will call this function again,
3068 ;; but we don't want to ask the question again.
3069 (setq undo-extra-outer-limit (+ size 50000))
3070 (if (let (use-dialog-box track-mouse executing-kbd-macro )
3071 (yes-or-no-p (format-message
3072 "Buffer `%s' undo info is %d bytes long; discard it? "
3073 (buffer-name) size)))
3074 (progn (setq buffer-undo-list nil)
3075 (setq undo-extra-outer-limit nil)
3077 nil))
3078 (display-warning '(undo discard-info)
3079 (concat
3080 (format-message
3081 "Buffer `%s' undo info was %d bytes long.\n"
3082 (buffer-name) size)
3083 "The undo info was discarded because it exceeded \
3084 `undo-outer-limit'.
3086 This is normal if you executed a command that made a huge change
3087 to the buffer. In that case, to prevent similar problems in the
3088 future, set `undo-outer-limit' to a value that is large enough to
3089 cover the maximum size of normal changes you expect a single
3090 command to make, but not so large that it might exceed the
3091 maximum memory allotted to Emacs.
3093 If you did not execute any such command, the situation is
3094 probably due to a bug and you should report it.
3096 You can disable the popping up of this buffer by adding the entry
3097 \(undo discard-info) to the user option `warning-suppress-types',
3098 which is defined in the `warnings' library.\n")
3099 :warning)
3100 (setq buffer-undo-list nil)
3103 (defcustom password-word-equivalents
3104 '("password" "passcode" "passphrase" "pass phrase"
3105 ; These are sorted according to the GNU en_US locale.
3106 "암호" ; ko
3107 "パスワード" ; ja
3108 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
3109 "ពាក្យសម្ងាត់" ; km
3110 "adgangskode" ; da
3111 "contraseña" ; es
3112 "contrasenya" ; ca
3113 "geslo" ; sl
3114 "hasło" ; pl
3115 "heslo" ; cs, sk
3116 "iphasiwedi" ; zu
3117 "jelszó" ; hu
3118 "lösenord" ; sv
3119 "lozinka" ; hr, sr
3120 "mật khẩu" ; vi
3121 "mot de passe" ; fr
3122 "parola" ; tr
3123 "pasahitza" ; eu
3124 "passord" ; nb
3125 "passwort" ; de
3126 "pasvorto" ; eo
3127 "salasana" ; fi
3128 "senha" ; pt
3129 "slaptažodis" ; lt
3130 "wachtwoord" ; nl
3131 "كلمة السر" ; ar
3132 "ססמה" ; he
3133 "лозинка" ; sr
3134 "пароль" ; kk, ru, uk
3135 "गुप्तशब्द" ; mr
3136 "शब्दकूट" ; hi
3137 "પાસવર્ડ" ; gu
3138 "సంకేతపదము" ; te
3139 "ਪਾਸਵਰਡ" ; pa
3140 "ಗುಪ್ತಪದ" ; kn
3141 "கடவுச்சொல்" ; ta
3142 "അടയാളവാക്ക്" ; ml
3143 "গুপ্তশব্দ" ; as
3144 "পাসওয়ার্ড" ; bn_IN
3145 "රහස්පදය" ; si
3146 "密码" ; zh_CN
3147 "密碼" ; zh_TW
3149 "List of words equivalent to \"password\".
3150 This is used by Shell mode and other parts of Emacs to recognize
3151 password prompts, including prompts in languages other than
3152 English. Different case choices should not be assumed to be
3153 included; callers should bind `case-fold-search' to t."
3154 :type '(repeat string)
3155 :version "24.4"
3156 :group 'processes)
3158 (defvar shell-command-history nil
3159 "History list for some commands that read shell commands.
3161 Maximum length of the history list is determined by the value
3162 of `history-length', which see.")
3164 (defvar shell-command-switch (purecopy "-c")
3165 "Switch used to have the shell execute its command line argument.")
3167 (defvar shell-command-default-error-buffer nil
3168 "Buffer name for `shell-command' and `shell-command-on-region' error output.
3169 This buffer is used when `shell-command' or `shell-command-on-region'
3170 is run interactively. A value of nil means that output to stderr and
3171 stdout will be intermixed in the output stream.")
3173 (declare-function mailcap-file-default-commands "mailcap" (files))
3174 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3176 (defun minibuffer-default-add-shell-commands ()
3177 "Return a list of all commands associated with the current file.
3178 This function is used to add all related commands retrieved by `mailcap'
3179 to the end of the list of defaults just after the default value."
3180 (interactive)
3181 (let* ((filename (if (listp minibuffer-default)
3182 (car minibuffer-default)
3183 minibuffer-default))
3184 (commands (and filename (require 'mailcap nil t)
3185 (mailcap-file-default-commands (list filename)))))
3186 (setq commands (mapcar (lambda (command)
3187 (concat command " " filename))
3188 commands))
3189 (if (listp minibuffer-default)
3190 (append minibuffer-default commands)
3191 (cons minibuffer-default commands))))
3193 (declare-function shell-completion-vars "shell" ())
3195 (defvar minibuffer-local-shell-command-map
3196 (let ((map (make-sparse-keymap)))
3197 (set-keymap-parent map minibuffer-local-map)
3198 (define-key map "\t" 'completion-at-point)
3199 map)
3200 "Keymap used for completing shell commands in minibuffer.")
3202 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
3203 "Read a shell command from the minibuffer.
3204 The arguments are the same as the ones of `read-from-minibuffer',
3205 except READ and KEYMAP are missing and HIST defaults
3206 to `shell-command-history'."
3207 (require 'shell)
3208 (minibuffer-with-setup-hook
3209 (lambda ()
3210 (shell-completion-vars)
3211 (set (make-local-variable 'minibuffer-default-add-function)
3212 'minibuffer-default-add-shell-commands))
3213 (apply 'read-from-minibuffer prompt initial-contents
3214 minibuffer-local-shell-command-map
3216 (or hist 'shell-command-history)
3217 args)))
3219 (defcustom async-shell-command-buffer 'confirm-new-buffer
3220 "What to do when the output buffer is used by another shell command.
3221 This option specifies how to resolve the conflict where a new command
3222 wants to direct its output to the buffer `*Async Shell Command*',
3223 but this buffer is already taken by another running shell command.
3225 The value `confirm-kill-process' is used to ask for confirmation before
3226 killing the already running process and running a new process
3227 in the same buffer, `confirm-new-buffer' for confirmation before running
3228 the command in a new buffer with a name other than the default buffer name,
3229 `new-buffer' for doing the same without confirmation,
3230 `confirm-rename-buffer' for confirmation before renaming the existing
3231 output buffer and running a new command in the default buffer,
3232 `rename-buffer' for doing the same without confirmation."
3233 :type '(choice (const :tag "Confirm killing of running command"
3234 confirm-kill-process)
3235 (const :tag "Confirm creation of a new buffer"
3236 confirm-new-buffer)
3237 (const :tag "Create a new buffer"
3238 new-buffer)
3239 (const :tag "Confirm renaming of existing buffer"
3240 confirm-rename-buffer)
3241 (const :tag "Rename the existing buffer"
3242 rename-buffer))
3243 :group 'shell
3244 :version "24.3")
3246 (defun shell-command--save-pos-or-erase ()
3247 "Store a buffer position or erase the buffer.
3248 See `shell-command-dont-erase-buffer'."
3249 (let ((sym shell-command-dont-erase-buffer)
3250 pos)
3251 (setq buffer-read-only nil)
3252 ;; Setting buffer-read-only to nil doesn't suffice
3253 ;; if some text has a non-nil read-only property,
3254 ;; which comint sometimes adds for prompts.
3255 (setq pos
3256 (cond ((eq sym 'save-point) (point))
3257 ((eq sym 'beg-last-out) (point-max))
3258 ((not sym)
3259 (let ((inhibit-read-only t))
3260 (erase-buffer) nil))))
3261 (when pos
3262 (goto-char (point-max))
3263 (push (cons (current-buffer) pos)
3264 shell-command-saved-pos))))
3266 (defun shell-command--set-point-after-cmd (&optional buffer)
3267 "Set point in BUFFER after command complete.
3268 BUFFER is the output buffer of the command; if nil, then defaults
3269 to the current BUFFER.
3270 Set point to the `cdr' of the element in `shell-command-saved-pos'
3271 whose `car' is BUFFER."
3272 (when shell-command-dont-erase-buffer
3273 (let* ((sym shell-command-dont-erase-buffer)
3274 (buf (or buffer (current-buffer)))
3275 (pos (alist-get buf shell-command-saved-pos)))
3276 (setq shell-command-saved-pos
3277 (assq-delete-all buf shell-command-saved-pos))
3278 (when (buffer-live-p buf)
3279 (let ((win (car (get-buffer-window-list buf)))
3280 (pmax (with-current-buffer buf (point-max))))
3281 (unless (and pos (memq sym '(save-point beg-last-out)))
3282 (setq pos pmax))
3283 ;; Set point in the window displaying buf, if any; otherwise
3284 ;; display buf temporary in selected frame and set the point.
3285 (if win
3286 (set-window-point win pos)
3287 (save-window-excursion
3288 (let ((win (display-buffer
3290 '(nil (inhibit-switch-frame . t)))))
3291 (set-window-point win pos)))))))))
3293 (defun async-shell-command (command &optional output-buffer error-buffer)
3294 "Execute string COMMAND asynchronously in background.
3296 Like `shell-command', but adds `&' at the end of COMMAND
3297 to execute it asynchronously.
3299 The output appears in the buffer `*Async Shell Command*'.
3300 That buffer is in shell mode.
3302 You can configure `async-shell-command-buffer' to specify what to do in
3303 case when `*Async Shell Command*' buffer is already taken by another
3304 running shell command. To run COMMAND without displaying the output
3305 in a window you can configure `display-buffer-alist' to use the action
3306 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
3308 In Elisp, you will often be better served by calling `start-process'
3309 directly, since it offers more control and does not impose the use of a
3310 shell (with its need to quote arguments)."
3311 (interactive
3312 (list
3313 (read-shell-command "Async shell command: " nil nil
3314 (let ((filename
3315 (cond
3316 (buffer-file-name)
3317 ((eq major-mode 'dired-mode)
3318 (dired-get-filename nil t)))))
3319 (and filename (file-relative-name filename))))
3320 current-prefix-arg
3321 shell-command-default-error-buffer))
3322 (unless (string-match "&[ \t]*\\'" command)
3323 (setq command (concat command " &")))
3324 (shell-command command output-buffer error-buffer))
3326 (defun shell-command (command &optional output-buffer error-buffer)
3327 "Execute string COMMAND in inferior shell; display output, if any.
3328 With prefix argument, insert the COMMAND's output at point.
3330 Interactively, prompt for COMMAND in the minibuffer.
3332 If COMMAND ends in `&', execute it asynchronously.
3333 The output appears in the buffer `*Async Shell Command*'.
3334 That buffer is in shell mode. You can also use
3335 `async-shell-command' that automatically adds `&'.
3337 Otherwise, COMMAND is executed synchronously. The output appears in
3338 the buffer `*Shell Command Output*'. If the output is short enough to
3339 display in the echo area (which is determined by the variables
3340 `resize-mini-windows' and `max-mini-window-height'), it is shown
3341 there, but it is nonetheless available in buffer `*Shell Command
3342 Output*' even though that buffer is not automatically displayed.
3344 To specify a coding system for converting non-ASCII characters
3345 in the shell command output, use \\[universal-coding-system-argument] \
3346 before this command.
3348 Noninteractive callers can specify coding systems by binding
3349 `coding-system-for-read' and `coding-system-for-write'.
3351 The optional second argument OUTPUT-BUFFER, if non-nil,
3352 says to put the output in some other buffer.
3353 If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
3354 and insert the output there; a non-nil value of
3355 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3356 If OUTPUT-BUFFER is not a buffer and not nil, insert the output
3357 in current buffer after point leaving mark after it.
3358 This cannot be done asynchronously.
3360 If the command terminates without error, but generates output,
3361 and you did not specify \"insert it in the current buffer\",
3362 the output can be displayed in the echo area or in its buffer.
3363 If the output is short enough to display in the echo area
3364 \(determined by the variable `max-mini-window-height' if
3365 `resize-mini-windows' is non-nil), it is shown there.
3366 Otherwise,the buffer containing the output is displayed.
3368 If there is output and an error, and you did not specify \"insert it
3369 in the current buffer\", a message about the error goes at the end
3370 of the output.
3372 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3373 or buffer name to which to direct the command's standard error output.
3374 If it is nil, error output is mingled with regular output.
3375 In an interactive call, the variable `shell-command-default-error-buffer'
3376 specifies the value of ERROR-BUFFER.
3378 In Elisp, you will often be better served by calling `call-process' or
3379 `start-process' directly, since it offers more control and does not impose
3380 the use of a shell (with its need to quote arguments)."
3382 (interactive
3383 (list
3384 (read-shell-command "Shell command: " nil nil
3385 (let ((filename
3386 (cond
3387 (buffer-file-name)
3388 ((eq major-mode 'dired-mode)
3389 (dired-get-filename nil t)))))
3390 (and filename (file-relative-name filename))))
3391 current-prefix-arg
3392 shell-command-default-error-buffer))
3393 ;; Look for a handler in case default-directory is a remote file name.
3394 (let ((handler
3395 (find-file-name-handler (directory-file-name default-directory)
3396 'shell-command)))
3397 (if handler
3398 (funcall handler 'shell-command command output-buffer error-buffer)
3399 (if (and output-buffer
3400 (not (or (bufferp output-buffer) (stringp output-buffer))))
3401 ;; Output goes in current buffer.
3402 (let ((error-file
3403 (if error-buffer
3404 (make-temp-file
3405 (expand-file-name "scor"
3406 (or small-temporary-file-directory
3407 temporary-file-directory)))
3408 nil)))
3409 (barf-if-buffer-read-only)
3410 (push-mark nil t)
3411 ;; We do not use -f for csh; we will not support broken use of
3412 ;; .cshrcs. Even the BSD csh manual says to use
3413 ;; "if ($?prompt) exit" before things which are not useful
3414 ;; non-interactively. Besides, if someone wants their other
3415 ;; aliases for shell commands then they can still have them.
3416 (call-process shell-file-name nil
3417 (if error-file
3418 (list t error-file)
3420 nil shell-command-switch command)
3421 (when (and error-file (file-exists-p error-file))
3422 (if (< 0 (nth 7 (file-attributes error-file)))
3423 (with-current-buffer (get-buffer-create error-buffer)
3424 (let ((pos-from-end (- (point-max) (point))))
3425 (or (bobp)
3426 (insert "\f\n"))
3427 ;; Do no formatting while reading error file,
3428 ;; because that can run a shell command, and we
3429 ;; don't want that to cause an infinite recursion.
3430 (format-insert-file error-file nil)
3431 ;; Put point after the inserted errors.
3432 (goto-char (- (point-max) pos-from-end)))
3433 (display-buffer (current-buffer))))
3434 (delete-file error-file))
3435 ;; This is like exchange-point-and-mark, but doesn't
3436 ;; activate the mark. It is cleaner to avoid activation,
3437 ;; even though the command loop would deactivate the mark
3438 ;; because we inserted text.
3439 (goto-char (prog1 (mark t)
3440 (set-marker (mark-marker) (point)
3441 (current-buffer)))))
3442 ;; Output goes in a separate buffer.
3443 ;; Preserve the match data in case called from a program.
3444 ;; FIXME: It'd be ridiculous for an Elisp function to call
3445 ;; shell-command and assume that it won't mess the match-data!
3446 (save-match-data
3447 (if (string-match "[ \t]*&[ \t]*\\'" command)
3448 ;; Command ending with ampersand means asynchronous.
3449 (let ((buffer (get-buffer-create
3450 (or output-buffer "*Async Shell Command*")))
3451 (directory default-directory)
3452 proc)
3453 ;; Remove the ampersand.
3454 (setq command (substring command 0 (match-beginning 0)))
3455 ;; Ask the user what to do with already running process.
3456 (setq proc (get-buffer-process buffer))
3457 (when proc
3458 (cond
3459 ((eq async-shell-command-buffer 'confirm-kill-process)
3460 ;; If will kill a process, query first.
3461 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3462 (kill-process proc)
3463 (error "Shell command in progress")))
3464 ((eq async-shell-command-buffer 'confirm-new-buffer)
3465 ;; If will create a new buffer, query first.
3466 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3467 (setq buffer (generate-new-buffer
3468 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3469 output-buffer "*Async Shell Command*")))
3470 (error "Shell command in progress")))
3471 ((eq async-shell-command-buffer 'new-buffer)
3472 ;; It will create a new buffer.
3473 (setq buffer (generate-new-buffer
3474 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3475 output-buffer "*Async Shell Command*"))))
3476 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3477 ;; If will rename the buffer, query first.
3478 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3479 (progn
3480 (with-current-buffer buffer
3481 (rename-uniquely))
3482 (setq buffer (get-buffer-create
3483 (or output-buffer "*Async Shell Command*"))))
3484 (error "Shell command in progress")))
3485 ((eq async-shell-command-buffer 'rename-buffer)
3486 ;; It will rename the buffer.
3487 (with-current-buffer buffer
3488 (rename-uniquely))
3489 (setq buffer (get-buffer-create
3490 (or output-buffer "*Async Shell Command*"))))))
3491 (with-current-buffer buffer
3492 (display-buffer buffer '(nil (allow-no-window . t)))
3493 (shell-command--save-pos-or-erase)
3494 (setq default-directory directory)
3495 (setq proc (start-process "Shell" buffer shell-file-name
3496 shell-command-switch command))
3497 (setq mode-line-process '(":%s"))
3498 (require 'shell) (shell-mode)
3499 (set-process-sentinel proc 'shell-command-sentinel)
3500 ;; Use the comint filter for proper handling of carriage motion
3501 ;; (see `comint-inhibit-carriage-motion'),.
3502 (set-process-filter proc 'comint-output-filter)
3504 ;; Otherwise, command is executed synchronously.
3505 (shell-command-on-region (point) (point) command
3506 output-buffer nil error-buffer)))))))
3508 (defun display-message-or-buffer (message &optional buffer-name action frame)
3509 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3510 MESSAGE may be either a string or a buffer.
3512 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3513 for maximum height of the echo area, as defined by `max-mini-window-height'
3514 if `resize-mini-windows' is non-nil.
3516 Returns either the string shown in the echo area, or when a pop-up
3517 buffer is used, the window used to display it.
3519 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3520 name of the buffer used to display it in the case where a pop-up buffer
3521 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3522 string and it is displayed in the echo area, it is not specified whether
3523 the contents are inserted into the buffer anyway.
3525 Optional arguments ACTION and FRAME are as for `display-buffer',
3526 and are only used if a pop-up buffer is displayed."
3527 (cond ((and (stringp message) (not (string-match "\n" message)))
3528 ;; Trivial case where we can use the echo area
3529 (message "%s" message))
3530 ((and (stringp message)
3531 (= (string-match "\n" message) (1- (length message))))
3532 ;; Trivial case where we can just remove single trailing newline
3533 (message "%s" (substring message 0 (1- (length message)))))
3535 ;; General case
3536 (with-current-buffer
3537 (if (bufferp message)
3538 message
3539 (get-buffer-create (or buffer-name "*Message*")))
3541 (unless (bufferp message)
3542 (erase-buffer)
3543 (insert message))
3545 (let ((lines
3546 (if (= (buffer-size) 0)
3548 (count-screen-lines nil nil nil (minibuffer-window)))))
3549 (cond ((= lines 0))
3550 ((and (or (<= lines 1)
3551 (<= lines
3552 (if resize-mini-windows
3553 (cond ((floatp max-mini-window-height)
3554 (* (frame-height)
3555 max-mini-window-height))
3556 ((integerp max-mini-window-height)
3557 max-mini-window-height)
3560 1)))
3561 ;; Don't use the echo area if the output buffer is
3562 ;; already displayed in the selected frame.
3563 (not (get-buffer-window (current-buffer))))
3564 ;; Echo area
3565 (goto-char (point-max))
3566 (when (bolp)
3567 (backward-char 1))
3568 (message "%s" (buffer-substring (point-min) (point))))
3570 ;; Buffer
3571 (goto-char (point-min))
3572 (display-buffer (current-buffer) action frame))))))))
3575 ;; We have a sentinel to prevent insertion of a termination message
3576 ;; in the buffer itself, and to set the point in the buffer when
3577 ;; `shell-command-dont-erase-buffer' is non-nil.
3578 (defun shell-command-sentinel (process signal)
3579 (when (memq (process-status process) '(exit signal))
3580 (shell-command--set-point-after-cmd (process-buffer process))
3581 (message "%s: %s."
3582 (car (cdr (cdr (process-command process))))
3583 (substring signal 0 -1))))
3585 (defun shell-command-on-region (start end command
3586 &optional output-buffer replace
3587 error-buffer display-error-buffer
3588 region-noncontiguous-p)
3589 "Execute string COMMAND in inferior shell with region as input.
3590 Normally display output (if any) in temp buffer `*Shell Command Output*';
3591 Prefix arg means replace the region with it. Return the exit code of
3592 COMMAND.
3594 To specify a coding system for converting non-ASCII characters
3595 in the input and output to the shell command, use \\[universal-coding-system-argument]
3596 before this command. By default, the input (from the current buffer)
3597 is encoded using coding-system specified by `process-coding-system-alist',
3598 falling back to `default-process-coding-system' if no match for COMMAND
3599 is found in `process-coding-system-alist'.
3601 Noninteractive callers can specify coding systems by binding
3602 `coding-system-for-read' and `coding-system-for-write'.
3604 If the command generates output, the output may be displayed
3605 in the echo area or in a buffer.
3606 If the output is short enough to display in the echo area
3607 \(determined by the variable `max-mini-window-height' if
3608 `resize-mini-windows' is non-nil), it is shown there.
3609 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3610 The output is available in that buffer in both cases.
3612 If there is output and an error, a message about the error
3613 appears at the end of the output.
3615 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3616 command's output. If the value is a buffer or buffer name,
3617 erase that buffer and insert the output there; a non-nil value of
3618 `shell-command-dont-erase-buffer' prevent to erase the buffer.
3619 If the value is nil, use the buffer `*Shell Command Output*'.
3620 Any other non-nil value means to insert the output in the
3621 current buffer after START.
3623 Optional fifth arg REPLACE, if non-nil, means to insert the
3624 output in place of text from START to END, putting point and mark
3625 around it.
3627 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3628 or buffer name to which to direct the command's standard error
3629 output. If nil, error output is mingled with regular output.
3630 When called interactively, `shell-command-default-error-buffer'
3631 is used for ERROR-BUFFER.
3633 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3634 display the error buffer if there were any errors. When called
3635 interactively, this is t."
3636 (interactive (let (string)
3637 (unless (mark)
3638 (user-error "The mark is not set now, so there is no region"))
3639 ;; Do this before calling region-beginning
3640 ;; and region-end, in case subprocess output
3641 ;; relocates them while we are in the minibuffer.
3642 (setq string (read-shell-command "Shell command on region: "))
3643 ;; call-interactively recognizes region-beginning and
3644 ;; region-end specially, leaving them in the history.
3645 (list (region-beginning) (region-end)
3646 string
3647 current-prefix-arg
3648 current-prefix-arg
3649 shell-command-default-error-buffer
3651 (region-noncontiguous-p))))
3652 (let ((error-file
3653 (if error-buffer
3654 (make-temp-file
3655 (expand-file-name "scor"
3656 (or small-temporary-file-directory
3657 temporary-file-directory)))
3658 nil))
3659 exit-status)
3660 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3661 (if region-noncontiguous-p
3662 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3663 output)
3664 (with-temp-buffer
3665 (insert input)
3666 (call-process-region (point-min) (point-max)
3667 shell-file-name t t
3668 nil shell-command-switch
3669 command)
3670 (setq output (split-string (buffer-string) "\n")))
3671 (goto-char start)
3672 (funcall region-insert-function output))
3673 (if (or replace
3674 (and output-buffer
3675 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3676 ;; Replace specified region with output from command.
3677 (let ((swap (and replace (< start end))))
3678 ;; Don't muck with mark unless REPLACE says we should.
3679 (goto-char start)
3680 (and replace (push-mark (point) 'nomsg))
3681 (setq exit-status
3682 (call-shell-region start end command replace
3683 (if error-file
3684 (list t error-file)
3685 t)))
3686 ;; It is rude to delete a buffer which the command is not using.
3687 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3688 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3689 ;; (kill-buffer shell-buffer)))
3690 ;; Don't muck with mark unless REPLACE says we should.
3691 (and replace swap (exchange-point-and-mark)))
3692 ;; No prefix argument: put the output in a temp buffer,
3693 ;; replacing its entire contents.
3694 (let ((buffer (get-buffer-create
3695 (or output-buffer "*Shell Command Output*"))))
3696 (unwind-protect
3697 (if (and (eq buffer (current-buffer))
3698 (or (not shell-command-dont-erase-buffer)
3699 (and (not (eq buffer (get-buffer "*Shell Command Output*")))
3700 (not (region-active-p)))))
3701 ;; If the input is the same buffer as the output,
3702 ;; delete everything but the specified region,
3703 ;; then replace that region with the output.
3704 (progn (setq buffer-read-only nil)
3705 (delete-region (max start end) (point-max))
3706 (delete-region (point-min) (min start end))
3707 (setq exit-status
3708 (call-process-region (point-min) (point-max)
3709 shell-file-name t
3710 (if error-file
3711 (list t error-file)
3713 nil shell-command-switch
3714 command)))
3715 ;; Clear the output buffer, then run the command with
3716 ;; output there.
3717 (let ((directory default-directory))
3718 (with-current-buffer buffer
3719 (if (not output-buffer)
3720 (setq default-directory directory))
3721 (shell-command--save-pos-or-erase)))
3722 (setq exit-status
3723 (call-shell-region start end command nil
3724 (if error-file
3725 (list buffer error-file)
3726 buffer))))
3727 ;; Report the output.
3728 (with-current-buffer buffer
3729 (setq mode-line-process
3730 (cond ((null exit-status)
3731 " - Error")
3732 ((stringp exit-status)
3733 (format " - Signal [%s]" exit-status))
3734 ((not (equal 0 exit-status))
3735 (format " - Exit [%d]" exit-status)))))
3736 (if (with-current-buffer buffer (> (point-max) (point-min)))
3737 ;; There's some output, display it
3738 (progn
3739 (display-message-or-buffer buffer)
3740 (shell-command--set-point-after-cmd buffer))
3741 ;; No output; error?
3742 (let ((output
3743 (if (and error-file
3744 (< 0 (nth 7 (file-attributes error-file))))
3745 (format "some error output%s"
3746 (if shell-command-default-error-buffer
3747 (format " to the \"%s\" buffer"
3748 shell-command-default-error-buffer)
3749 ""))
3750 "no output")))
3751 (cond ((null exit-status)
3752 (message "(Shell command failed with error)"))
3753 ((equal 0 exit-status)
3754 (message "(Shell command succeeded with %s)"
3755 output))
3756 ((stringp exit-status)
3757 (message "(Shell command killed by signal %s)"
3758 exit-status))
3760 (message "(Shell command failed with code %d and %s)"
3761 exit-status output))))
3762 ;; Don't kill: there might be useful info in the undo-log.
3763 ;; (kill-buffer buffer)
3764 )))))
3766 (when (and error-file (file-exists-p error-file))
3767 (if (< 0 (nth 7 (file-attributes error-file)))
3768 (with-current-buffer (get-buffer-create error-buffer)
3769 (let ((pos-from-end (- (point-max) (point))))
3770 (or (bobp)
3771 (insert "\f\n"))
3772 ;; Do no formatting while reading error file,
3773 ;; because that can run a shell command, and we
3774 ;; don't want that to cause an infinite recursion.
3775 (format-insert-file error-file nil)
3776 ;; Put point after the inserted errors.
3777 (goto-char (- (point-max) pos-from-end)))
3778 (and display-error-buffer
3779 (display-buffer (current-buffer)))))
3780 (delete-file error-file))
3781 exit-status))
3783 (defun shell-command-to-string (command)
3784 "Execute shell command COMMAND and return its output as a string."
3785 (with-output-to-string
3786 (with-current-buffer
3787 standard-output
3788 (process-file shell-file-name nil t nil shell-command-switch command))))
3790 (defun process-file (program &optional infile buffer display &rest args)
3791 "Process files synchronously in a separate process.
3792 Similar to `call-process', but may invoke a file handler based on
3793 `default-directory'. The current working directory of the
3794 subprocess is `default-directory'.
3796 File names in INFILE and BUFFER are handled normally, but file
3797 names in ARGS should be relative to `default-directory', as they
3798 are passed to the process verbatim. (This is a difference to
3799 `call-process' which does not support file handlers for INFILE
3800 and BUFFER.)
3802 Some file handlers might not support all variants, for example
3803 they might behave as if DISPLAY was nil, regardless of the actual
3804 value passed."
3805 (let ((fh (find-file-name-handler default-directory 'process-file))
3806 lc stderr-file)
3807 (unwind-protect
3808 (if fh (apply fh 'process-file program infile buffer display args)
3809 (when infile (setq lc (file-local-copy infile)))
3810 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3811 (make-temp-file "emacs")))
3812 (prog1
3813 (apply 'call-process program
3814 (or lc infile)
3815 (if stderr-file (list (car buffer) stderr-file) buffer)
3816 display args)
3817 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3818 (when stderr-file (delete-file stderr-file))
3819 (when lc (delete-file lc)))))
3821 (defvar process-file-side-effects t
3822 "Whether a call of `process-file' changes remote files.
3824 By default, this variable is always set to t, meaning that a
3825 call of `process-file' could potentially change any file on a
3826 remote host. When set to nil, a file handler could optimize
3827 its behavior with respect to remote file attribute caching.
3829 You should only ever change this variable with a let-binding;
3830 never with `setq'.")
3832 (defun start-file-process (name buffer program &rest program-args)
3833 "Start a program in a subprocess. Return the process object for it.
3835 Similar to `start-process', but may invoke a file handler based on
3836 `default-directory'. See Info node `(elisp)Magic File Names'.
3838 This handler ought to run PROGRAM, perhaps on the local host,
3839 perhaps on a remote host that corresponds to `default-directory'.
3840 In the latter case, the local part of `default-directory' becomes
3841 the working directory of the process.
3843 PROGRAM and PROGRAM-ARGS might be file names. They are not
3844 objects of file handler invocation. File handlers might not
3845 support pty association, if PROGRAM is nil."
3846 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3847 (if fh (apply fh 'start-file-process name buffer program program-args)
3848 (apply 'start-process name buffer program program-args))))
3850 ;;;; Process menu
3852 (defvar tabulated-list-format)
3853 (defvar tabulated-list-entries)
3854 (defvar tabulated-list-sort-key)
3855 (declare-function tabulated-list-init-header "tabulated-list" ())
3856 (declare-function tabulated-list-print "tabulated-list"
3857 (&optional remember-pos update))
3859 (defvar process-menu-query-only nil)
3861 (defvar process-menu-mode-map
3862 (let ((map (make-sparse-keymap)))
3863 (define-key map [?d] 'process-menu-delete-process)
3864 map))
3866 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3867 "Major mode for listing the processes called by Emacs."
3868 (setq tabulated-list-format [("Process" 15 t)
3869 ("PID" 7 t)
3870 ("Status" 7 t)
3871 ("Buffer" 15 t)
3872 ("TTY" 12 t)
3873 ("Command" 0 t)])
3874 (make-local-variable 'process-menu-query-only)
3875 (setq tabulated-list-sort-key (cons "Process" nil))
3876 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3877 (tabulated-list-init-header))
3879 (defun process-menu-delete-process ()
3880 "Kill process at point in a `list-processes' buffer."
3881 (interactive)
3882 (let ((pos (point)))
3883 (delete-process (tabulated-list-get-id))
3884 (revert-buffer)
3885 (goto-char (min pos (point-max)))
3886 (if (eobp)
3887 (forward-line -1)
3888 (beginning-of-line))))
3890 (defun list-processes--refresh ()
3891 "Recompute the list of processes for the Process List buffer.
3892 Also, delete any process that is exited or signaled."
3893 (setq tabulated-list-entries nil)
3894 (dolist (p (process-list))
3895 (cond ((memq (process-status p) '(exit signal closed))
3896 (delete-process p))
3897 ((or (not process-menu-query-only)
3898 (process-query-on-exit-flag p))
3899 (let* ((buf (process-buffer p))
3900 (type (process-type p))
3901 (pid (if (process-id p) (format "%d" (process-id p)) "--"))
3902 (name (process-name p))
3903 (status (symbol-name (process-status p)))
3904 (buf-label (if (buffer-live-p buf)
3905 `(,(buffer-name buf)
3906 face link
3907 help-echo ,(format-message
3908 "Visit buffer `%s'"
3909 (buffer-name buf))
3910 follow-link t
3911 process-buffer ,buf
3912 action process-menu-visit-buffer)
3913 "--"))
3914 (tty (or (process-tty-name p) "--"))
3915 (cmd
3916 (if (memq type '(network serial))
3917 (let ((contact (process-contact p t)))
3918 (if (eq type 'network)
3919 (format "(%s %s)"
3920 (if (plist-get contact :type)
3921 "datagram"
3922 "network")
3923 (if (plist-get contact :server)
3924 (format "server on %s"
3926 (plist-get contact :host)
3927 (plist-get contact :local)))
3928 (format "connection to %s"
3929 (plist-get contact :host))))
3930 (format "(serial port %s%s)"
3931 (or (plist-get contact :port) "?")
3932 (let ((speed (plist-get contact :speed)))
3933 (if speed
3934 (format " at %s b/s" speed)
3935 "")))))
3936 (mapconcat 'identity (process-command p) " "))))
3937 (push (list p (vector name pid status buf-label tty cmd))
3938 tabulated-list-entries))))))
3940 (defun process-menu-visit-buffer (button)
3941 (display-buffer (button-get button 'process-buffer)))
3943 (defun list-processes (&optional query-only buffer)
3944 "Display a list of all processes that are Emacs sub-processes.
3945 If optional argument QUERY-ONLY is non-nil, only processes with
3946 the query-on-exit flag set are listed.
3947 Any process listed as exited or signaled is actually eliminated
3948 after the listing is made.
3949 Optional argument BUFFER specifies a buffer to use, instead of
3950 \"*Process List*\".
3951 The return value is always nil.
3953 This function lists only processes that were launched by Emacs. To
3954 see other processes running on the system, use `list-system-processes'."
3955 (interactive)
3956 (or (fboundp 'process-list)
3957 (error "Asynchronous subprocesses are not supported on this system"))
3958 (unless (bufferp buffer)
3959 (setq buffer (get-buffer-create "*Process List*")))
3960 (with-current-buffer buffer
3961 (process-menu-mode)
3962 (setq process-menu-query-only query-only)
3963 (list-processes--refresh)
3964 (tabulated-list-print))
3965 (display-buffer buffer)
3966 nil)
3968 ;;;; Prefix commands
3970 (setq prefix-command--needs-update nil)
3971 (setq prefix-command--last-echo nil)
3973 (defun internal-echo-keystrokes-prefix ()
3974 ;; BEWARE: Called directly from C code.
3975 ;; If the return value is non-nil, it means we are in the middle of
3976 ;; a command with prefix, such as a command invoked with prefix-arg.
3977 (if (not prefix-command--needs-update)
3978 prefix-command--last-echo
3979 (setq prefix-command--last-echo
3980 (let ((strs nil))
3981 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
3982 (lambda (fun) (push (funcall fun) strs)))
3983 (setq strs (delq nil strs))
3984 (when strs (mapconcat #'identity strs " "))))))
3986 (defvar prefix-command-echo-keystrokes-functions nil
3987 "Abnormal hook which constructs the description of the current prefix state.
3988 Each function is called with no argument, should return a string or nil.")
3990 (defun prefix-command-update ()
3991 "Update state of prefix commands.
3992 Call it whenever you change the \"prefix command state\"."
3993 (setq prefix-command--needs-update t))
3995 (defvar prefix-command-preserve-state-hook nil
3996 "Normal hook run when a command needs to preserve the prefix.")
3998 (defun prefix-command-preserve-state ()
3999 "Pass the current prefix command state to the next command.
4000 Should be called by all prefix commands.
4001 Runs `prefix-command-preserve-state-hook'."
4002 (run-hooks 'prefix-command-preserve-state-hook)
4003 ;; If the current command is a prefix command, we don't want the next (real)
4004 ;; command to have `last-command' set to, say, `universal-argument'.
4005 (setq this-command last-command)
4006 (setq real-this-command real-last-command)
4007 (prefix-command-update))
4009 (defun reset-this-command-lengths ()
4010 (declare (obsolete prefix-command-preserve-state "25.1"))
4011 nil)
4013 ;;;;; The main prefix command.
4015 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
4017 (add-hook 'prefix-command-echo-keystrokes-functions
4018 #'universal-argument--description)
4019 (defun universal-argument--description ()
4020 (when prefix-arg
4021 (concat "C-u"
4022 (pcase prefix-arg
4023 (`(-) " -")
4024 (`(,(and (pred integerp) n))
4025 (let ((str ""))
4026 (while (and (> n 4) (= (mod n 4) 0))
4027 (setq str (concat str " C-u"))
4028 (setq n (/ n 4)))
4029 (if (= n 4) str (format " %s" prefix-arg))))
4030 (_ (format " %s" prefix-arg))))))
4032 (add-hook 'prefix-command-preserve-state-hook
4033 #'universal-argument--preserve)
4034 (defun universal-argument--preserve ()
4035 (setq prefix-arg current-prefix-arg))
4037 (defvar universal-argument-map
4038 (let ((map (make-sparse-keymap))
4039 (universal-argument-minus
4040 ;; For backward compatibility, minus with no modifiers is an ordinary
4041 ;; command if digits have already been entered.
4042 `(menu-item "" negative-argument
4043 :filter ,(lambda (cmd)
4044 (if (integerp prefix-arg) nil cmd)))))
4045 (define-key map [switch-frame]
4046 (lambda (e) (interactive "e")
4047 (handle-switch-frame e) (universal-argument--mode)))
4048 (define-key map [?\C-u] 'universal-argument-more)
4049 (define-key map [?-] universal-argument-minus)
4050 (define-key map [?0] 'digit-argument)
4051 (define-key map [?1] 'digit-argument)
4052 (define-key map [?2] 'digit-argument)
4053 (define-key map [?3] 'digit-argument)
4054 (define-key map [?4] 'digit-argument)
4055 (define-key map [?5] 'digit-argument)
4056 (define-key map [?6] 'digit-argument)
4057 (define-key map [?7] 'digit-argument)
4058 (define-key map [?8] 'digit-argument)
4059 (define-key map [?9] 'digit-argument)
4060 (define-key map [kp-0] 'digit-argument)
4061 (define-key map [kp-1] 'digit-argument)
4062 (define-key map [kp-2] 'digit-argument)
4063 (define-key map [kp-3] 'digit-argument)
4064 (define-key map [kp-4] 'digit-argument)
4065 (define-key map [kp-5] 'digit-argument)
4066 (define-key map [kp-6] 'digit-argument)
4067 (define-key map [kp-7] 'digit-argument)
4068 (define-key map [kp-8] 'digit-argument)
4069 (define-key map [kp-9] 'digit-argument)
4070 (define-key map [kp-subtract] universal-argument-minus)
4071 map)
4072 "Keymap used while processing \\[universal-argument].")
4074 (defun universal-argument--mode ()
4075 (prefix-command-update)
4076 (set-transient-map universal-argument-map nil))
4078 (defun universal-argument ()
4079 "Begin a numeric argument for the following command.
4080 Digits or minus sign following \\[universal-argument] make up the numeric argument.
4081 \\[universal-argument] following the digits or minus sign ends the argument.
4082 \\[universal-argument] without digits or minus sign provides 4 as argument.
4083 Repeating \\[universal-argument] without digits or minus sign
4084 multiplies the argument by 4 each time.
4085 For some commands, just \\[universal-argument] by itself serves as a flag
4086 which is different in effect from any particular numeric argument.
4087 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
4088 (interactive)
4089 (prefix-command-preserve-state)
4090 (setq prefix-arg (list 4))
4091 (universal-argument--mode))
4093 (defun universal-argument-more (arg)
4094 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
4095 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
4096 (interactive "P")
4097 (prefix-command-preserve-state)
4098 (setq prefix-arg (if (consp arg)
4099 (list (* 4 (car arg)))
4100 (if (eq arg '-)
4101 (list -4)
4102 arg)))
4103 (when (consp prefix-arg) (universal-argument--mode)))
4105 (defun negative-argument (arg)
4106 "Begin a negative numeric argument for the next command.
4107 \\[universal-argument] following digits or minus sign ends the argument."
4108 (interactive "P")
4109 (prefix-command-preserve-state)
4110 (setq prefix-arg (cond ((integerp arg) (- arg))
4111 ((eq arg '-) nil)
4112 (t '-)))
4113 (universal-argument--mode))
4115 (defun digit-argument (arg)
4116 "Part of the numeric argument for the next command.
4117 \\[universal-argument] following digits or minus sign ends the argument."
4118 (interactive "P")
4119 (prefix-command-preserve-state)
4120 (let* ((char (if (integerp last-command-event)
4121 last-command-event
4122 (get last-command-event 'ascii-character)))
4123 (digit (- (logand char ?\177) ?0)))
4124 (setq prefix-arg (cond ((integerp arg)
4125 (+ (* arg 10)
4126 (if (< arg 0) (- digit) digit)))
4127 ((eq arg '-)
4128 ;; Treat -0 as just -, so that -01 will work.
4129 (if (zerop digit) '- (- digit)))
4131 digit))))
4132 (universal-argument--mode))
4135 (defvar filter-buffer-substring-functions nil
4136 "This variable is a wrapper hook around `buffer-substring--filter'.
4137 \(See `with-wrapper-hook' for details about wrapper hooks.)")
4138 (make-obsolete-variable 'filter-buffer-substring-functions
4139 'filter-buffer-substring-function "24.4")
4141 (defvar filter-buffer-substring-function #'buffer-substring--filter
4142 "Function to perform the filtering in `filter-buffer-substring'.
4143 The function is called with the same 3 arguments (BEG END DELETE)
4144 that `filter-buffer-substring' received. It should return the
4145 buffer substring between BEG and END, after filtering. If DELETE is
4146 non-nil, it should delete the text between BEG and END from the buffer.")
4148 (defvar buffer-substring-filters nil
4149 "List of filter functions for `buffer-substring--filter'.
4150 Each function must accept a single argument, a string, and return a string.
4151 The buffer substring is passed to the first function in the list,
4152 and the return value of each function is passed to the next.
4153 As a special convention, point is set to the start of the buffer text
4154 being operated on (i.e., the first argument of `buffer-substring--filter')
4155 before these functions are called.")
4156 (make-obsolete-variable 'buffer-substring-filters
4157 'filter-buffer-substring-function "24.1")
4159 (defun filter-buffer-substring (beg end &optional delete)
4160 "Return the buffer substring between BEG and END, after filtering.
4161 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4163 This calls the function that `filter-buffer-substring-function' specifies
4164 \(passing the same three arguments that it received) to do the work,
4165 and returns whatever it does. The default function does no filtering,
4166 unless a hook has been set.
4168 Use `filter-buffer-substring' instead of `buffer-substring',
4169 `buffer-substring-no-properties', or `delete-and-extract-region' when
4170 you want to allow filtering to take place. For example, major or minor
4171 modes can use `filter-buffer-substring-function' to extract characters
4172 that are special to a buffer, and should not be copied into other buffers."
4173 (funcall filter-buffer-substring-function beg end delete))
4175 (defun buffer-substring--filter (beg end &optional delete)
4176 "Default function to use for `filter-buffer-substring-function'.
4177 Its arguments and return value are as specified for `filter-buffer-substring'.
4178 Also respects the obsolete wrapper hook `filter-buffer-substring-functions'
4179 \(see `with-wrapper-hook' for details about wrapper hooks),
4180 and the abnormal hook `buffer-substring-filters'.
4181 No filtering is done unless a hook says to."
4182 (subr--with-wrapper-hook-no-warnings
4183 filter-buffer-substring-functions (beg end delete)
4184 (cond
4185 ((or delete buffer-substring-filters)
4186 (save-excursion
4187 (goto-char beg)
4188 (let ((string (if delete (delete-and-extract-region beg end)
4189 (buffer-substring beg end))))
4190 (dolist (filter buffer-substring-filters)
4191 (setq string (funcall filter string)))
4192 string)))
4194 (buffer-substring beg end)))))
4197 ;;;; Window system cut and paste hooks.
4199 (defvar interprogram-cut-function #'gui-select-text
4200 "Function to call to make a killed region available to other programs.
4201 Most window systems provide a facility for cutting and pasting
4202 text between different programs, such as the clipboard on X and
4203 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4205 This variable holds a function that Emacs calls whenever text is
4206 put in the kill ring, to make the new kill available to other
4207 programs. The function takes one argument, TEXT, which is a
4208 string containing the text which should be made available.")
4210 (defvar interprogram-paste-function #'gui-selection-value
4211 "Function to call to get text cut from other programs.
4212 Most window systems provide a facility for cutting and pasting
4213 text between different programs, such as the clipboard on X and
4214 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4216 This variable holds a function that Emacs calls to obtain text
4217 that other programs have provided for pasting. The function is
4218 called with no arguments. If no other program has provided text
4219 to paste, the function should return nil (in which case the
4220 caller, usually `current-kill', should use the top of the Emacs
4221 kill ring). If another program has provided text to paste, the
4222 function should return that text as a string (in which case the
4223 caller should put this string in the kill ring as the latest
4224 kill).
4226 The function may also return a list of strings if the window
4227 system supports multiple selections. The first string will be
4228 used as the pasted text, but the other will be placed in the kill
4229 ring for easy access via `yank-pop'.
4231 Note that the function should return a string only if a program
4232 other than Emacs has provided a string for pasting; if Emacs
4233 provided the most recent string, the function should return nil.
4234 If it is difficult to tell whether Emacs or some other program
4235 provided the current string, it is probably good enough to return
4236 nil if the string is equal (according to `string=') to the last
4237 text Emacs provided.")
4241 ;;;; The kill ring data structure.
4243 (defvar kill-ring nil
4244 "List of killed text sequences.
4245 Since the kill ring is supposed to interact nicely with cut-and-paste
4246 facilities offered by window systems, use of this variable should
4247 interact nicely with `interprogram-cut-function' and
4248 `interprogram-paste-function'. The functions `kill-new',
4249 `kill-append', and `current-kill' are supposed to implement this
4250 interaction; you may want to use them instead of manipulating the kill
4251 ring directly.")
4253 (defcustom kill-ring-max 60
4254 "Maximum length of kill ring before oldest elements are thrown away."
4255 :type 'integer
4256 :group 'killing)
4258 (defvar kill-ring-yank-pointer nil
4259 "The tail of the kill ring whose car is the last thing yanked.")
4261 (defcustom save-interprogram-paste-before-kill nil
4262 "Save clipboard strings into kill ring before replacing them.
4263 When one selects something in another program to paste it into Emacs,
4264 but kills something in Emacs before actually pasting it,
4265 this selection is gone unless this variable is non-nil,
4266 in which case the other program's selection is saved in the `kill-ring'
4267 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4268 :type 'boolean
4269 :group 'killing
4270 :version "23.2")
4272 (defcustom kill-do-not-save-duplicates nil
4273 "Do not add a new string to `kill-ring' if it duplicates the last one.
4274 The comparison is done using `equal-including-properties'."
4275 :type 'boolean
4276 :group 'killing
4277 :version "23.2")
4279 (defun kill-new (string &optional replace)
4280 "Make STRING the latest kill in the kill ring.
4281 Set `kill-ring-yank-pointer' to point to it.
4282 If `interprogram-cut-function' is non-nil, apply it to STRING.
4283 Optional second argument REPLACE non-nil means that STRING will replace
4284 the front of the kill ring, rather than being added to the list.
4286 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4287 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4288 STRING.
4290 When the yank handler has a non-nil PARAM element, the original STRING
4291 argument is not used by `insert-for-yank'. However, since Lisp code
4292 may access and use elements from the kill ring directly, the STRING
4293 argument should still be a \"useful\" string for such uses."
4294 (unless (and kill-do-not-save-duplicates
4295 ;; Due to text properties such as 'yank-handler that
4296 ;; can alter the contents to yank, comparison using
4297 ;; `equal' is unsafe.
4298 (equal-including-properties string (car kill-ring)))
4299 (if (fboundp 'menu-bar-update-yank-menu)
4300 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4301 (when save-interprogram-paste-before-kill
4302 (let ((interprogram-paste (and interprogram-paste-function
4303 (funcall interprogram-paste-function))))
4304 (when interprogram-paste
4305 (dolist (s (if (listp interprogram-paste)
4306 (nreverse interprogram-paste)
4307 (list interprogram-paste)))
4308 (unless (and kill-do-not-save-duplicates
4309 (equal-including-properties s (car kill-ring)))
4310 (push s kill-ring))))))
4311 (unless (and kill-do-not-save-duplicates
4312 (equal-including-properties string (car kill-ring)))
4313 (if (and replace kill-ring)
4314 (setcar kill-ring string)
4315 (push string kill-ring)
4316 (if (> (length kill-ring) kill-ring-max)
4317 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4318 (setq kill-ring-yank-pointer kill-ring)
4319 (if interprogram-cut-function
4320 (funcall interprogram-cut-function string)))
4322 ;; It has been argued that this should work similar to `self-insert-command'
4323 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4324 (defcustom kill-append-merge-undo nil
4325 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4326 :type 'boolean
4327 :group 'killing
4328 :version "25.1")
4330 (defun kill-append (string before-p)
4331 "Append STRING to the end of the latest kill in the kill ring.
4332 If BEFORE-P is non-nil, prepend STRING to the kill.
4333 Also removes the last undo boundary in the current buffer,
4334 depending on `kill-append-merge-undo'.
4335 If `interprogram-cut-function' is set, pass the resulting kill to it."
4336 (let* ((cur (car kill-ring)))
4337 (kill-new (if before-p (concat string cur) (concat cur string))
4338 (or (= (length cur) 0)
4339 (equal nil (get-text-property 0 'yank-handler cur))))
4340 (when (and kill-append-merge-undo (not buffer-read-only))
4341 (let ((prev buffer-undo-list)
4342 (next (cdr buffer-undo-list)))
4343 ;; find the next undo boundary
4344 (while (car next)
4345 (pop next)
4346 (pop prev))
4347 ;; remove this undo boundary
4348 (when prev
4349 (setcdr prev (cdr next)))))))
4351 (defcustom yank-pop-change-selection nil
4352 "Whether rotating the kill ring changes the window system selection.
4353 If non-nil, whenever the kill ring is rotated (usually via the
4354 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4355 to copy the new kill to the window system selection."
4356 :type 'boolean
4357 :group 'killing
4358 :version "23.1")
4360 (defun current-kill (n &optional do-not-move)
4361 "Rotate the yanking point by N places, and then return that kill.
4362 If N is zero and `interprogram-paste-function' is set to a
4363 function that returns a string or a list of strings, and if that
4364 function doesn't return nil, then that string (or list) is added
4365 to the front of the kill ring and the string (or first string in
4366 the list) is returned as the latest kill.
4368 If N is not zero, and if `yank-pop-change-selection' is
4369 non-nil, use `interprogram-cut-function' to transfer the
4370 kill at the new yank point into the window system selection.
4372 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4373 move the yanking point; just return the Nth kill forward."
4375 (let ((interprogram-paste (and (= n 0)
4376 interprogram-paste-function
4377 (funcall interprogram-paste-function))))
4378 (if interprogram-paste
4379 (progn
4380 ;; Disable the interprogram cut function when we add the new
4381 ;; text to the kill ring, so Emacs doesn't try to own the
4382 ;; selection, with identical text.
4383 (let ((interprogram-cut-function nil))
4384 (if (listp interprogram-paste)
4385 (mapc 'kill-new (nreverse interprogram-paste))
4386 (kill-new interprogram-paste)))
4387 (car kill-ring))
4388 (or kill-ring (error "Kill ring is empty"))
4389 (let ((ARGth-kill-element
4390 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4391 (length kill-ring))
4392 kill-ring)))
4393 (unless do-not-move
4394 (setq kill-ring-yank-pointer ARGth-kill-element)
4395 (when (and yank-pop-change-selection
4396 (> n 0)
4397 interprogram-cut-function)
4398 (funcall interprogram-cut-function (car ARGth-kill-element))))
4399 (car ARGth-kill-element)))))
4403 ;;;; Commands for manipulating the kill ring.
4405 (defcustom kill-read-only-ok nil
4406 "Non-nil means don't signal an error for killing read-only text."
4407 :type 'boolean
4408 :group 'killing)
4410 (defun kill-region (beg end &optional region)
4411 "Kill (\"cut\") text between point and mark.
4412 This deletes the text from the buffer and saves it in the kill ring.
4413 The command \\[yank] can retrieve it from there.
4414 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4416 If you want to append the killed region to the last killed text,
4417 use \\[append-next-kill] before \\[kill-region].
4419 Any command that calls this function is a \"kill command\".
4420 If the previous command was also a kill command,
4421 the text killed this time appends to the text killed last time
4422 to make one entry in the kill ring.
4424 The killed text is filtered by `filter-buffer-substring' before it is
4425 saved in the kill ring, so the actual saved text might be different
4426 from what was killed.
4428 If the buffer is read-only, Emacs will beep and refrain from deleting
4429 the text, but put the text in the kill ring anyway. This means that
4430 you can use the killing commands to copy text from a read-only buffer.
4432 Lisp programs should use this function for killing text.
4433 (To delete text, use `delete-region'.)
4434 Supply two arguments, character positions BEG and END indicating the
4435 stretch of text to be killed. If the optional argument REGION is
4436 non-nil, the function ignores BEG and END, and kills the current
4437 region instead."
4438 ;; Pass mark first, then point, because the order matters when
4439 ;; calling `kill-append'.
4440 (interactive (list (mark) (point) 'region))
4441 (unless (and beg end)
4442 (user-error "The mark is not set now, so there is no region"))
4443 (condition-case nil
4444 (let ((string (if region
4445 (funcall region-extract-function 'delete)
4446 (filter-buffer-substring beg end 'delete))))
4447 (when string ;STRING is nil if BEG = END
4448 ;; Add that string to the kill ring, one way or another.
4449 (if (eq last-command 'kill-region)
4450 (kill-append string (< end beg))
4451 (kill-new string)))
4452 (when (or string (eq last-command 'kill-region))
4453 (setq this-command 'kill-region))
4454 (setq deactivate-mark t)
4455 nil)
4456 ((buffer-read-only text-read-only)
4457 ;; The code above failed because the buffer, or some of the characters
4458 ;; in the region, are read-only.
4459 ;; We should beep, in case the user just isn't aware of this.
4460 ;; However, there's no harm in putting
4461 ;; the region's text in the kill ring, anyway.
4462 (copy-region-as-kill beg end region)
4463 ;; Set this-command now, so it will be set even if we get an error.
4464 (setq this-command 'kill-region)
4465 ;; This should barf, if appropriate, and give us the correct error.
4466 (if kill-read-only-ok
4467 (progn (message "Read only text copied to kill ring") nil)
4468 ;; Signal an error if the buffer is read-only.
4469 (barf-if-buffer-read-only)
4470 ;; If the buffer isn't read-only, the text is.
4471 (signal 'text-read-only (list (current-buffer)))))))
4473 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4474 ;; to get two copies of the text when the user accidentally types M-w and
4475 ;; then corrects it with the intended C-w.
4476 (defun copy-region-as-kill (beg end &optional region)
4477 "Save the region as if killed, but don't kill it.
4478 In Transient Mark mode, deactivate the mark.
4479 If `interprogram-cut-function' is non-nil, also save the text for a window
4480 system cut and paste.
4482 The copied text is filtered by `filter-buffer-substring' before it is
4483 saved in the kill ring, so the actual saved text might be different
4484 from what was in the buffer.
4486 When called from Lisp, save in the kill ring the stretch of text
4487 between BEG and END, unless the optional argument REGION is
4488 non-nil, in which case ignore BEG and END, and save the current
4489 region instead.
4491 This command's old key binding has been given to `kill-ring-save'."
4492 ;; Pass mark first, then point, because the order matters when
4493 ;; calling `kill-append'.
4494 (interactive (list (mark) (point)
4495 (prefix-numeric-value current-prefix-arg)))
4496 (let ((str (if region
4497 (funcall region-extract-function nil)
4498 (filter-buffer-substring beg end))))
4499 (if (eq last-command 'kill-region)
4500 (kill-append str (< end beg))
4501 (kill-new str)))
4502 (setq deactivate-mark t)
4503 nil)
4505 (defun kill-ring-save (beg end &optional region)
4506 "Save the region as if killed, but don't kill it.
4507 In Transient Mark mode, deactivate the mark.
4508 If `interprogram-cut-function' is non-nil, also save the text for a window
4509 system cut and paste.
4511 If you want to append the killed line to the last killed text,
4512 use \\[append-next-kill] before \\[kill-ring-save].
4514 The copied text is filtered by `filter-buffer-substring' before it is
4515 saved in the kill ring, so the actual saved text might be different
4516 from what was in the buffer.
4518 When called from Lisp, save in the kill ring the stretch of text
4519 between BEG and END, unless the optional argument REGION is
4520 non-nil, in which case ignore BEG and END, and save the current
4521 region instead.
4523 This command is similar to `copy-region-as-kill', except that it gives
4524 visual feedback indicating the extent of the region being copied."
4525 ;; Pass mark first, then point, because the order matters when
4526 ;; calling `kill-append'.
4527 (interactive (list (mark) (point)
4528 (prefix-numeric-value current-prefix-arg)))
4529 (copy-region-as-kill beg end region)
4530 ;; This use of called-interactively-p is correct because the code it
4531 ;; controls just gives the user visual feedback.
4532 (if (called-interactively-p 'interactive)
4533 (indicate-copied-region)))
4535 (defun indicate-copied-region (&optional message-len)
4536 "Indicate that the region text has been copied interactively.
4537 If the mark is visible in the selected window, blink the cursor
4538 between point and mark if there is currently no active region
4539 highlighting.
4541 If the mark lies outside the selected window, display an
4542 informative message containing a sample of the copied text. The
4543 optional argument MESSAGE-LEN, if non-nil, specifies the length
4544 of this sample text; it defaults to 40."
4545 (let ((mark (mark t))
4546 (point (point))
4547 ;; Inhibit quitting so we can make a quit here
4548 ;; look like a C-g typed as a command.
4549 (inhibit-quit t))
4550 (if (pos-visible-in-window-p mark (selected-window))
4551 ;; Swap point-and-mark quickly so as to show the region that
4552 ;; was selected. Don't do it if the region is highlighted.
4553 (unless (and (region-active-p)
4554 (face-background 'region))
4555 ;; Swap point and mark.
4556 (set-marker (mark-marker) (point) (current-buffer))
4557 (goto-char mark)
4558 (sit-for blink-matching-delay)
4559 ;; Swap back.
4560 (set-marker (mark-marker) mark (current-buffer))
4561 (goto-char point)
4562 ;; If user quit, deactivate the mark
4563 ;; as C-g would as a command.
4564 (and quit-flag (region-active-p)
4565 (deactivate-mark)))
4566 (let ((len (min (abs (- mark point))
4567 (or message-len 40))))
4568 (if (< point mark)
4569 ;; Don't say "killed"; that is misleading.
4570 (message "Saved text until \"%s\""
4571 (buffer-substring-no-properties (- mark len) mark))
4572 (message "Saved text from \"%s\""
4573 (buffer-substring-no-properties mark (+ mark len))))))))
4575 (defun append-next-kill (&optional interactive)
4576 "Cause following command, if it kills, to add to previous kill.
4577 If the next command kills forward from point, the kill is
4578 appended to the previous killed text. If the command kills
4579 backward, the kill is prepended. Kill commands that act on the
4580 region, such as `kill-region', are regarded as killing forward if
4581 point is after mark, and killing backward if point is before
4582 mark.
4584 If the next command is not a kill command, `append-next-kill' has
4585 no effect.
4587 The argument is used for internal purposes; do not supply one."
4588 (interactive "p")
4589 ;; We don't use (interactive-p), since that breaks kbd macros.
4590 (if interactive
4591 (progn
4592 (setq this-command 'kill-region)
4593 (message "If the next command is a kill, it will append"))
4594 (setq last-command 'kill-region)))
4596 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4597 "Character set that matches bidirectional formatting control characters.")
4599 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4600 "Character set that matches any character except bidirectional controls.")
4602 (defun squeeze-bidi-context-1 (from to category replacement)
4603 "A subroutine of `squeeze-bidi-context'.
4604 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4605 (let ((pt (copy-marker from))
4606 (limit (copy-marker to))
4607 (old-pt 0)
4608 lim1)
4609 (setq lim1 limit)
4610 (goto-char pt)
4611 (while (< pt limit)
4612 (if (> pt old-pt)
4613 (move-marker lim1
4614 (save-excursion
4615 ;; L and R categories include embedding and
4616 ;; override controls, but we don't want to
4617 ;; replace them, because that might change
4618 ;; the visual order. Likewise with PDF and
4619 ;; isolate controls.
4620 (+ pt (skip-chars-forward
4621 bidi-directional-non-controls-chars
4622 limit)))))
4623 ;; Replace any run of non-RTL characters by a single LRM.
4624 (if (null (re-search-forward category lim1 t))
4625 ;; No more characters of CATEGORY, we are done.
4626 (setq pt limit)
4627 (replace-match replacement nil t)
4628 (move-marker pt (point)))
4629 (setq old-pt pt)
4630 ;; Skip directional controls, if any.
4631 (move-marker
4632 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4634 (defun squeeze-bidi-context (from to)
4635 "Replace characters between FROM and TO while keeping bidi context.
4637 This function replaces the region of text with as few characters
4638 as possible, while preserving the effect that region will have on
4639 bidirectional display before and after the region."
4640 (let ((start (set-marker (make-marker)
4641 (if (> from 0) from (+ (point-max) from))))
4642 (end (set-marker (make-marker) to))
4643 ;; This is for when they copy text with read-only text
4644 ;; properties.
4645 (inhibit-read-only t))
4646 (if (null (marker-position end))
4647 (setq end (point-max-marker)))
4648 ;; Replace each run of non-RTL characters with a single LRM.
4649 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4650 ;; Replace each run of non-LTR characters with a single RLM. Note
4651 ;; that the \cR category includes both the Arabic Letter (AL) and
4652 ;; R characters; here we ignore the distinction between them,
4653 ;; because that distinction only affects Arabic Number (AN)
4654 ;; characters, which are weak and don't affect the reordering.
4655 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4657 (defun line-substring-with-bidi-context (start end &optional no-properties)
4658 "Return buffer text between START and END with its bidi context.
4660 START and END are assumed to belong to the same physical line
4661 of buffer text. This function prepends and appends to the text
4662 between START and END bidi control characters that preserve the
4663 visual order of that text when it is inserted at some other place."
4664 (if (or (< start (point-min))
4665 (> end (point-max)))
4666 (signal 'args-out-of-range (list (current-buffer) start end)))
4667 (let ((buf (current-buffer))
4668 substr para-dir from to)
4669 (save-excursion
4670 (goto-char start)
4671 (setq para-dir (current-bidi-paragraph-direction))
4672 (setq from (line-beginning-position)
4673 to (line-end-position))
4674 (goto-char from)
4675 ;; If we don't have any mixed directional characters in the
4676 ;; entire line, we can just copy the substring without adding
4677 ;; any context.
4678 (if (or (looking-at-p "\\CR*$")
4679 (looking-at-p "\\CL*$"))
4680 (setq substr (if no-properties
4681 (buffer-substring-no-properties start end)
4682 (buffer-substring start end)))
4683 (setq substr
4684 (with-temp-buffer
4685 (if no-properties
4686 (insert-buffer-substring-no-properties buf from to)
4687 (insert-buffer-substring buf from to))
4688 (squeeze-bidi-context 1 (1+ (- start from)))
4689 (squeeze-bidi-context (- end to) nil)
4690 (buffer-substring 1 (point-max)))))
4692 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4693 ;; (1) force the string to have the same base embedding
4694 ;; direction as the paragraph direction at the source, no matter
4695 ;; what is the paragraph direction at destination; and (2) avoid
4696 ;; affecting the visual order of the surrounding text at
4697 ;; destination if there are characters of different
4698 ;; directionality there.
4699 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4700 substr "\x2069"))))
4702 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4703 "Return portion of current buffer between START and END with bidi context.
4705 This function works similar to `buffer-substring', but it prepends and
4706 appends to the text bidi directional control characters necessary to
4707 preserve the visual appearance of the text if it is inserted at another
4708 place. This is useful when the buffer substring includes bidirectional
4709 text and control characters that cause non-trivial reordering on display.
4710 If copied verbatim, such text can have a very different visual appearance,
4711 and can also change the visual appearance of the surrounding text at the
4712 destination of the copy.
4714 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4715 the text properties."
4716 (let (line-end substr)
4717 (if (or (< start (point-min))
4718 (> end (point-max)))
4719 (signal 'args-out-of-range (list (current-buffer) start end)))
4720 (save-excursion
4721 (goto-char start)
4722 (setq line-end (min end (line-end-position)))
4723 (while (< start end)
4724 (setq substr
4725 (concat substr
4726 (if substr "\n" "")
4727 (line-substring-with-bidi-context start line-end
4728 no-properties)))
4729 (forward-line 1)
4730 (setq start (point))
4731 (setq line-end (min end (line-end-position))))
4732 substr)))
4734 ;; Yanking.
4736 (defcustom yank-handled-properties
4737 '((font-lock-face . yank-handle-font-lock-face-property)
4738 (category . yank-handle-category-property))
4739 "List of special text property handling conditions for yanking.
4740 Each element should have the form (PROP . FUN), where PROP is a
4741 property symbol and FUN is a function. When the `yank' command
4742 inserts text into the buffer, it scans the inserted text for
4743 stretches of text that have `eq' values of the text property
4744 PROP; for each such stretch of text, FUN is called with three
4745 arguments: the property's value in that text, and the start and
4746 end positions of the text.
4748 This is done prior to removing the properties specified by
4749 `yank-excluded-properties'."
4750 :group 'killing
4751 :type '(repeat (cons (symbol :tag "property symbol")
4752 function))
4753 :version "24.3")
4755 ;; This is actually used in subr.el but defcustom does not work there.
4756 (defcustom yank-excluded-properties
4757 '(category field follow-link fontified font-lock-face help-echo
4758 intangible invisible keymap local-map mouse-face read-only
4759 yank-handler)
4760 "Text properties to discard when yanking.
4761 The value should be a list of text properties to discard or t,
4762 which means to discard all text properties.
4764 See also `yank-handled-properties'."
4765 :type '(choice (const :tag "All" t) (repeat symbol))
4766 :group 'killing
4767 :version "24.3")
4769 (defvar yank-window-start nil)
4770 (defvar yank-undo-function nil
4771 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4772 Function is called with two parameters, START and END corresponding to
4773 the value of the mark and point; it is guaranteed that START <= END.
4774 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4776 (defun yank-pop (&optional arg)
4777 "Replace just-yanked stretch of killed text with a different stretch.
4778 This command is allowed only immediately after a `yank' or a `yank-pop'.
4779 At such a time, the region contains a stretch of reinserted
4780 previously-killed text. `yank-pop' deletes that text and inserts in its
4781 place a different stretch of killed text.
4783 With no argument, the previous kill is inserted.
4784 With argument N, insert the Nth previous kill.
4785 If N is negative, this is a more recent kill.
4787 The sequence of kills wraps around, so that after the oldest one
4788 comes the newest one.
4790 This command honors the `yank-handled-properties' and
4791 `yank-excluded-properties' variables, and the `yank-handler' text
4792 property, in the way that `yank' does."
4793 (interactive "*p")
4794 (if (not (eq last-command 'yank))
4795 (user-error "Previous command was not a yank"))
4796 (setq this-command 'yank)
4797 (unless arg (setq arg 1))
4798 (let ((inhibit-read-only t)
4799 (before (< (point) (mark t))))
4800 (if before
4801 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4802 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4803 (setq yank-undo-function nil)
4804 (set-marker (mark-marker) (point) (current-buffer))
4805 (insert-for-yank (current-kill arg))
4806 ;; Set the window start back where it was in the yank command,
4807 ;; if possible.
4808 (set-window-start (selected-window) yank-window-start t)
4809 (if before
4810 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4811 ;; It is cleaner to avoid activation, even though the command
4812 ;; loop would deactivate the mark because we inserted text.
4813 (goto-char (prog1 (mark t)
4814 (set-marker (mark-marker) (point) (current-buffer))))))
4815 nil)
4817 (defun yank (&optional arg)
4818 "Reinsert (\"paste\") the last stretch of killed text.
4819 More precisely, reinsert the most recent kill, which is the
4820 stretch of killed text most recently killed OR yanked. Put point
4821 at the end, and set mark at the beginning without activating it.
4822 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4823 With argument N, reinsert the Nth most recent kill.
4825 This command honors the `yank-handled-properties' and
4826 `yank-excluded-properties' variables, and the `yank-handler' text
4827 property, as described below.
4829 Properties listed in `yank-handled-properties' are processed,
4830 then those listed in `yank-excluded-properties' are discarded.
4832 If STRING has a non-nil `yank-handler' property anywhere, the
4833 normal insert behavior is altered, and instead, for each contiguous
4834 segment of STRING that has a given value of the `yank-handler'
4835 property, that value is used as follows:
4837 The value of a `yank-handler' property must be a list of one to four
4838 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
4839 FUNCTION, if non-nil, should be a function of one argument (the
4840 object to insert); FUNCTION is called instead of `insert'.
4841 PARAM, if present and non-nil, is passed to FUNCTION (to be handled
4842 in whatever way is appropriate; e.g. if FUNCTION is `yank-rectangle',
4843 PARAM may be a list of strings to insert as a rectangle). If PARAM
4844 is nil, then the current segment of STRING is used.
4845 If NOEXCLUDE is present and non-nil, the normal removal of
4846 `yank-excluded-properties' is not performed; instead FUNCTION is
4847 responsible for the removal. This may be necessary if FUNCTION
4848 adjusts point before or after inserting the object.
4849 UNDO, if present and non-nil, should be a function to be called
4850 by `yank-pop' to undo the insertion of the current PARAM. It is
4851 given two arguments, the start and end of the region. FUNCTION
4852 may set `yank-undo-function' to override UNDO.
4854 See also the command `yank-pop' (\\[yank-pop])."
4855 (interactive "*P")
4856 (setq yank-window-start (window-start))
4857 ;; If we don't get all the way thru, make last-command indicate that
4858 ;; for the following command.
4859 (setq this-command t)
4860 (push-mark (point))
4861 (insert-for-yank (current-kill (cond
4862 ((listp arg) 0)
4863 ((eq arg '-) -2)
4864 (t (1- arg)))))
4865 (if (consp arg)
4866 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4867 ;; It is cleaner to avoid activation, even though the command
4868 ;; loop would deactivate the mark because we inserted text.
4869 (goto-char (prog1 (mark t)
4870 (set-marker (mark-marker) (point) (current-buffer)))))
4871 ;; If we do get all the way thru, make this-command indicate that.
4872 (if (eq this-command t)
4873 (setq this-command 'yank))
4874 nil)
4876 (defun rotate-yank-pointer (arg)
4877 "Rotate the yanking point in the kill ring.
4878 With ARG, rotate that many kills forward (or backward, if negative)."
4879 (interactive "p")
4880 (current-kill arg))
4882 ;; Some kill commands.
4884 ;; Internal subroutine of delete-char
4885 (defun kill-forward-chars (arg)
4886 (if (listp arg) (setq arg (car arg)))
4887 (if (eq arg '-) (setq arg -1))
4888 (kill-region (point) (+ (point) arg)))
4890 ;; Internal subroutine of backward-delete-char
4891 (defun kill-backward-chars (arg)
4892 (if (listp arg) (setq arg (car arg)))
4893 (if (eq arg '-) (setq arg -1))
4894 (kill-region (point) (- (point) arg)))
4896 (defcustom backward-delete-char-untabify-method 'untabify
4897 "The method for untabifying when deleting backward.
4898 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4899 `hungry' -- delete all whitespace, both tabs and spaces;
4900 `all' -- delete all whitespace, including tabs, spaces and newlines;
4901 nil -- just delete one character."
4902 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4903 :version "20.3"
4904 :group 'killing)
4906 (defun backward-delete-char-untabify (arg &optional killp)
4907 "Delete characters backward, changing tabs into spaces.
4908 The exact behavior depends on `backward-delete-char-untabify-method'.
4909 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4910 Interactively, ARG is the prefix arg (default 1)
4911 and KILLP is t if a prefix arg was specified."
4912 (interactive "*p\nP")
4913 (when (eq backward-delete-char-untabify-method 'untabify)
4914 (let ((count arg))
4915 (save-excursion
4916 (while (and (> count 0) (not (bobp)))
4917 (if (= (preceding-char) ?\t)
4918 (let ((col (current-column)))
4919 (forward-char -1)
4920 (setq col (- col (current-column)))
4921 (insert-char ?\s col)
4922 (delete-char 1)))
4923 (forward-char -1)
4924 (setq count (1- count))))))
4925 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4926 ((eq backward-delete-char-untabify-method 'all)
4927 " \t\n\r")))
4928 (n (if skip
4929 (let* ((oldpt (point))
4930 (wh (- oldpt (save-excursion
4931 (skip-chars-backward skip)
4932 (constrain-to-field nil oldpt)))))
4933 (+ arg (if (zerop wh) 0 (1- wh))))
4934 arg)))
4935 ;; Avoid warning about delete-backward-char
4936 (with-no-warnings (delete-backward-char n killp))))
4938 (defun zap-to-char (arg char)
4939 "Kill up to and including ARGth occurrence of CHAR.
4940 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4941 Goes backward if ARG is negative; error if CHAR not found."
4942 (interactive (list (prefix-numeric-value current-prefix-arg)
4943 (read-char "Zap to char: " t)))
4944 ;; Avoid "obsolete" warnings for translation-table-for-input.
4945 (with-no-warnings
4946 (if (char-table-p translation-table-for-input)
4947 (setq char (or (aref translation-table-for-input char) char))))
4948 (kill-region (point) (progn
4949 (search-forward (char-to-string char) nil nil arg)
4950 (point))))
4952 ;; kill-line and its subroutines.
4954 (defcustom kill-whole-line nil
4955 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4956 :type 'boolean
4957 :group 'killing)
4959 (defun kill-line (&optional arg)
4960 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4961 With prefix argument ARG, kill that many lines from point.
4962 Negative arguments kill lines backward.
4963 With zero argument, kills the text before point on the current line.
4965 When calling from a program, nil means \"no arg\",
4966 a number counts as a prefix arg.
4968 To kill a whole line, when point is not at the beginning, type \
4969 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4971 If `show-trailing-whitespace' is non-nil, this command will just
4972 kill the rest of the current line, even if there are no nonblanks
4973 there.
4975 If option `kill-whole-line' is non-nil, then this command kills the whole line
4976 including its terminating newline, when used at the beginning of a line
4977 with no argument. As a consequence, you can always kill a whole line
4978 by typing \\[move-beginning-of-line] \\[kill-line].
4980 If you want to append the killed line to the last killed text,
4981 use \\[append-next-kill] before \\[kill-line].
4983 If the buffer is read-only, Emacs will beep and refrain from deleting
4984 the line, but put the line in the kill ring anyway. This means that
4985 you can use this command to copy text from a read-only buffer.
4986 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4987 even beep.)"
4988 (interactive "P")
4989 (kill-region (point)
4990 ;; It is better to move point to the other end of the kill
4991 ;; before killing. That way, in a read-only buffer, point
4992 ;; moves across the text that is copied to the kill ring.
4993 ;; The choice has no effect on undo now that undo records
4994 ;; the value of point from before the command was run.
4995 (progn
4996 (if arg
4997 (forward-visible-line (prefix-numeric-value arg))
4998 (if (eobp)
4999 (signal 'end-of-buffer nil))
5000 (let ((end
5001 (save-excursion
5002 (end-of-visible-line) (point))))
5003 (if (or (save-excursion
5004 ;; If trailing whitespace is visible,
5005 ;; don't treat it as nothing.
5006 (unless show-trailing-whitespace
5007 (skip-chars-forward " \t" end))
5008 (= (point) end))
5009 (and kill-whole-line (bolp)))
5010 (forward-visible-line 1)
5011 (goto-char end))))
5012 (point))))
5014 (defun kill-whole-line (&optional arg)
5015 "Kill current line.
5016 With prefix ARG, kill that many lines starting from the current line.
5017 If ARG is negative, kill backward. Also kill the preceding newline.
5018 \(This is meant to make \\[repeat] work well with negative arguments.)
5019 If ARG is zero, kill current line but exclude the trailing newline."
5020 (interactive "p")
5021 (or arg (setq arg 1))
5022 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
5023 (signal 'end-of-buffer nil))
5024 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
5025 (signal 'beginning-of-buffer nil))
5026 (unless (eq last-command 'kill-region)
5027 (kill-new "")
5028 (setq last-command 'kill-region))
5029 (cond ((zerop arg)
5030 ;; We need to kill in two steps, because the previous command
5031 ;; could have been a kill command, in which case the text
5032 ;; before point needs to be prepended to the current kill
5033 ;; ring entry and the text after point appended. Also, we
5034 ;; need to use save-excursion to avoid copying the same text
5035 ;; twice to the kill ring in read-only buffers.
5036 (save-excursion
5037 (kill-region (point) (progn (forward-visible-line 0) (point))))
5038 (kill-region (point) (progn (end-of-visible-line) (point))))
5039 ((< arg 0)
5040 (save-excursion
5041 (kill-region (point) (progn (end-of-visible-line) (point))))
5042 (kill-region (point)
5043 (progn (forward-visible-line (1+ arg))
5044 (unless (bobp) (backward-char))
5045 (point))))
5047 (save-excursion
5048 (kill-region (point) (progn (forward-visible-line 0) (point))))
5049 (kill-region (point)
5050 (progn (forward-visible-line arg) (point))))))
5052 (defun forward-visible-line (arg)
5053 "Move forward by ARG lines, ignoring currently invisible newlines only.
5054 If ARG is negative, move backward -ARG lines.
5055 If ARG is zero, move to the beginning of the current line."
5056 (condition-case nil
5057 (if (> arg 0)
5058 (progn
5059 (while (> arg 0)
5060 (or (zerop (forward-line 1))
5061 (signal 'end-of-buffer nil))
5062 ;; If the newline we just skipped is invisible,
5063 ;; don't count it.
5064 (let ((prop
5065 (get-char-property (1- (point)) 'invisible)))
5066 (if (if (eq buffer-invisibility-spec t)
5067 prop
5068 (or (memq prop buffer-invisibility-spec)
5069 (assq prop buffer-invisibility-spec)))
5070 (setq arg (1+ arg))))
5071 (setq arg (1- arg)))
5072 ;; If invisible text follows, and it is a number of complete lines,
5073 ;; skip it.
5074 (let ((opoint (point)))
5075 (while (and (not (eobp))
5076 (let ((prop
5077 (get-char-property (point) 'invisible)))
5078 (if (eq buffer-invisibility-spec t)
5079 prop
5080 (or (memq prop buffer-invisibility-spec)
5081 (assq prop buffer-invisibility-spec)))))
5082 (goto-char
5083 (if (get-text-property (point) 'invisible)
5084 (or (next-single-property-change (point) 'invisible)
5085 (point-max))
5086 (next-overlay-change (point)))))
5087 (unless (bolp)
5088 (goto-char opoint))))
5089 (let ((first t))
5090 (while (or first (<= arg 0))
5091 (if first
5092 (beginning-of-line)
5093 (or (zerop (forward-line -1))
5094 (signal 'beginning-of-buffer nil)))
5095 ;; If the newline we just moved to is invisible,
5096 ;; don't count it.
5097 (unless (bobp)
5098 (let ((prop
5099 (get-char-property (1- (point)) 'invisible)))
5100 (unless (if (eq buffer-invisibility-spec t)
5101 prop
5102 (or (memq prop buffer-invisibility-spec)
5103 (assq prop buffer-invisibility-spec)))
5104 (setq arg (1+ arg)))))
5105 (setq first nil))
5106 ;; If invisible text follows, and it is a number of complete lines,
5107 ;; skip it.
5108 (let ((opoint (point)))
5109 (while (and (not (bobp))
5110 (let ((prop
5111 (get-char-property (1- (point)) 'invisible)))
5112 (if (eq buffer-invisibility-spec t)
5113 prop
5114 (or (memq prop buffer-invisibility-spec)
5115 (assq prop buffer-invisibility-spec)))))
5116 (goto-char
5117 (if (get-text-property (1- (point)) 'invisible)
5118 (or (previous-single-property-change (point) 'invisible)
5119 (point-min))
5120 (previous-overlay-change (point)))))
5121 (unless (bolp)
5122 (goto-char opoint)))))
5123 ((beginning-of-buffer end-of-buffer)
5124 nil)))
5126 (defun end-of-visible-line ()
5127 "Move to end of current visible line."
5128 (end-of-line)
5129 ;; If the following character is currently invisible,
5130 ;; skip all characters with that same `invisible' property value,
5131 ;; then find the next newline.
5132 (while (and (not (eobp))
5133 (save-excursion
5134 (skip-chars-forward "^\n")
5135 (let ((prop
5136 (get-char-property (point) 'invisible)))
5137 (if (eq buffer-invisibility-spec t)
5138 prop
5139 (or (memq prop buffer-invisibility-spec)
5140 (assq prop buffer-invisibility-spec))))))
5141 (skip-chars-forward "^\n")
5142 (if (get-text-property (point) 'invisible)
5143 (goto-char (or (next-single-property-change (point) 'invisible)
5144 (point-max)))
5145 (goto-char (next-overlay-change (point))))
5146 (end-of-line)))
5148 (defun insert-buffer (buffer)
5149 "Insert after point the contents of BUFFER.
5150 Puts mark after the inserted text.
5151 BUFFER may be a buffer or a buffer name."
5152 (declare (interactive-only insert-buffer-substring))
5153 (interactive
5154 (list
5155 (progn
5156 (barf-if-buffer-read-only)
5157 (read-buffer "Insert buffer: "
5158 (if (eq (selected-window) (next-window))
5159 (other-buffer (current-buffer))
5160 (window-buffer (next-window)))
5161 t))))
5162 (push-mark
5163 (save-excursion
5164 (insert-buffer-substring (get-buffer buffer))
5165 (point)))
5166 nil)
5168 (defun append-to-buffer (buffer start end)
5169 "Append to specified buffer the text of the region.
5170 It is inserted into that buffer before its point.
5172 When calling from a program, give three arguments:
5173 BUFFER (or buffer name), START and END.
5174 START and END specify the portion of the current buffer to be copied."
5175 (interactive
5176 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5177 (region-beginning) (region-end)))
5178 (let* ((oldbuf (current-buffer))
5179 (append-to (get-buffer-create buffer))
5180 (windows (get-buffer-window-list append-to t t))
5181 point)
5182 (save-excursion
5183 (with-current-buffer append-to
5184 (setq point (point))
5185 (barf-if-buffer-read-only)
5186 (insert-buffer-substring oldbuf start end)
5187 (dolist (window windows)
5188 (when (= (window-point window) point)
5189 (set-window-point window (point))))))))
5191 (defun prepend-to-buffer (buffer start end)
5192 "Prepend to specified buffer the text of the region.
5193 It is inserted into that buffer after its point.
5195 When calling from a program, give three arguments:
5196 BUFFER (or buffer name), START and END.
5197 START and END specify the portion of the current buffer to be copied."
5198 (interactive "BPrepend to buffer: \nr")
5199 (let ((oldbuf (current-buffer)))
5200 (with-current-buffer (get-buffer-create buffer)
5201 (barf-if-buffer-read-only)
5202 (save-excursion
5203 (insert-buffer-substring oldbuf start end)))))
5205 (defun copy-to-buffer (buffer start end)
5206 "Copy to specified buffer the text of the region.
5207 It is inserted into that buffer, replacing existing text there.
5209 When calling from a program, give three arguments:
5210 BUFFER (or buffer name), START and END.
5211 START and END specify the portion of the current buffer to be copied."
5212 (interactive "BCopy to buffer: \nr")
5213 (let ((oldbuf (current-buffer)))
5214 (with-current-buffer (get-buffer-create buffer)
5215 (barf-if-buffer-read-only)
5216 (erase-buffer)
5217 (save-excursion
5218 (insert-buffer-substring oldbuf start end)))))
5220 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5222 (defvar activate-mark-hook nil
5223 "Hook run when the mark becomes active.
5224 It is also run at the end of a command, if the mark is active and
5225 it is possible that the region may have changed.")
5227 (defvar deactivate-mark-hook nil
5228 "Hook run when the mark becomes inactive.")
5230 (defun mark (&optional force)
5231 "Return this buffer's mark value as integer, or nil if never set.
5233 In Transient Mark mode, this function signals an error if
5234 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5235 or the argument FORCE is non-nil, it disregards whether the mark
5236 is active, and returns an integer or nil in the usual way.
5238 If you are using this in an editing command, you are most likely making
5239 a mistake; see the documentation of `set-mark'."
5240 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5241 (marker-position (mark-marker))
5242 (signal 'mark-inactive nil)))
5244 ;; Behind display-selections-p.
5246 (defun deactivate-mark (&optional force)
5247 "Deactivate the mark.
5248 If Transient Mark mode is disabled, this function normally does
5249 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5251 Deactivating the mark sets `mark-active' to nil, updates the
5252 primary selection according to `select-active-regions', and runs
5253 `deactivate-mark-hook'.
5255 If Transient Mark mode was temporarily enabled, reset the value
5256 of the variable `transient-mark-mode'; if this causes Transient
5257 Mark mode to be disabled, don't change `mark-active' to nil or
5258 run `deactivate-mark-hook'."
5259 (when (or (region-active-p) force)
5260 (when (and (if (eq select-active-regions 'only)
5261 (eq (car-safe transient-mark-mode) 'only)
5262 select-active-regions)
5263 (region-active-p)
5264 (display-selections-p))
5265 ;; The var `saved-region-selection', if non-nil, is the text in
5266 ;; the region prior to the last command modifying the buffer.
5267 ;; Set the selection to that, or to the current region.
5268 (cond (saved-region-selection
5269 (if (gui-backend-selection-owner-p 'PRIMARY)
5270 (gui-set-selection 'PRIMARY saved-region-selection))
5271 (setq saved-region-selection nil))
5272 ;; If another program has acquired the selection, region
5273 ;; deactivation should not clobber it (Bug#11772).
5274 ((and (/= (region-beginning) (region-end))
5275 (or (gui-backend-selection-owner-p 'PRIMARY)
5276 (null (gui-backend-selection-exists-p 'PRIMARY))))
5277 (gui-set-selection 'PRIMARY
5278 (funcall region-extract-function nil)))))
5279 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5280 (cond
5281 ((eq (car-safe transient-mark-mode) 'only)
5282 (setq transient-mark-mode (cdr transient-mark-mode))
5283 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5284 (kill-local-variable 'transient-mark-mode)))
5285 ((eq transient-mark-mode 'lambda)
5286 (kill-local-variable 'transient-mark-mode)))
5287 (setq mark-active nil)
5288 (run-hooks 'deactivate-mark-hook)
5289 (redisplay--update-region-highlight (selected-window))))
5291 (defun activate-mark (&optional no-tmm)
5292 "Activate the mark.
5293 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5294 (when (mark t)
5295 (unless (region-active-p)
5296 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5297 (setq mark-active t)
5298 (unless (or transient-mark-mode no-tmm)
5299 (setq-local transient-mark-mode 'lambda))
5300 (run-hooks 'activate-mark-hook))))
5302 (defun set-mark (pos)
5303 "Set this buffer's mark to POS. Don't use this function!
5304 That is to say, don't use this function unless you want
5305 the user to see that the mark has moved, and you want the previous
5306 mark position to be lost.
5308 Normally, when a new mark is set, the old one should go on the stack.
5309 This is why most applications should use `push-mark', not `set-mark'.
5311 Novice Emacs Lisp programmers often try to use the mark for the wrong
5312 purposes. The mark saves a location for the user's convenience.
5313 Most editing commands should not alter the mark.
5314 To remember a location for internal use in the Lisp program,
5315 store it in a Lisp variable. Example:
5317 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5318 (if pos
5319 (progn
5320 (set-marker (mark-marker) pos (current-buffer))
5321 (activate-mark 'no-tmm))
5322 ;; Normally we never clear mark-active except in Transient Mark mode.
5323 ;; But when we actually clear out the mark value too, we must
5324 ;; clear mark-active in any mode.
5325 (deactivate-mark t)
5326 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5327 ;; it should never be nil if the mark is nil.
5328 (setq mark-active nil)
5329 (set-marker (mark-marker) nil)))
5331 (defun save-mark-and-excursion--save ()
5332 (cons
5333 (let ((mark (mark-marker)))
5334 (and (marker-position mark) (copy-marker mark)))
5335 mark-active))
5337 (defun save-mark-and-excursion--restore (saved-mark-info)
5338 (let ((saved-mark (car saved-mark-info))
5339 (omark (marker-position (mark-marker)))
5340 (nmark nil)
5341 (saved-mark-active (cdr saved-mark-info)))
5342 ;; Mark marker
5343 (if (null saved-mark)
5344 (set-marker (mark-marker) nil)
5345 (setf nmark (marker-position saved-mark))
5346 (set-marker (mark-marker) nmark)
5347 (set-marker saved-mark nil))
5348 ;; Mark active
5349 (let ((cur-mark-active mark-active))
5350 (setq mark-active saved-mark-active)
5351 ;; If mark is active now, and either was not active or was at a
5352 ;; different place, run the activate hook.
5353 (if saved-mark-active
5354 (when (or (not cur-mark-active)
5355 (not (eq omark nmark)))
5356 (run-hooks 'activate-mark-hook))
5357 ;; If mark has ceased to be active, run deactivate hook.
5358 (when cur-mark-active
5359 (run-hooks 'deactivate-mark-hook))))))
5361 (defmacro save-mark-and-excursion (&rest body)
5362 "Like `save-excursion', but also save and restore the mark state.
5363 This macro does what `save-excursion' did before Emacs 25.1."
5364 (declare (indent 0) (debug t))
5365 (let ((saved-marker-sym (make-symbol "saved-marker")))
5366 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5367 (unwind-protect
5368 (save-excursion ,@body)
5369 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5371 (defcustom use-empty-active-region nil
5372 "Whether \"region-aware\" commands should act on empty regions.
5373 If nil, region-aware commands treat the empty region as inactive.
5374 If non-nil, region-aware commands treat the region as active as
5375 long as the mark is active, even if the region is empty.
5377 Region-aware commands are those that act on the region if it is
5378 active and Transient Mark mode is enabled, and on the text near
5379 point otherwise."
5380 :type 'boolean
5381 :version "23.1"
5382 :group 'editing-basics)
5384 (defun use-region-p ()
5385 "Return t if the region is active and it is appropriate to act on it.
5386 This is used by commands that act specially on the region under
5387 Transient Mark mode.
5389 The return value is t if Transient Mark mode is enabled and the
5390 mark is active; furthermore, if `use-empty-active-region' is nil,
5391 the region must not be empty. Otherwise, the return value is nil.
5393 For some commands, it may be appropriate to ignore the value of
5394 `use-empty-active-region'; in that case, use `region-active-p'."
5395 (and (region-active-p)
5396 (or use-empty-active-region (> (region-end) (region-beginning)))))
5398 (defun region-active-p ()
5399 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5401 Some commands act specially on the region when Transient Mark
5402 mode is enabled. Usually, such commands should use
5403 `use-region-p' instead of this function, because `use-region-p'
5404 also checks the value of `use-empty-active-region'."
5405 (and transient-mark-mode mark-active
5406 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5407 ;; without the mark being set (e.g. bug#17324). We really should fix
5408 ;; that problem, but in the mean time, let's make sure we don't say the
5409 ;; region is active when there's no mark.
5410 (progn (cl-assert (mark)) t)))
5412 (defun region-noncontiguous-p ()
5413 "Return non-nil if the region contains several pieces.
5414 An example is a rectangular region handled as a list of
5415 separate contiguous regions for each line."
5416 (> (length (funcall region-extract-function 'bounds)) 1))
5418 (defvar redisplay-unhighlight-region-function
5419 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5421 (defvar redisplay-highlight-region-function
5422 (lambda (start end window rol)
5423 (if (not (overlayp rol))
5424 (let ((nrol (make-overlay start end)))
5425 (funcall redisplay-unhighlight-region-function rol)
5426 (overlay-put nrol 'window window)
5427 (overlay-put nrol 'face 'region)
5428 ;; Normal priority so that a large region doesn't hide all the
5429 ;; overlays within it, but high secondary priority so that if it
5430 ;; ends/starts in the middle of a small overlay, that small overlay
5431 ;; won't hide the region's boundaries.
5432 (overlay-put nrol 'priority '(nil . 100))
5433 nrol)
5434 (unless (and (eq (overlay-buffer rol) (current-buffer))
5435 (eq (overlay-start rol) start)
5436 (eq (overlay-end rol) end))
5437 (move-overlay rol start end (current-buffer)))
5438 rol)))
5440 (defun redisplay--update-region-highlight (window)
5441 (let ((rol (window-parameter window 'internal-region-overlay)))
5442 (if (not (and (region-active-p)
5443 (or highlight-nonselected-windows
5444 (eq window (selected-window))
5445 (and (window-minibuffer-p)
5446 (eq window (minibuffer-selected-window))))))
5447 (funcall redisplay-unhighlight-region-function rol)
5448 (let* ((pt (window-point window))
5449 (mark (mark))
5450 (start (min pt mark))
5451 (end (max pt mark))
5452 (new
5453 (funcall redisplay-highlight-region-function
5454 start end window rol)))
5455 (unless (equal new rol)
5456 (set-window-parameter window 'internal-region-overlay
5457 new))))))
5459 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5460 "Hook run just before redisplay.
5461 It is called in each window that is to be redisplayed. It takes one argument,
5462 which is the window that will be redisplayed. When run, the `current-buffer'
5463 is set to the buffer displayed in that window.")
5465 (defun redisplay--pre-redisplay-functions (windows)
5466 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5467 (if (null windows)
5468 (with-current-buffer (window-buffer (selected-window))
5469 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5470 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5471 (with-current-buffer (window-buffer win)
5472 (run-hook-with-args 'pre-redisplay-functions win))))))
5474 (add-function :before pre-redisplay-function
5475 #'redisplay--pre-redisplay-functions)
5478 (defvar-local mark-ring nil
5479 "The list of former marks of the current buffer, most recent first.")
5480 (put 'mark-ring 'permanent-local t)
5482 (defcustom mark-ring-max 16
5483 "Maximum size of mark ring. Start discarding off end if gets this big."
5484 :type 'integer
5485 :group 'editing-basics)
5487 (defvar global-mark-ring nil
5488 "The list of saved global marks, most recent first.")
5490 (defcustom global-mark-ring-max 16
5491 "Maximum size of global mark ring. \
5492 Start discarding off end if gets this big."
5493 :type 'integer
5494 :group 'editing-basics)
5496 (defun pop-to-mark-command ()
5497 "Jump to mark, and pop a new position for mark off the ring.
5498 \(Does not affect global mark ring)."
5499 (interactive)
5500 (if (null (mark t))
5501 (user-error "No mark set in this buffer")
5502 (if (= (point) (mark t))
5503 (message "Mark popped"))
5504 (goto-char (mark t))
5505 (pop-mark)))
5507 (defun push-mark-command (arg &optional nomsg)
5508 "Set mark at where point is.
5509 If no prefix ARG and mark is already set there, just activate it.
5510 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5511 (interactive "P")
5512 (let ((mark (mark t)))
5513 (if (or arg (null mark) (/= mark (point)))
5514 (push-mark nil nomsg t)
5515 (activate-mark 'no-tmm)
5516 (unless nomsg
5517 (message "Mark activated")))))
5519 (defcustom set-mark-command-repeat-pop nil
5520 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5521 That means that C-u \\[set-mark-command] \\[set-mark-command]
5522 will pop the mark twice, and
5523 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5524 will pop the mark three times.
5526 A value of nil means \\[set-mark-command]'s behavior does not change
5527 after C-u \\[set-mark-command]."
5528 :type 'boolean
5529 :group 'editing-basics)
5531 (defun set-mark-command (arg)
5532 "Set the mark where point is, and activate it; or jump to the mark.
5533 Setting the mark also alters the region, which is the text
5534 between point and mark; this is the closest equivalent in
5535 Emacs to what some editors call the \"selection\".
5537 With no prefix argument, set the mark at point, and push the
5538 old mark position on local mark ring. Also push the new mark on
5539 global mark ring, if the previous mark was set in another buffer.
5541 When Transient Mark Mode is off, immediately repeating this
5542 command activates `transient-mark-mode' temporarily.
5544 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5545 jump to the mark, and set the mark from
5546 position popped off the local mark ring (this does not affect the global
5547 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5548 mark ring (see `pop-global-mark').
5550 If `set-mark-command-repeat-pop' is non-nil, repeating
5551 the \\[set-mark-command] command with no prefix argument pops the next position
5552 off the local (or global) mark ring and jumps there.
5554 With \\[universal-argument] \\[universal-argument] as prefix
5555 argument, unconditionally set mark where point is, even if
5556 `set-mark-command-repeat-pop' is non-nil.
5558 Novice Emacs Lisp programmers often try to use the mark for the wrong
5559 purposes. See the documentation of `set-mark' for more information."
5560 (interactive "P")
5561 (cond ((eq transient-mark-mode 'lambda)
5562 (kill-local-variable 'transient-mark-mode))
5563 ((eq (car-safe transient-mark-mode) 'only)
5564 (deactivate-mark)))
5565 (cond
5566 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5567 (push-mark-command nil))
5568 ((not (eq this-command 'set-mark-command))
5569 (if arg
5570 (pop-to-mark-command)
5571 (push-mark-command t)))
5572 ((and set-mark-command-repeat-pop
5573 (eq last-command 'pop-global-mark)
5574 (not arg))
5575 (setq this-command 'pop-global-mark)
5576 (pop-global-mark))
5577 ((or (and set-mark-command-repeat-pop
5578 (eq last-command 'pop-to-mark-command))
5579 arg)
5580 (setq this-command 'pop-to-mark-command)
5581 (pop-to-mark-command))
5582 ((eq last-command 'set-mark-command)
5583 (if (region-active-p)
5584 (progn
5585 (deactivate-mark)
5586 (message "Mark deactivated"))
5587 (activate-mark)
5588 (message "Mark activated")))
5590 (push-mark-command nil))))
5592 (defun push-mark (&optional location nomsg activate)
5593 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5594 If the last global mark pushed was not in the current buffer,
5595 also push LOCATION on the global mark ring.
5596 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5598 Novice Emacs Lisp programmers often try to use the mark for the wrong
5599 purposes. See the documentation of `set-mark' for more information.
5601 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5602 (unless (null (mark t))
5603 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5604 (when (> (length mark-ring) mark-ring-max)
5605 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5606 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5607 (set-marker (mark-marker) (or location (point)) (current-buffer))
5608 ;; Now push the mark on the global mark ring.
5609 (if (and global-mark-ring
5610 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5611 ;; The last global mark pushed was in this same buffer.
5612 ;; Don't push another one.
5614 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5615 (when (> (length global-mark-ring) global-mark-ring-max)
5616 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5617 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5618 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5619 (message "Mark set"))
5620 (if (or activate (not transient-mark-mode))
5621 (set-mark (mark t)))
5622 nil)
5624 (defun pop-mark ()
5625 "Pop off mark ring into the buffer's actual mark.
5626 Does not set point. Does nothing if mark ring is empty."
5627 (when mark-ring
5628 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5629 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5630 (move-marker (car mark-ring) nil)
5631 (if (null (mark t)) (ding))
5632 (setq mark-ring (cdr mark-ring)))
5633 (deactivate-mark))
5635 (define-obsolete-function-alias
5636 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5637 (defun exchange-point-and-mark (&optional arg)
5638 "Put the mark where point is now, and point where the mark is now.
5639 This command works even when the mark is not active,
5640 and it reactivates the mark.
5642 If Transient Mark mode is on, a prefix ARG deactivates the mark
5643 if it is active, and otherwise avoids reactivating it. If
5644 Transient Mark mode is off, a prefix ARG enables Transient Mark
5645 mode temporarily."
5646 (interactive "P")
5647 (let ((omark (mark t))
5648 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5649 (if (null omark)
5650 (user-error "No mark set in this buffer"))
5651 (set-mark (point))
5652 (goto-char omark)
5653 (cond (temp-highlight
5654 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5655 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5656 (not (or arg (region-active-p))))
5657 (deactivate-mark))
5658 (t (activate-mark)))
5659 nil))
5661 (defcustom shift-select-mode t
5662 "When non-nil, shifted motion keys activate the mark momentarily.
5664 While the mark is activated in this way, any shift-translated point
5665 motion key extends the region, and if Transient Mark mode was off, it
5666 is temporarily turned on. Furthermore, the mark will be deactivated
5667 by any subsequent point motion key that was not shift-translated, or
5668 by any action that normally deactivates the mark in Transient Mark mode.
5670 See `this-command-keys-shift-translated' for the meaning of
5671 shift-translation."
5672 :type 'boolean
5673 :group 'editing-basics)
5675 (defun handle-shift-selection ()
5676 "Activate/deactivate mark depending on invocation thru shift translation.
5677 This function is called by `call-interactively' when a command
5678 with a `^' character in its `interactive' spec is invoked, before
5679 running the command itself.
5681 If `shift-select-mode' is enabled and the command was invoked
5682 through shift translation, set the mark and activate the region
5683 temporarily, unless it was already set in this way. See
5684 `this-command-keys-shift-translated' for the meaning of shift
5685 translation.
5687 Otherwise, if the region has been activated temporarily,
5688 deactivate it, and restore the variable `transient-mark-mode' to
5689 its earlier value."
5690 (cond ((and shift-select-mode this-command-keys-shift-translated)
5691 (unless (and mark-active
5692 (eq (car-safe transient-mark-mode) 'only))
5693 (setq-local transient-mark-mode
5694 (cons 'only
5695 (unless (eq transient-mark-mode 'lambda)
5696 transient-mark-mode)))
5697 (push-mark nil nil t)))
5698 ((eq (car-safe transient-mark-mode) 'only)
5699 (setq transient-mark-mode (cdr transient-mark-mode))
5700 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5701 (kill-local-variable 'transient-mark-mode))
5702 (deactivate-mark))))
5704 (define-minor-mode transient-mark-mode
5705 "Toggle Transient Mark mode.
5706 With a prefix argument ARG, enable Transient Mark mode if ARG is
5707 positive, and disable it otherwise. If called from Lisp, enable
5708 Transient Mark mode if ARG is omitted or nil.
5710 Transient Mark mode is a global minor mode. When enabled, the
5711 region is highlighted with the `region' face whenever the mark
5712 is active. The mark is \"deactivated\" by changing the buffer,
5713 and after certain other operations that set the mark but whose
5714 main purpose is something else--for example, incremental search,
5715 \\[beginning-of-buffer], and \\[end-of-buffer].
5717 You can also deactivate the mark by typing \\[keyboard-quit] or
5718 \\[keyboard-escape-quit].
5720 Many commands change their behavior when Transient Mark mode is
5721 in effect and the mark is active, by acting on the region instead
5722 of their usual default part of the buffer's text. Examples of
5723 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5724 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5725 To see the documentation of commands which are sensitive to the
5726 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5727 or \"mark.*active\" at the prompt."
5728 :global t
5729 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5730 :variable (default-value 'transient-mark-mode))
5732 (defvar widen-automatically t
5733 "Non-nil means it is ok for commands to call `widen' when they want to.
5734 Some commands will do this in order to go to positions outside
5735 the current accessible part of the buffer.
5737 If `widen-automatically' is nil, these commands will do something else
5738 as a fallback, and won't change the buffer bounds.")
5740 (defvar non-essential nil
5741 "Whether the currently executing code is performing an essential task.
5742 This variable should be non-nil only when running code which should not
5743 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5744 user for a password when we are simply scanning a set of files in the
5745 background or displaying possible completions before the user even asked
5746 for it.")
5748 (defun pop-global-mark ()
5749 "Pop off global mark ring and jump to the top location."
5750 (interactive)
5751 ;; Pop entries which refer to non-existent buffers.
5752 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5753 (setq global-mark-ring (cdr global-mark-ring)))
5754 (or global-mark-ring
5755 (error "No global mark set"))
5756 (let* ((marker (car global-mark-ring))
5757 (buffer (marker-buffer marker))
5758 (position (marker-position marker)))
5759 (setq global-mark-ring (nconc (cdr global-mark-ring)
5760 (list (car global-mark-ring))))
5761 (set-buffer buffer)
5762 (or (and (>= position (point-min))
5763 (<= position (point-max)))
5764 (if widen-automatically
5765 (widen)
5766 (error "Global mark position is outside accessible part of buffer")))
5767 (goto-char position)
5768 (switch-to-buffer buffer)))
5770 (defcustom next-line-add-newlines nil
5771 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5772 :type 'boolean
5773 :version "21.1"
5774 :group 'editing-basics)
5776 (defun next-line (&optional arg try-vscroll)
5777 "Move cursor vertically down ARG lines.
5778 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5779 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5780 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5781 function will not vscroll.
5783 ARG defaults to 1.
5785 If there is no character in the target line exactly under the current column,
5786 the cursor is positioned after the character in that line which spans this
5787 column, or at the end of the line if it is not long enough.
5788 If there is no line in the buffer after this one, behavior depends on the
5789 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5790 to create a line, and moves the cursor to that line. Otherwise it moves the
5791 cursor to the end of the buffer.
5793 If the variable `line-move-visual' is non-nil, this command moves
5794 by display lines. Otherwise, it moves by buffer lines, without
5795 taking variable-width characters or continued lines into account.
5796 See \\[next-logical-line] for a command that always moves by buffer lines.
5798 The command \\[set-goal-column] can be used to create
5799 a semipermanent goal column for this command.
5800 Then instead of trying to move exactly vertically (or as close as possible),
5801 this command moves to the specified goal column (or as close as possible).
5802 The goal column is stored in the variable `goal-column', which is nil
5803 when there is no goal column. Note that setting `goal-column'
5804 overrides `line-move-visual' and causes this command to move by buffer
5805 lines rather than by display lines."
5806 (declare (interactive-only forward-line))
5807 (interactive "^p\np")
5808 (or arg (setq arg 1))
5809 (if (and next-line-add-newlines (= arg 1))
5810 (if (save-excursion (end-of-line) (eobp))
5811 ;; When adding a newline, don't expand an abbrev.
5812 (let ((abbrev-mode nil))
5813 (end-of-line)
5814 (insert (if use-hard-newlines hard-newline "\n")))
5815 (line-move arg nil nil try-vscroll))
5816 (if (called-interactively-p 'interactive)
5817 (condition-case err
5818 (line-move arg nil nil try-vscroll)
5819 ((beginning-of-buffer end-of-buffer)
5820 (signal (car err) (cdr err))))
5821 (line-move arg nil nil try-vscroll)))
5822 nil)
5824 (defun previous-line (&optional arg try-vscroll)
5825 "Move cursor vertically up ARG lines.
5826 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5827 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5828 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5829 function will not vscroll.
5831 ARG defaults to 1.
5833 If there is no character in the target line exactly over the current column,
5834 the cursor is positioned after the character in that line which spans this
5835 column, or at the end of the line if it is not long enough.
5837 If the variable `line-move-visual' is non-nil, this command moves
5838 by display lines. Otherwise, it moves by buffer lines, without
5839 taking variable-width characters or continued lines into account.
5840 See \\[previous-logical-line] for a command that always moves by buffer lines.
5842 The command \\[set-goal-column] can be used to create
5843 a semipermanent goal column for this command.
5844 Then instead of trying to move exactly vertically (or as close as possible),
5845 this command moves to the specified goal column (or as close as possible).
5846 The goal column is stored in the variable `goal-column', which is nil
5847 when there is no goal column. Note that setting `goal-column'
5848 overrides `line-move-visual' and causes this command to move by buffer
5849 lines rather than by display lines."
5850 (declare (interactive-only
5851 "use `forward-line' with negative argument instead."))
5852 (interactive "^p\np")
5853 (or arg (setq arg 1))
5854 (if (called-interactively-p 'interactive)
5855 (condition-case err
5856 (line-move (- arg) nil nil try-vscroll)
5857 ((beginning-of-buffer end-of-buffer)
5858 (signal (car err) (cdr err))))
5859 (line-move (- arg) nil nil try-vscroll))
5860 nil)
5862 (defcustom track-eol nil
5863 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5864 This means moving to the end of each line moved onto.
5865 The beginning of a blank line does not count as the end of a line.
5866 This has no effect when the variable `line-move-visual' is non-nil."
5867 :type 'boolean
5868 :group 'editing-basics)
5870 (defcustom goal-column nil
5871 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5872 A non-nil setting overrides the variable `line-move-visual', which see."
5873 :type '(choice integer
5874 (const :tag "None" nil))
5875 :group 'editing-basics)
5876 (make-variable-buffer-local 'goal-column)
5878 (defvar temporary-goal-column 0
5879 "Current goal column for vertical motion.
5880 It is the column where point was at the start of the current run
5881 of vertical motion commands.
5883 When moving by visual lines via the function `line-move-visual', it is a cons
5884 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5885 divided by the default column width, and HSCROLL is the number of
5886 columns by which window is scrolled from left margin.
5888 When the `track-eol' feature is doing its job, the value is
5889 `most-positive-fixnum'.")
5891 (defcustom line-move-ignore-invisible t
5892 "Non-nil means commands that move by lines ignore invisible newlines.
5893 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5894 as if newlines that are invisible didn't exist, and count
5895 only visible newlines. Thus, moving across across 2 newlines
5896 one of which is invisible will be counted as a one-line move.
5897 Also, a non-nil value causes invisible text to be ignored when
5898 counting columns for the purposes of keeping point in the same
5899 column by \\[next-line] and \\[previous-line].
5901 Outline mode sets this."
5902 :type 'boolean
5903 :group 'editing-basics)
5905 (defcustom line-move-visual t
5906 "When non-nil, `line-move' moves point by visual lines.
5907 This movement is based on where the cursor is displayed on the
5908 screen, instead of relying on buffer contents alone. It takes
5909 into account variable-width characters and line continuation.
5910 If nil, `line-move' moves point by logical lines.
5911 A non-nil setting of `goal-column' overrides the value of this variable
5912 and forces movement by logical lines.
5913 A window that is horizontally scrolled also forces movement by logical
5914 lines."
5915 :type 'boolean
5916 :group 'editing-basics
5917 :version "23.1")
5919 ;; Only used if display-graphic-p.
5920 (declare-function font-info "font.c" (name &optional frame))
5922 (defun default-font-height ()
5923 "Return the height in pixels of the current buffer's default face font.
5925 If the default font is remapped (see `face-remapping-alist'), the
5926 function returns the height of the remapped face."
5927 (let ((default-font (face-font 'default)))
5928 (cond
5929 ((and (display-multi-font-p)
5930 ;; Avoid calling font-info if the frame's default font was
5931 ;; not changed since the frame was created. That's because
5932 ;; font-info is expensive for some fonts, see bug #14838.
5933 (not (string= (frame-parameter nil 'font) default-font)))
5934 (aref (font-info default-font) 3))
5935 (t (frame-char-height)))))
5937 (defun default-font-width ()
5938 "Return the width in pixels of the current buffer's default face font.
5940 If the default font is remapped (see `face-remapping-alist'), the
5941 function returns the width of the remapped face."
5942 (let ((default-font (face-font 'default)))
5943 (cond
5944 ((and (display-multi-font-p)
5945 ;; Avoid calling font-info if the frame's default font was
5946 ;; not changed since the frame was created. That's because
5947 ;; font-info is expensive for some fonts, see bug #14838.
5948 (not (string= (frame-parameter nil 'font) default-font)))
5949 (let* ((info (font-info (face-font 'default)))
5950 (width (aref info 11)))
5951 (if (> width 0)
5952 width
5953 (aref info 10))))
5954 (t (frame-char-width)))))
5956 (defun default-line-height ()
5957 "Return the pixel height of current buffer's default-face text line.
5959 The value includes `line-spacing', if any, defined for the buffer
5960 or the frame."
5961 (let ((dfh (default-font-height))
5962 (lsp (if (display-graphic-p)
5963 (or line-spacing
5964 (default-value 'line-spacing)
5965 (frame-parameter nil 'line-spacing)
5967 0)))
5968 (if (floatp lsp)
5969 (setq lsp (truncate (* (frame-char-height) lsp))))
5970 (+ dfh lsp)))
5972 (defun window-screen-lines ()
5973 "Return the number of screen lines in the text area of the selected window.
5975 This is different from `window-text-height' in that this function counts
5976 lines in units of the height of the font used by the default face displayed
5977 in the window, not in units of the frame's default font, and also accounts
5978 for `line-spacing', if any, defined for the window's buffer or frame.
5980 The value is a floating-point number."
5981 (let ((edges (window-inside-pixel-edges))
5982 (dlh (default-line-height)))
5983 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5985 ;; Returns non-nil if partial move was done.
5986 (defun line-move-partial (arg noerror &optional _to-end)
5987 (if (< arg 0)
5988 ;; Move backward (up).
5989 ;; If already vscrolled, reduce vscroll
5990 (let ((vs (window-vscroll nil t))
5991 (dlh (default-line-height)))
5992 (when (> vs dlh)
5993 (set-window-vscroll nil (- vs dlh) t)))
5995 ;; Move forward (down).
5996 (let* ((lh (window-line-height -1))
5997 (rowh (car lh))
5998 (vpos (nth 1 lh))
5999 (ypos (nth 2 lh))
6000 (rbot (nth 3 lh))
6001 (this-lh (window-line-height))
6002 (this-height (car this-lh))
6003 (this-ypos (nth 2 this-lh))
6004 (dlh (default-line-height))
6005 (wslines (window-screen-lines))
6006 (edges (window-inside-pixel-edges))
6007 (winh (- (nth 3 edges) (nth 1 edges) 1))
6008 py vs last-line)
6009 (if (> (mod wslines 1.0) 0.0)
6010 (setq wslines (round (+ wslines 0.5))))
6011 (when (or (null lh)
6012 (>= rbot dlh)
6013 (<= ypos (- dlh))
6014 (null this-lh)
6015 (<= this-ypos (- dlh)))
6016 (unless lh
6017 (let ((wend (pos-visible-in-window-p t nil t)))
6018 (setq rbot (nth 3 wend)
6019 rowh (nth 4 wend)
6020 vpos (nth 5 wend))))
6021 (unless this-lh
6022 (let ((wstart (pos-visible-in-window-p nil nil t)))
6023 (setq this-ypos (nth 2 wstart)
6024 this-height (nth 4 wstart))))
6025 (setq py
6026 (or (nth 1 this-lh)
6027 (let ((ppos (posn-at-point))
6028 col-row)
6029 (setq col-row (posn-actual-col-row ppos))
6030 (if col-row
6031 (- (cdr col-row) (window-vscroll))
6032 (cdr (posn-col-row ppos))))))
6033 ;; VPOS > 0 means the last line is only partially visible.
6034 ;; But if the part that is visible is at least as tall as the
6035 ;; default font, that means the line is actually fully
6036 ;; readable, and something like line-spacing is hidden. So in
6037 ;; that case we accept the last line in the window as still
6038 ;; visible, and consider the margin as starting one line
6039 ;; later.
6040 (if (and vpos (> vpos 0))
6041 (if (and rowh
6042 (>= rowh (default-font-height))
6043 (< rowh dlh))
6044 (setq last-line (min (- wslines scroll-margin) vpos))
6045 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
6046 (cond
6047 ;; If last line of window is fully visible, and vscrolling
6048 ;; more would make this line invisible, move forward.
6049 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
6050 (null this-height)
6051 (<= this-height dlh))
6052 (or (null rbot) (= rbot 0)))
6053 nil)
6054 ;; If cursor is not in the bottom scroll margin, and the
6055 ;; current line is is not too tall, move forward.
6056 ((and (or (null this-height) (<= this-height winh))
6057 vpos
6058 (> vpos 0)
6059 (< py last-line))
6060 nil)
6061 ;; When already vscrolled, we vscroll some more if we can,
6062 ;; or clear vscroll and move forward at end of tall image.
6063 ((> vs 0)
6064 (when (or (and rbot (> rbot 0))
6065 (and this-height (> this-height dlh)))
6066 (set-window-vscroll nil (+ vs dlh) t)))
6067 ;; If cursor just entered the bottom scroll margin, move forward,
6068 ;; but also optionally vscroll one line so redisplay won't recenter.
6069 ((and vpos
6070 (> vpos 0)
6071 (= py last-line))
6072 ;; Don't vscroll if the partially-visible line at window
6073 ;; bottom is not too tall (a.k.a. "just one more text
6074 ;; line"): in that case, we do want redisplay to behave
6075 ;; normally, i.e. recenter or whatever.
6077 ;; Note: ROWH + RBOT from the value returned by
6078 ;; pos-visible-in-window-p give the total height of the
6079 ;; partially-visible glyph row at the end of the window. As
6080 ;; we are dealing with floats, we disregard sub-pixel
6081 ;; discrepancies between that and DLH.
6082 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
6083 (set-window-vscroll nil dlh t))
6084 (line-move-1 arg noerror)
6086 ;; If there are lines above the last line, scroll-up one line.
6087 ((and vpos (> vpos 0))
6088 (scroll-up 1)
6090 ;; Finally, start vscroll.
6092 (set-window-vscroll nil dlh t)))))))
6095 ;; This is like line-move-1 except that it also performs
6096 ;; vertical scrolling of tall images if appropriate.
6097 ;; That is not really a clean thing to do, since it mixes
6098 ;; scrolling with cursor motion. But so far we don't have
6099 ;; a cleaner solution to the problem of making C-n do something
6100 ;; useful given a tall image.
6101 (defun line-move (arg &optional noerror _to-end try-vscroll)
6102 "Move forward ARG lines.
6103 If NOERROR, don't signal an error if we can't move ARG lines.
6104 TO-END is unused.
6105 TRY-VSCROLL controls whether to vscroll tall lines: if either
6106 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
6107 not vscroll."
6108 (if noninteractive
6109 (line-move-1 arg noerror)
6110 (unless (and auto-window-vscroll try-vscroll
6111 ;; Only vscroll for single line moves
6112 (= (abs arg) 1)
6113 ;; Under scroll-conservatively, the display engine
6114 ;; does this better.
6115 (zerop scroll-conservatively)
6116 ;; But don't vscroll in a keyboard macro.
6117 (not defining-kbd-macro)
6118 (not executing-kbd-macro)
6119 (line-move-partial arg noerror))
6120 (set-window-vscroll nil 0 t)
6121 (if (and line-move-visual
6122 ;; Display-based column are incompatible with goal-column.
6123 (not goal-column)
6124 ;; When the text in the window is scrolled to the left,
6125 ;; display-based motion doesn't make sense (because each
6126 ;; logical line occupies exactly one screen line).
6127 (not (> (window-hscroll) 0))
6128 ;; Likewise when the text _was_ scrolled to the left
6129 ;; when the current run of vertical motion commands
6130 ;; started.
6131 (not (and (memq last-command
6132 `(next-line previous-line ,this-command))
6133 auto-hscroll-mode
6134 (numberp temporary-goal-column)
6135 (>= temporary-goal-column
6136 (- (window-width) hscroll-margin)))))
6137 (prog1 (line-move-visual arg noerror)
6138 ;; If we moved into a tall line, set vscroll to make
6139 ;; scrolling through tall images more smooth.
6140 (let ((lh (line-pixel-height))
6141 (edges (window-inside-pixel-edges))
6142 (dlh (default-line-height))
6143 winh)
6144 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
6145 (if (and (< arg 0)
6146 (< (point) (window-start))
6147 (> lh winh))
6148 (set-window-vscroll
6150 (- lh dlh) t))))
6151 (line-move-1 arg noerror)))))
6153 ;; Display-based alternative to line-move-1.
6154 ;; Arg says how many lines to move. The value is t if we can move the
6155 ;; specified number of lines.
6156 (defun line-move-visual (arg &optional noerror)
6157 "Move ARG lines forward.
6158 If NOERROR, don't signal an error if we can't move that many lines."
6159 (let ((opoint (point))
6160 (hscroll (window-hscroll))
6161 target-hscroll)
6162 ;; Check if the previous command was a line-motion command, or if
6163 ;; we were called from some other command.
6164 (if (and (consp temporary-goal-column)
6165 (memq last-command `(next-line previous-line ,this-command)))
6166 ;; If so, there's no need to reset `temporary-goal-column',
6167 ;; but we may need to hscroll.
6168 (if (or (/= (cdr temporary-goal-column) hscroll)
6169 (> (cdr temporary-goal-column) 0))
6170 (setq target-hscroll (cdr temporary-goal-column)))
6171 ;; Otherwise, we should reset `temporary-goal-column'.
6172 (let ((posn (posn-at-point))
6173 x-pos)
6174 (cond
6175 ;; Handle the `overflow-newline-into-fringe' case:
6176 ((eq (nth 1 posn) 'right-fringe)
6177 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
6178 ((car (posn-x-y posn))
6179 (setq x-pos (car (posn-x-y posn)))
6180 ;; In R2L lines, the X pixel coordinate is measured from the
6181 ;; left edge of the window, but columns are still counted
6182 ;; from the logical-order beginning of the line, i.e. from
6183 ;; the right edge in this case. We need to adjust for that.
6184 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6185 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6186 (setq temporary-goal-column
6187 (cons (/ (float x-pos)
6188 (frame-char-width))
6189 hscroll)))
6190 (executing-kbd-macro
6191 ;; When we move beyond the first/last character visible in
6192 ;; the window, posn-at-point will return nil, so we need to
6193 ;; approximate the goal column as below.
6194 (setq temporary-goal-column
6195 (mod (current-column) (window-text-width)))))))
6196 (if target-hscroll
6197 (set-window-hscroll (selected-window) target-hscroll))
6198 ;; vertical-motion can move more than it was asked to if it moves
6199 ;; across display strings with newlines. We don't want to ring
6200 ;; the bell and announce beginning/end of buffer in that case.
6201 (or (and (or (and (>= arg 0)
6202 (>= (vertical-motion
6203 (cons (or goal-column
6204 (if (consp temporary-goal-column)
6205 (car temporary-goal-column)
6206 temporary-goal-column))
6207 arg))
6208 arg))
6209 (and (< arg 0)
6210 (<= (vertical-motion
6211 (cons (or goal-column
6212 (if (consp temporary-goal-column)
6213 (car temporary-goal-column)
6214 temporary-goal-column))
6215 arg))
6216 arg)))
6217 (or (>= arg 0)
6218 (/= (point) opoint)
6219 ;; If the goal column lies on a display string,
6220 ;; `vertical-motion' advances the cursor to the end
6221 ;; of the string. For arg < 0, this can cause the
6222 ;; cursor to get stuck. (Bug#3020).
6223 (= (vertical-motion arg) arg)))
6224 (unless noerror
6225 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6226 nil)))))
6228 ;; This is the guts of next-line and previous-line.
6229 ;; Arg says how many lines to move.
6230 ;; The value is t if we can move the specified number of lines.
6231 (defun line-move-1 (arg &optional noerror _to-end)
6232 ;; Don't run any point-motion hooks, and disregard intangibility,
6233 ;; for intermediate positions.
6234 (let ((inhibit-point-motion-hooks t)
6235 (opoint (point))
6236 (orig-arg arg))
6237 (if (consp temporary-goal-column)
6238 (setq temporary-goal-column (+ (car temporary-goal-column)
6239 (cdr temporary-goal-column))))
6240 (unwind-protect
6241 (progn
6242 (if (not (memq last-command '(next-line previous-line)))
6243 (setq temporary-goal-column
6244 (if (and track-eol (eolp)
6245 ;; Don't count beg of empty line as end of line
6246 ;; unless we just did explicit end-of-line.
6247 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6248 most-positive-fixnum
6249 (current-column))))
6251 (if (not (or (integerp selective-display)
6252 line-move-ignore-invisible))
6253 ;; Use just newline characters.
6254 ;; Set ARG to 0 if we move as many lines as requested.
6255 (or (if (> arg 0)
6256 (progn (if (> arg 1) (forward-line (1- arg)))
6257 ;; This way of moving forward ARG lines
6258 ;; verifies that we have a newline after the last one.
6259 ;; It doesn't get confused by intangible text.
6260 (end-of-line)
6261 (if (zerop (forward-line 1))
6262 (setq arg 0)))
6263 (and (zerop (forward-line arg))
6264 (bolp)
6265 (setq arg 0)))
6266 (unless noerror
6267 (signal (if (< arg 0)
6268 'beginning-of-buffer
6269 'end-of-buffer)
6270 nil)))
6271 ;; Move by arg lines, but ignore invisible ones.
6272 (let (done)
6273 (while (and (> arg 0) (not done))
6274 ;; If the following character is currently invisible,
6275 ;; skip all characters with that same `invisible' property value.
6276 (while (and (not (eobp)) (invisible-p (point)))
6277 (goto-char (next-char-property-change (point))))
6278 ;; Move a line.
6279 ;; We don't use `end-of-line', since we want to escape
6280 ;; from field boundaries occurring exactly at point.
6281 (goto-char (constrain-to-field
6282 (let ((inhibit-field-text-motion t))
6283 (line-end-position))
6284 (point) t t
6285 'inhibit-line-move-field-capture))
6286 ;; If there's no invisibility here, move over the newline.
6287 (cond
6288 ((eobp)
6289 (if (not noerror)
6290 (signal 'end-of-buffer nil)
6291 (setq done t)))
6292 ((and (> arg 1) ;; Use vertical-motion for last move
6293 (not (integerp selective-display))
6294 (not (invisible-p (point))))
6295 ;; We avoid vertical-motion when possible
6296 ;; because that has to fontify.
6297 (forward-line 1))
6298 ;; Otherwise move a more sophisticated way.
6299 ((zerop (vertical-motion 1))
6300 (if (not noerror)
6301 (signal 'end-of-buffer nil)
6302 (setq done t))))
6303 (unless done
6304 (setq arg (1- arg))))
6305 ;; The logic of this is the same as the loop above,
6306 ;; it just goes in the other direction.
6307 (while (and (< arg 0) (not done))
6308 ;; For completely consistency with the forward-motion
6309 ;; case, we should call beginning-of-line here.
6310 ;; However, if point is inside a field and on a
6311 ;; continued line, the call to (vertical-motion -1)
6312 ;; below won't move us back far enough; then we return
6313 ;; to the same column in line-move-finish, and point
6314 ;; gets stuck -- cyd
6315 (forward-line 0)
6316 (cond
6317 ((bobp)
6318 (if (not noerror)
6319 (signal 'beginning-of-buffer nil)
6320 (setq done t)))
6321 ((and (< arg -1) ;; Use vertical-motion for last move
6322 (not (integerp selective-display))
6323 (not (invisible-p (1- (point)))))
6324 (forward-line -1))
6325 ((zerop (vertical-motion -1))
6326 (if (not noerror)
6327 (signal 'beginning-of-buffer nil)
6328 (setq done t))))
6329 (unless done
6330 (setq arg (1+ arg))
6331 (while (and ;; Don't move over previous invis lines
6332 ;; if our target is the middle of this line.
6333 (or (zerop (or goal-column temporary-goal-column))
6334 (< arg 0))
6335 (not (bobp)) (invisible-p (1- (point))))
6336 (goto-char (previous-char-property-change (point))))))))
6337 ;; This is the value the function returns.
6338 (= arg 0))
6340 (cond ((> arg 0)
6341 ;; If we did not move down as far as desired, at least go
6342 ;; to end of line. Be sure to call point-entered and
6343 ;; point-left-hooks.
6344 (let* ((npoint (prog1 (line-end-position)
6345 (goto-char opoint)))
6346 (inhibit-point-motion-hooks nil))
6347 (goto-char npoint)))
6348 ((< arg 0)
6349 ;; If we did not move up as far as desired,
6350 ;; at least go to beginning of line.
6351 (let* ((npoint (prog1 (line-beginning-position)
6352 (goto-char opoint)))
6353 (inhibit-point-motion-hooks nil))
6354 (goto-char npoint)))
6356 (line-move-finish (or goal-column temporary-goal-column)
6357 opoint (> orig-arg 0)))))))
6359 (defun line-move-finish (column opoint forward)
6360 (let ((repeat t))
6361 (while repeat
6362 ;; Set REPEAT to t to repeat the whole thing.
6363 (setq repeat nil)
6365 (let (new
6366 (old (point))
6367 (line-beg (line-beginning-position))
6368 (line-end
6369 ;; Compute the end of the line
6370 ;; ignoring effectively invisible newlines.
6371 (save-excursion
6372 ;; Like end-of-line but ignores fields.
6373 (skip-chars-forward "^\n")
6374 (while (and (not (eobp)) (invisible-p (point)))
6375 (goto-char (next-char-property-change (point)))
6376 (skip-chars-forward "^\n"))
6377 (point))))
6379 ;; Move to the desired column.
6380 (line-move-to-column (truncate column))
6382 ;; Corner case: suppose we start out in a field boundary in
6383 ;; the middle of a continued line. When we get to
6384 ;; line-move-finish, point is at the start of a new *screen*
6385 ;; line but the same text line; then line-move-to-column would
6386 ;; move us backwards. Test using C-n with point on the "x" in
6387 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6388 (and forward
6389 (< (point) old)
6390 (goto-char old))
6392 (setq new (point))
6394 ;; Process intangibility within a line.
6395 ;; With inhibit-point-motion-hooks bound to nil, a call to
6396 ;; goto-char moves point past intangible text.
6398 ;; However, inhibit-point-motion-hooks controls both the
6399 ;; intangibility and the point-entered/point-left hooks. The
6400 ;; following hack avoids calling the point-* hooks
6401 ;; unnecessarily. Note that we move *forward* past intangible
6402 ;; text when the initial and final points are the same.
6403 (goto-char new)
6404 (let ((inhibit-point-motion-hooks nil))
6405 (goto-char new)
6407 ;; If intangibility moves us to a different (later) place
6408 ;; in the same line, use that as the destination.
6409 (if (<= (point) line-end)
6410 (setq new (point))
6411 ;; If that position is "too late",
6412 ;; try the previous allowable position.
6413 ;; See if it is ok.
6414 (backward-char)
6415 (if (if forward
6416 ;; If going forward, don't accept the previous
6417 ;; allowable position if it is before the target line.
6418 (< line-beg (point))
6419 ;; If going backward, don't accept the previous
6420 ;; allowable position if it is still after the target line.
6421 (<= (point) line-end))
6422 (setq new (point))
6423 ;; As a last resort, use the end of the line.
6424 (setq new line-end))))
6426 ;; Now move to the updated destination, processing fields
6427 ;; as well as intangibility.
6428 (goto-char opoint)
6429 (let ((inhibit-point-motion-hooks nil))
6430 (goto-char
6431 ;; Ignore field boundaries if the initial and final
6432 ;; positions have the same `field' property, even if the
6433 ;; fields are non-contiguous. This seems to be "nicer"
6434 ;; behavior in many situations.
6435 (if (eq (get-char-property new 'field)
6436 (get-char-property opoint 'field))
6438 (constrain-to-field new opoint t t
6439 'inhibit-line-move-field-capture))))
6441 ;; If all this moved us to a different line,
6442 ;; retry everything within that new line.
6443 (when (or (< (point) line-beg) (> (point) line-end))
6444 ;; Repeat the intangibility and field processing.
6445 (setq repeat t))))))
6447 (defun line-move-to-column (col)
6448 "Try to find column COL, considering invisibility.
6449 This function works only in certain cases,
6450 because what we really need is for `move-to-column'
6451 and `current-column' to be able to ignore invisible text."
6452 (if (zerop col)
6453 (beginning-of-line)
6454 (move-to-column col))
6456 (when (and line-move-ignore-invisible
6457 (not (bolp)) (invisible-p (1- (point))))
6458 (let ((normal-location (point))
6459 (normal-column (current-column)))
6460 ;; If the following character is currently invisible,
6461 ;; skip all characters with that same `invisible' property value.
6462 (while (and (not (eobp))
6463 (invisible-p (point)))
6464 (goto-char (next-char-property-change (point))))
6465 ;; Have we advanced to a larger column position?
6466 (if (> (current-column) normal-column)
6467 ;; We have made some progress towards the desired column.
6468 ;; See if we can make any further progress.
6469 (line-move-to-column (+ (current-column) (- col normal-column)))
6470 ;; Otherwise, go to the place we originally found
6471 ;; and move back over invisible text.
6472 ;; that will get us to the same place on the screen
6473 ;; but with a more reasonable buffer position.
6474 (goto-char normal-location)
6475 (let ((line-beg
6476 ;; We want the real line beginning, so it's consistent
6477 ;; with bolp below, otherwise we might infloop.
6478 (let ((inhibit-field-text-motion t))
6479 (line-beginning-position))))
6480 (while (and (not (bolp)) (invisible-p (1- (point))))
6481 (goto-char (previous-char-property-change (point) line-beg))))))))
6483 (defun move-end-of-line (arg)
6484 "Move point to end of current line as displayed.
6485 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6486 If point reaches the beginning or end of buffer, it stops there.
6488 To ignore the effects of the `intangible' text or overlay
6489 property, bind `inhibit-point-motion-hooks' to t.
6490 If there is an image in the current line, this function
6491 disregards newlines that are part of the text on which the image
6492 rests."
6493 (interactive "^p")
6494 (or arg (setq arg 1))
6495 (let (done)
6496 (while (not done)
6497 (let ((newpos
6498 (save-excursion
6499 (let ((goal-column 0)
6500 (line-move-visual nil))
6501 (and (line-move arg t)
6502 ;; With bidi reordering, we may not be at bol,
6503 ;; so make sure we are.
6504 (skip-chars-backward "^\n")
6505 (not (bobp))
6506 (progn
6507 (while (and (not (bobp)) (invisible-p (1- (point))))
6508 (goto-char (previous-single-char-property-change
6509 (point) 'invisible)))
6510 (backward-char 1)))
6511 (point)))))
6512 (goto-char newpos)
6513 (if (and (> (point) newpos)
6514 (eq (preceding-char) ?\n))
6515 (backward-char 1)
6516 (if (and (> (point) newpos) (not (eobp))
6517 (not (eq (following-char) ?\n)))
6518 ;; If we skipped something intangible and now we're not
6519 ;; really at eol, keep going.
6520 (setq arg 1)
6521 (setq done t)))))))
6523 (defun move-beginning-of-line (arg)
6524 "Move point to beginning of current line as displayed.
6525 \(If there's an image in the line, this disregards newlines
6526 which are part of the text that the image rests on.)
6528 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6529 If point reaches the beginning or end of buffer, it stops there.
6530 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6531 (interactive "^p")
6532 (or arg (setq arg 1))
6534 (let ((orig (point))
6535 first-vis first-vis-field-value)
6537 ;; Move by lines, if ARG is not 1 (the default).
6538 (if (/= arg 1)
6539 (let ((line-move-visual nil))
6540 (line-move (1- arg) t)))
6542 ;; Move to beginning-of-line, ignoring fields and invisible text.
6543 (skip-chars-backward "^\n")
6544 (while (and (not (bobp)) (invisible-p (1- (point))))
6545 (goto-char (previous-char-property-change (point)))
6546 (skip-chars-backward "^\n"))
6548 ;; Now find first visible char in the line.
6549 (while (and (< (point) orig) (invisible-p (point)))
6550 (goto-char (next-char-property-change (point) orig)))
6551 (setq first-vis (point))
6553 ;; See if fields would stop us from reaching FIRST-VIS.
6554 (setq first-vis-field-value
6555 (constrain-to-field first-vis orig (/= arg 1) t nil))
6557 (goto-char (if (/= first-vis-field-value first-vis)
6558 ;; If yes, obey them.
6559 first-vis-field-value
6560 ;; Otherwise, move to START with attention to fields.
6561 ;; (It is possible that fields never matter in this case.)
6562 (constrain-to-field (point) orig
6563 (/= arg 1) t nil)))))
6566 ;; Many people have said they rarely use this feature, and often type
6567 ;; it by accident. Maybe it shouldn't even be on a key.
6568 (put 'set-goal-column 'disabled t)
6570 (defun set-goal-column (arg)
6571 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6572 Those commands will move to this position in the line moved to
6573 rather than trying to keep the same horizontal position.
6574 With a non-nil argument ARG, clears out the goal column
6575 so that \\[next-line] and \\[previous-line] resume vertical motion.
6576 The goal column is stored in the variable `goal-column'.
6577 This is a buffer-local setting."
6578 (interactive "P")
6579 (if arg
6580 (progn
6581 (setq goal-column nil)
6582 (message "No goal column"))
6583 (setq goal-column (current-column))
6584 ;; The older method below can be erroneous if `set-goal-column' is bound
6585 ;; to a sequence containing %
6586 ;;(message (substitute-command-keys
6587 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6588 ;;goal-column)
6589 (message "%s"
6590 (concat
6591 (format "Goal column %d " goal-column)
6592 (substitute-command-keys
6593 "(use \\[set-goal-column] with an arg to unset it)")))
6596 nil)
6598 ;;; Editing based on visual lines, as opposed to logical lines.
6600 (defun end-of-visual-line (&optional n)
6601 "Move point to end of current visual line.
6602 With argument N not nil or 1, move forward N - 1 visual lines first.
6603 If point reaches the beginning or end of buffer, it stops there.
6604 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6605 (interactive "^p")
6606 (or n (setq n 1))
6607 (if (/= n 1)
6608 (let ((line-move-visual t))
6609 (line-move (1- n) t)))
6610 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6611 ;; constrain to field boundaries, so we don't either.
6612 (vertical-motion (cons (window-width) 0)))
6614 (defun beginning-of-visual-line (&optional n)
6615 "Move point to beginning of current visual line.
6616 With argument N not nil or 1, move forward N - 1 visual lines first.
6617 If point reaches the beginning or end of buffer, it stops there.
6618 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6619 (interactive "^p")
6620 (or n (setq n 1))
6621 (let ((opoint (point)))
6622 (if (/= n 1)
6623 (let ((line-move-visual t))
6624 (line-move (1- n) t)))
6625 (vertical-motion 0)
6626 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6627 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6629 (defun kill-visual-line (&optional arg)
6630 "Kill the rest of the visual line.
6631 With prefix argument ARG, kill that many visual lines from point.
6632 If ARG is negative, kill visual lines backward.
6633 If ARG is zero, kill the text before point on the current visual
6634 line.
6636 If you want to append the killed line to the last killed text,
6637 use \\[append-next-kill] before \\[kill-line].
6639 If the buffer is read-only, Emacs will beep and refrain from deleting
6640 the line, but put the line in the kill ring anyway. This means that
6641 you can use this command to copy text from a read-only buffer.
6642 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6643 even beep.)"
6644 (interactive "P")
6645 ;; Like in `kill-line', it's better to move point to the other end
6646 ;; of the kill before killing.
6647 (let ((opoint (point))
6648 (kill-whole-line (and kill-whole-line (bolp))))
6649 (if arg
6650 (vertical-motion (prefix-numeric-value arg))
6651 (end-of-visual-line 1)
6652 (if (= (point) opoint)
6653 (vertical-motion 1)
6654 ;; Skip any trailing whitespace at the end of the visual line.
6655 ;; We used to do this only if `show-trailing-whitespace' is
6656 ;; nil, but that's wrong; the correct thing would be to check
6657 ;; whether the trailing whitespace is highlighted. But, it's
6658 ;; OK to just do this unconditionally.
6659 (skip-chars-forward " \t")))
6660 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
6661 (1+ (point))
6662 (point)))))
6664 (defun next-logical-line (&optional arg try-vscroll)
6665 "Move cursor vertically down ARG lines.
6666 This is identical to `next-line', except that it always moves
6667 by logical lines instead of visual lines, ignoring the value of
6668 the variable `line-move-visual'."
6669 (interactive "^p\np")
6670 (let ((line-move-visual nil))
6671 (with-no-warnings
6672 (next-line arg try-vscroll))))
6674 (defun previous-logical-line (&optional arg try-vscroll)
6675 "Move cursor vertically up ARG lines.
6676 This is identical to `previous-line', except that it always moves
6677 by logical lines instead of visual lines, ignoring the value of
6678 the variable `line-move-visual'."
6679 (interactive "^p\np")
6680 (let ((line-move-visual nil))
6681 (with-no-warnings
6682 (previous-line arg try-vscroll))))
6684 (defgroup visual-line nil
6685 "Editing based on visual lines."
6686 :group 'convenience
6687 :version "23.1")
6689 (defvar visual-line-mode-map
6690 (let ((map (make-sparse-keymap)))
6691 (define-key map [remap kill-line] 'kill-visual-line)
6692 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6693 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6694 ;; These keybindings interfere with xterm function keys. Are
6695 ;; there any other suitable bindings?
6696 ;; (define-key map "\M-[" 'previous-logical-line)
6697 ;; (define-key map "\M-]" 'next-logical-line)
6698 map))
6700 (defcustom visual-line-fringe-indicators '(nil nil)
6701 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6702 The value should be a list of the form (LEFT RIGHT), where LEFT
6703 and RIGHT are symbols representing the bitmaps to display, to
6704 indicate wrapped lines, in the left and right fringes respectively.
6705 See also `fringe-indicator-alist'.
6706 The default is not to display fringe indicators for wrapped lines.
6707 This variable does not affect fringe indicators displayed for
6708 other purposes."
6709 :type '(list (choice (const :tag "Hide left indicator" nil)
6710 (const :tag "Left curly arrow" left-curly-arrow)
6711 (symbol :tag "Other bitmap"))
6712 (choice (const :tag "Hide right indicator" nil)
6713 (const :tag "Right curly arrow" right-curly-arrow)
6714 (symbol :tag "Other bitmap")))
6715 :set (lambda (symbol value)
6716 (dolist (buf (buffer-list))
6717 (with-current-buffer buf
6718 (when (and (boundp 'visual-line-mode)
6719 (symbol-value 'visual-line-mode))
6720 (setq fringe-indicator-alist
6721 (cons (cons 'continuation value)
6722 (assq-delete-all
6723 'continuation
6724 (copy-tree fringe-indicator-alist)))))))
6725 (set-default symbol value)))
6727 (defvar visual-line--saved-state nil)
6729 (define-minor-mode visual-line-mode
6730 "Toggle visual line based editing (Visual Line mode).
6731 With a prefix argument ARG, enable Visual Line mode if ARG is
6732 positive, and disable it otherwise. If called from Lisp, enable
6733 the mode if ARG is omitted or nil.
6735 When Visual Line mode is enabled, `word-wrap' is turned on in
6736 this buffer, and simple editing commands are redefined to act on
6737 visual lines, not logical lines. See Info node `Visual Line
6738 Mode' for details."
6739 :keymap visual-line-mode-map
6740 :group 'visual-line
6741 :lighter " Wrap"
6742 (if visual-line-mode
6743 (progn
6744 (set (make-local-variable 'visual-line--saved-state) nil)
6745 ;; Save the local values of some variables, to be restored if
6746 ;; visual-line-mode is turned off.
6747 (dolist (var '(line-move-visual truncate-lines
6748 truncate-partial-width-windows
6749 word-wrap fringe-indicator-alist))
6750 (if (local-variable-p var)
6751 (push (cons var (symbol-value var))
6752 visual-line--saved-state)))
6753 (set (make-local-variable 'line-move-visual) t)
6754 (set (make-local-variable 'truncate-partial-width-windows) nil)
6755 (setq truncate-lines nil
6756 word-wrap t
6757 fringe-indicator-alist
6758 (cons (cons 'continuation visual-line-fringe-indicators)
6759 fringe-indicator-alist)))
6760 (kill-local-variable 'line-move-visual)
6761 (kill-local-variable 'word-wrap)
6762 (kill-local-variable 'truncate-lines)
6763 (kill-local-variable 'truncate-partial-width-windows)
6764 (kill-local-variable 'fringe-indicator-alist)
6765 (dolist (saved visual-line--saved-state)
6766 (set (make-local-variable (car saved)) (cdr saved)))
6767 (kill-local-variable 'visual-line--saved-state)))
6769 (defun turn-on-visual-line-mode ()
6770 (visual-line-mode 1))
6772 (define-globalized-minor-mode global-visual-line-mode
6773 visual-line-mode turn-on-visual-line-mode)
6776 (defun transpose-chars (arg)
6777 "Interchange characters around point, moving forward one character.
6778 With prefix arg ARG, effect is to take character before point
6779 and drag it forward past ARG other characters (backward if ARG negative).
6780 If no argument and at end of line, the previous two chars are exchanged."
6781 (interactive "*P")
6782 (when (and (null arg) (eolp) (not (bobp))
6783 (not (get-text-property (1- (point)) 'read-only)))
6784 (forward-char -1))
6785 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6787 (defun transpose-words (arg)
6788 "Interchange words around point, leaving point at end of them.
6789 With prefix arg ARG, effect is to take word before or around point
6790 and drag it forward past ARG other words (backward if ARG negative).
6791 If ARG is zero, the words around or after point and around or after mark
6792 are interchanged."
6793 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6794 (interactive "*p")
6795 (transpose-subr 'forward-word arg))
6797 (defun transpose-sexps (arg)
6798 "Like \\[transpose-chars] (`transpose-chars'), but applies to sexps.
6799 Unlike `transpose-words', point must be between the two sexps and not
6800 in the middle of a sexp to be transposed.
6801 With non-zero prefix arg ARG, effect is to take the sexp before point
6802 and drag it forward past ARG other sexps (backward if ARG is negative).
6803 If ARG is zero, the sexps ending at or after point and at or after mark
6804 are interchanged."
6805 (interactive "*p")
6806 (transpose-subr
6807 (lambda (arg)
6808 ;; Here we should try to simulate the behavior of
6809 ;; (cons (progn (forward-sexp x) (point))
6810 ;; (progn (forward-sexp (- x)) (point)))
6811 ;; Except that we don't want to rely on the second forward-sexp
6812 ;; putting us back to where we want to be, since forward-sexp-function
6813 ;; might do funny things like infix-precedence.
6814 (if (if (> arg 0)
6815 (looking-at "\\sw\\|\\s_")
6816 (and (not (bobp))
6817 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6818 ;; Jumping over a symbol. We might be inside it, mind you.
6819 (progn (funcall (if (> arg 0)
6820 'skip-syntax-backward 'skip-syntax-forward)
6821 "w_")
6822 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6823 ;; Otherwise, we're between sexps. Take a step back before jumping
6824 ;; to make sure we'll obey the same precedence no matter which direction
6825 ;; we're going.
6826 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6827 (cons (save-excursion (forward-sexp arg) (point))
6828 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6829 (not (zerop (funcall (if (> arg 0)
6830 'skip-syntax-forward
6831 'skip-syntax-backward)
6832 ".")))))
6833 (point)))))
6834 arg 'special))
6836 (defun transpose-lines (arg)
6837 "Exchange current line and previous line, leaving point after both.
6838 With argument ARG, takes previous line and moves it past ARG lines.
6839 With argument 0, interchanges line point is in with line mark is in."
6840 (interactive "*p")
6841 (transpose-subr (function
6842 (lambda (arg)
6843 (if (> arg 0)
6844 (progn
6845 ;; Move forward over ARG lines,
6846 ;; but create newlines if necessary.
6847 (setq arg (forward-line arg))
6848 (if (/= (preceding-char) ?\n)
6849 (setq arg (1+ arg)))
6850 (if (> arg 0)
6851 (newline arg)))
6852 (forward-line arg))))
6853 arg))
6855 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6856 ;; which seems inconsistent with the ARG /= 0 case.
6857 ;; FIXME document SPECIAL.
6858 (defun transpose-subr (mover arg &optional special)
6859 "Subroutine to do the work of transposing objects.
6860 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6861 moves forward by units of the given object (e.g. forward-sentence,
6862 forward-paragraph). If ARG is zero, exchanges the current object
6863 with the one containing mark. If ARG is an integer, moves the
6864 current object past ARG following (if ARG is positive) or
6865 preceding (if ARG is negative) objects, leaving point after the
6866 current object."
6867 (let ((aux (if special mover
6868 (lambda (x)
6869 (cons (progn (funcall mover x) (point))
6870 (progn (funcall mover (- x)) (point))))))
6871 pos1 pos2)
6872 (cond
6873 ((= arg 0)
6874 (save-excursion
6875 (setq pos1 (funcall aux 1))
6876 (goto-char (or (mark) (error "No mark set in this buffer")))
6877 (setq pos2 (funcall aux 1))
6878 (transpose-subr-1 pos1 pos2))
6879 (exchange-point-and-mark))
6880 ((> arg 0)
6881 (setq pos1 (funcall aux -1))
6882 (setq pos2 (funcall aux arg))
6883 (transpose-subr-1 pos1 pos2)
6884 (goto-char (car pos2)))
6886 (setq pos1 (funcall aux -1))
6887 (goto-char (car pos1))
6888 (setq pos2 (funcall aux arg))
6889 (transpose-subr-1 pos1 pos2)
6890 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6892 (defun transpose-subr-1 (pos1 pos2)
6893 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6894 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6895 (when (> (car pos1) (car pos2))
6896 (let ((swap pos1))
6897 (setq pos1 pos2 pos2 swap)))
6898 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6899 (atomic-change-group
6900 ;; This sequence of insertions attempts to preserve marker
6901 ;; positions at the start and end of the transposed objects.
6902 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6903 (len1 (- (cdr pos1) (car pos1)))
6904 (len2 (length word))
6905 (boundary (make-marker)))
6906 (set-marker boundary (car pos2))
6907 (goto-char (cdr pos1))
6908 (insert-before-markers word)
6909 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6910 (goto-char boundary)
6911 (insert word)
6912 (goto-char (+ boundary len1))
6913 (delete-region (point) (+ (point) len2))
6914 (set-marker boundary nil))))
6916 (defun backward-word (&optional arg)
6917 "Move backward until encountering the beginning of a word.
6918 With argument ARG, do this that many times.
6919 If ARG is omitted or nil, move point backward one word.
6921 The word boundaries are normally determined by the buffer's syntax
6922 table, but `find-word-boundary-function-table', such as set up
6923 by `subword-mode', can change that. If a Lisp program needs to
6924 move by words determined strictly by the syntax table, it should
6925 use `backward-word-strictly' instead."
6926 (interactive "^p")
6927 (forward-word (- (or arg 1))))
6929 (defun mark-word (&optional arg allow-extend)
6930 "Set mark ARG words away from point.
6931 The place mark goes is the same place \\[forward-word] would
6932 move to with the same argument.
6933 Interactively, if this command is repeated
6934 or (in Transient Mark mode) if the mark is active,
6935 it marks the next ARG words after the ones already marked."
6936 (interactive "P\np")
6937 (cond ((and allow-extend
6938 (or (and (eq last-command this-command) (mark t))
6939 (region-active-p)))
6940 (setq arg (if arg (prefix-numeric-value arg)
6941 (if (< (mark) (point)) -1 1)))
6942 (set-mark
6943 (save-excursion
6944 (goto-char (mark))
6945 (forward-word arg)
6946 (point))))
6948 (push-mark
6949 (save-excursion
6950 (forward-word (prefix-numeric-value arg))
6951 (point))
6952 nil t))))
6954 (defun kill-word (arg)
6955 "Kill characters forward until encountering the end of a word.
6956 With argument ARG, do this that many times."
6957 (interactive "p")
6958 (kill-region (point) (progn (forward-word arg) (point))))
6960 (defun backward-kill-word (arg)
6961 "Kill characters backward until encountering the beginning of a word.
6962 With argument ARG, do this that many times."
6963 (interactive "p")
6964 (kill-word (- arg)))
6966 (defun current-word (&optional strict really-word)
6967 "Return the word at or near point, as a string.
6968 The return value includes no text properties.
6970 If optional arg STRICT is non-nil, return nil unless point is
6971 within or adjacent to a word, otherwise look for a word within
6972 point's line. If there is no word anywhere on point's line, the
6973 value is nil regardless of STRICT.
6975 By default, this function treats as a single word any sequence of
6976 characters that have either word or symbol syntax. If optional
6977 arg REALLY-WORD is non-nil, only characters of word syntax can
6978 constitute a word."
6979 (save-excursion
6980 (let* ((oldpoint (point)) (start (point)) (end (point))
6981 (syntaxes (if really-word "w" "w_"))
6982 (not-syntaxes (concat "^" syntaxes)))
6983 (skip-syntax-backward syntaxes) (setq start (point))
6984 (goto-char oldpoint)
6985 (skip-syntax-forward syntaxes) (setq end (point))
6986 (when (and (eq start oldpoint) (eq end oldpoint)
6987 ;; Point is neither within nor adjacent to a word.
6988 (not strict))
6989 ;; Look for preceding word in same line.
6990 (skip-syntax-backward not-syntaxes (line-beginning-position))
6991 (if (bolp)
6992 ;; No preceding word in same line.
6993 ;; Look for following word in same line.
6994 (progn
6995 (skip-syntax-forward not-syntaxes (line-end-position))
6996 (setq start (point))
6997 (skip-syntax-forward syntaxes)
6998 (setq end (point)))
6999 (setq end (point))
7000 (skip-syntax-backward syntaxes)
7001 (setq start (point))))
7002 ;; If we found something nonempty, return it as a string.
7003 (unless (= start end)
7004 (buffer-substring-no-properties start end)))))
7006 (defcustom fill-prefix nil
7007 "String for filling to insert at front of new line, or nil for none."
7008 :type '(choice (const :tag "None" nil)
7009 string)
7010 :group 'fill)
7011 (make-variable-buffer-local 'fill-prefix)
7012 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
7014 (defcustom auto-fill-inhibit-regexp nil
7015 "Regexp to match lines which should not be auto-filled."
7016 :type '(choice (const :tag "None" nil)
7017 regexp)
7018 :group 'fill)
7020 (defun do-auto-fill ()
7021 "The default value for `normal-auto-fill-function'.
7022 This is the default auto-fill function, some major modes use a different one.
7023 Returns t if it really did any work."
7024 (let (fc justify give-up
7025 (fill-prefix fill-prefix))
7026 (if (or (not (setq justify (current-justification)))
7027 (null (setq fc (current-fill-column)))
7028 (and (eq justify 'left)
7029 (<= (current-column) fc))
7030 (and auto-fill-inhibit-regexp
7031 (save-excursion (beginning-of-line)
7032 (looking-at auto-fill-inhibit-regexp))))
7033 nil ;; Auto-filling not required
7034 (if (memq justify '(full center right))
7035 (save-excursion (unjustify-current-line)))
7037 ;; Choose a fill-prefix automatically.
7038 (when (and adaptive-fill-mode
7039 (or (null fill-prefix) (string= fill-prefix "")))
7040 (let ((prefix
7041 (fill-context-prefix
7042 (save-excursion (fill-forward-paragraph -1) (point))
7043 (save-excursion (fill-forward-paragraph 1) (point)))))
7044 (and prefix (not (equal prefix ""))
7045 ;; Use auto-indentation rather than a guessed empty prefix.
7046 (not (and fill-indent-according-to-mode
7047 (string-match "\\`[ \t]*\\'" prefix)))
7048 (setq fill-prefix prefix))))
7050 (while (and (not give-up) (> (current-column) fc))
7051 ;; Determine where to split the line.
7052 (let* (after-prefix
7053 (fill-point
7054 (save-excursion
7055 (beginning-of-line)
7056 (setq after-prefix (point))
7057 (and fill-prefix
7058 (looking-at (regexp-quote fill-prefix))
7059 (setq after-prefix (match-end 0)))
7060 (move-to-column (1+ fc))
7061 (fill-move-to-break-point after-prefix)
7062 (point))))
7064 ;; See whether the place we found is any good.
7065 (if (save-excursion
7066 (goto-char fill-point)
7067 (or (bolp)
7068 ;; There is no use breaking at end of line.
7069 (save-excursion (skip-chars-forward " ") (eolp))
7070 ;; It is futile to split at the end of the prefix
7071 ;; since we would just insert the prefix again.
7072 (and after-prefix (<= (point) after-prefix))
7073 ;; Don't split right after a comment starter
7074 ;; since we would just make another comment starter.
7075 (and comment-start-skip
7076 (let ((limit (point)))
7077 (beginning-of-line)
7078 (and (re-search-forward comment-start-skip
7079 limit t)
7080 (eq (point) limit))))))
7081 ;; No good place to break => stop trying.
7082 (setq give-up t)
7083 ;; Ok, we have a useful place to break the line. Do it.
7084 (let ((prev-column (current-column)))
7085 ;; If point is at the fill-point, do not `save-excursion'.
7086 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
7087 ;; point will end up before it rather than after it.
7088 (if (save-excursion
7089 (skip-chars-backward " \t")
7090 (= (point) fill-point))
7091 (default-indent-new-line t)
7092 (save-excursion
7093 (goto-char fill-point)
7094 (default-indent-new-line t)))
7095 ;; Now do justification, if required
7096 (if (not (eq justify 'left))
7097 (save-excursion
7098 (end-of-line 0)
7099 (justify-current-line justify nil t)))
7100 ;; If making the new line didn't reduce the hpos of
7101 ;; the end of the line, then give up now;
7102 ;; trying again will not help.
7103 (if (>= (current-column) prev-column)
7104 (setq give-up t))))))
7105 ;; Justify last line.
7106 (justify-current-line justify t t)
7107 t)))
7109 (defvar comment-line-break-function 'comment-indent-new-line
7110 "Mode-specific function which line breaks and continues a comment.
7111 This function is called during auto-filling when a comment syntax
7112 is defined.
7113 The function should take a single optional argument, which is a flag
7114 indicating whether it should use soft newlines.")
7116 (defun default-indent-new-line (&optional soft)
7117 "Break line at point and indent.
7118 If a comment syntax is defined, call `comment-indent-new-line'.
7120 The inserted newline is marked hard if variable `use-hard-newlines' is true,
7121 unless optional argument SOFT is non-nil."
7122 (interactive)
7123 (if comment-start
7124 (funcall comment-line-break-function soft)
7125 ;; Insert the newline before removing empty space so that markers
7126 ;; get preserved better.
7127 (if soft (insert-and-inherit ?\n) (newline 1))
7128 (save-excursion (forward-char -1) (delete-horizontal-space))
7129 (delete-horizontal-space)
7131 (if (and fill-prefix (not adaptive-fill-mode))
7132 ;; Blindly trust a non-adaptive fill-prefix.
7133 (progn
7134 (indent-to-left-margin)
7135 (insert-before-markers-and-inherit fill-prefix))
7137 (cond
7138 ;; If there's an adaptive prefix, use it unless we're inside
7139 ;; a comment and the prefix is not a comment starter.
7140 (fill-prefix
7141 (indent-to-left-margin)
7142 (insert-and-inherit fill-prefix))
7143 ;; If we're not inside a comment, just try to indent.
7144 (t (indent-according-to-mode))))))
7146 (defvar normal-auto-fill-function 'do-auto-fill
7147 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
7148 Some major modes set this.")
7150 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
7151 ;; `functions' and `hooks' are usually unsafe to set, but setting
7152 ;; auto-fill-function to nil in a file-local setting is safe and
7153 ;; can be useful to prevent auto-filling.
7154 (put 'auto-fill-function 'safe-local-variable 'null)
7156 (define-minor-mode auto-fill-mode
7157 "Toggle automatic line breaking (Auto Fill mode).
7158 With a prefix argument ARG, enable Auto Fill mode if ARG is
7159 positive, and disable it otherwise. If called from Lisp, enable
7160 the mode if ARG is omitted or nil.
7162 When Auto Fill mode is enabled, inserting a space at a column
7163 beyond `current-fill-column' automatically breaks the line at a
7164 previous space.
7166 When `auto-fill-mode' is on, the `auto-fill-function' variable is
7167 non-nil.
7169 The value of `normal-auto-fill-function' specifies the function to use
7170 for `auto-fill-function' when turning Auto Fill mode on."
7171 :variable (auto-fill-function
7172 . (lambda (v) (setq auto-fill-function
7173 (if v normal-auto-fill-function)))))
7175 ;; This holds a document string used to document auto-fill-mode.
7176 (defun auto-fill-function ()
7177 "Automatically break line at a previous space, in insertion of text."
7178 nil)
7180 (defun turn-on-auto-fill ()
7181 "Unconditionally turn on Auto Fill mode."
7182 (auto-fill-mode 1))
7184 (defun turn-off-auto-fill ()
7185 "Unconditionally turn off Auto Fill mode."
7186 (auto-fill-mode -1))
7188 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7190 (defun set-fill-column (arg)
7191 "Set `fill-column' to specified argument.
7192 Use \\[universal-argument] followed by a number to specify a column.
7193 Just \\[universal-argument] as argument means to use the current column."
7194 (interactive
7195 (list (or current-prefix-arg
7196 ;; We used to use current-column silently, but C-x f is too easily
7197 ;; typed as a typo for C-x C-f, so we turned it into an error and
7198 ;; now an interactive prompt.
7199 (read-number "Set fill-column to: " (current-column)))))
7200 (if (consp arg)
7201 (setq arg (current-column)))
7202 (if (not (integerp arg))
7203 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7204 (error "set-fill-column requires an explicit argument")
7205 (message "Fill column set to %d (was %d)" arg fill-column)
7206 (setq fill-column arg)))
7208 (defun set-selective-display (arg)
7209 "Set `selective-display' to ARG; clear it if no arg.
7210 When the value of `selective-display' is a number > 0,
7211 lines whose indentation is >= that value are not displayed.
7212 The variable `selective-display' has a separate value for each buffer."
7213 (interactive "P")
7214 (if (eq selective-display t)
7215 (error "selective-display already in use for marked lines"))
7216 (let ((current-vpos
7217 (save-restriction
7218 (narrow-to-region (point-min) (point))
7219 (goto-char (window-start))
7220 (vertical-motion (window-height)))))
7221 (setq selective-display
7222 (and arg (prefix-numeric-value arg)))
7223 (recenter current-vpos))
7224 (set-window-start (selected-window) (window-start))
7225 (princ "selective-display set to " t)
7226 (prin1 selective-display t)
7227 (princ "." t))
7229 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7231 (defun toggle-truncate-lines (&optional arg)
7232 "Toggle truncating of long lines for the current buffer.
7233 When truncating is off, long lines are folded.
7234 With prefix argument ARG, truncate long lines if ARG is positive,
7235 otherwise fold them. Note that in side-by-side windows, this
7236 command has no effect if `truncate-partial-width-windows' is
7237 non-nil."
7238 (interactive "P")
7239 (setq truncate-lines
7240 (if (null arg)
7241 (not truncate-lines)
7242 (> (prefix-numeric-value arg) 0)))
7243 (force-mode-line-update)
7244 (unless truncate-lines
7245 (let ((buffer (current-buffer)))
7246 (walk-windows (lambda (window)
7247 (if (eq buffer (window-buffer window))
7248 (set-window-hscroll window 0)))
7249 nil t)))
7250 (message "Truncate long lines %s"
7251 (if truncate-lines "enabled" "disabled")))
7253 (defun toggle-word-wrap (&optional arg)
7254 "Toggle whether to use word-wrapping for continuation lines.
7255 With prefix argument ARG, wrap continuation lines at word boundaries
7256 if ARG is positive, otherwise wrap them at the right screen edge.
7257 This command toggles the value of `word-wrap'. It has no effect
7258 if long lines are truncated."
7259 (interactive "P")
7260 (setq word-wrap
7261 (if (null arg)
7262 (not word-wrap)
7263 (> (prefix-numeric-value arg) 0)))
7264 (force-mode-line-update)
7265 (message "Word wrapping %s"
7266 (if word-wrap "enabled" "disabled")))
7268 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7269 "The string displayed in the mode line when in overwrite mode.")
7270 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7271 "The string displayed in the mode line when in binary overwrite mode.")
7273 (define-minor-mode overwrite-mode
7274 "Toggle Overwrite mode.
7275 With a prefix argument ARG, enable Overwrite mode if ARG is
7276 positive, and disable it otherwise. If called from Lisp, enable
7277 the mode if ARG is omitted or nil.
7279 When Overwrite mode is enabled, printing characters typed in
7280 replace existing text on a one-for-one basis, rather than pushing
7281 it to the right. At the end of a line, such characters extend
7282 the line. Before a tab, such characters insert until the tab is
7283 filled in. \\[quoted-insert] still inserts characters in
7284 overwrite mode; this is supposed to make it easier to insert
7285 characters when necessary."
7286 :variable (overwrite-mode
7287 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7289 (define-minor-mode binary-overwrite-mode
7290 "Toggle Binary Overwrite mode.
7291 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7292 is positive, and disable it otherwise. If called from Lisp,
7293 enable the mode if ARG is omitted or nil.
7295 When Binary Overwrite mode is enabled, printing characters typed
7296 in replace existing text. Newlines are not treated specially, so
7297 typing at the end of a line joins the line to the next, with the
7298 typed character between them. Typing before a tab character
7299 simply replaces the tab with the character typed.
7300 \\[quoted-insert] replaces the text at the cursor, just as
7301 ordinary typing characters do.
7303 Note that Binary Overwrite mode is not its own minor mode; it is
7304 a specialization of overwrite mode, entered by setting the
7305 `overwrite-mode' variable to `overwrite-mode-binary'."
7306 :variable (overwrite-mode
7307 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7309 (define-minor-mode line-number-mode
7310 "Toggle line number display in the mode line (Line Number mode).
7311 With a prefix argument ARG, enable Line Number mode if ARG is
7312 positive, and disable it otherwise. If called from Lisp, enable
7313 the mode if ARG is omitted or nil.
7315 Line numbers do not appear for very large buffers and buffers
7316 with very long lines; see variables `line-number-display-limit'
7317 and `line-number-display-limit-width'."
7318 :init-value t :global t :group 'mode-line)
7320 (define-minor-mode column-number-mode
7321 "Toggle column number display in the mode line (Column Number mode).
7322 With a prefix argument ARG, enable Column Number mode if ARG is
7323 positive, and disable it otherwise.
7325 If called from Lisp, enable the mode if ARG is omitted or nil."
7326 :global t :group 'mode-line)
7328 (define-minor-mode size-indication-mode
7329 "Toggle buffer size display in the mode line (Size Indication mode).
7330 With a prefix argument ARG, enable Size Indication mode if ARG is
7331 positive, and disable it otherwise.
7333 If called from Lisp, enable the mode if ARG is omitted or nil."
7334 :global t :group 'mode-line)
7336 (define-minor-mode auto-save-mode
7337 "Toggle auto-saving in the current buffer (Auto Save mode).
7338 With a prefix argument ARG, enable Auto Save mode if ARG is
7339 positive, and disable it otherwise.
7341 If called from Lisp, enable the mode if ARG is omitted or nil."
7342 :variable ((and buffer-auto-save-file-name
7343 ;; If auto-save is off because buffer has shrunk,
7344 ;; then toggling should turn it on.
7345 (>= buffer-saved-size 0))
7346 . (lambda (val)
7347 (setq buffer-auto-save-file-name
7348 (cond
7349 ((null val) nil)
7350 ((and buffer-file-name auto-save-visited-file-name
7351 (not buffer-read-only))
7352 buffer-file-name)
7353 (t (make-auto-save-file-name))))))
7354 ;; If -1 was stored here, to temporarily turn off saving,
7355 ;; turn it back on.
7356 (and (< buffer-saved-size 0)
7357 (setq buffer-saved-size 0)))
7359 (defgroup paren-blinking nil
7360 "Blinking matching of parens and expressions."
7361 :prefix "blink-matching-"
7362 :group 'paren-matching)
7364 (defcustom blink-matching-paren t
7365 "Non-nil means show matching open-paren when close-paren is inserted.
7366 If t, highlight the paren. If `jump', briefly move cursor to its
7367 position. If `jump-offscreen', move cursor there even if the
7368 position is off screen. With any other non-nil value, the
7369 off-screen position of the opening paren will be shown in the
7370 echo area."
7371 :type '(choice
7372 (const :tag "Disable" nil)
7373 (const :tag "Highlight" t)
7374 (const :tag "Move cursor" jump)
7375 (const :tag "Move cursor, even if off screen" jump-offscreen))
7376 :group 'paren-blinking)
7378 (defcustom blink-matching-paren-on-screen t
7379 "Non-nil means show matching open-paren when it is on screen.
7380 If nil, don't show it (but the open-paren can still be shown
7381 in the echo area when it is off screen).
7383 This variable has no effect if `blink-matching-paren' is nil.
7384 \(In that case, the open-paren is never shown.)
7385 It is also ignored if `show-paren-mode' is enabled."
7386 :type 'boolean
7387 :group 'paren-blinking)
7389 (defcustom blink-matching-paren-distance (* 100 1024)
7390 "If non-nil, maximum distance to search backwards for matching open-paren.
7391 If nil, search stops at the beginning of the accessible portion of the buffer."
7392 :version "23.2" ; 25->100k
7393 :type '(choice (const nil) integer)
7394 :group 'paren-blinking)
7396 (defcustom blink-matching-delay 1
7397 "Time in seconds to delay after showing a matching paren."
7398 :type 'number
7399 :group 'paren-blinking)
7401 (defcustom blink-matching-paren-dont-ignore-comments nil
7402 "If nil, `blink-matching-paren' ignores comments.
7403 More precisely, when looking for the matching parenthesis,
7404 it skips the contents of comments that end before point."
7405 :type 'boolean
7406 :group 'paren-blinking)
7408 (defun blink-matching-check-mismatch (start end)
7409 "Return whether or not START...END are matching parens.
7410 END is the current point and START is the blink position.
7411 START might be nil if no matching starter was found.
7412 Returns non-nil if we find there is a mismatch."
7413 (let* ((end-syntax (syntax-after (1- end)))
7414 (matching-paren (and (consp end-syntax)
7415 (eq (syntax-class end-syntax) 5)
7416 (cdr end-syntax))))
7417 ;; For self-matched chars like " and $, we can't know when they're
7418 ;; mismatched or unmatched, so we can only do it for parens.
7419 (when matching-paren
7420 (not (and start
7422 (eq (char-after start) matching-paren)
7423 ;; The cdr might hold a new paren-class info rather than
7424 ;; a matching-char info, in which case the two CDRs
7425 ;; should match.
7426 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7428 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7429 "Function to check parentheses mismatches.
7430 The function takes two arguments (START and END) where START is the
7431 position just before the opening token and END is the position right after.
7432 START can be nil, if it was not found.
7433 The function should return non-nil if the two tokens do not match.")
7435 (defvar blink-matching--overlay
7436 (let ((ol (make-overlay (point) (point) nil t)))
7437 (overlay-put ol 'face 'show-paren-match)
7438 (delete-overlay ol)
7440 "Overlay used to highlight the matching paren.")
7442 (defun blink-matching-open ()
7443 "Momentarily highlight the beginning of the sexp before point."
7444 (interactive)
7445 (when (and (not (bobp))
7446 blink-matching-paren)
7447 (let* ((oldpos (point))
7448 (message-log-max nil) ; Don't log messages about paren matching.
7449 (blinkpos
7450 (save-excursion
7451 (save-restriction
7452 (if blink-matching-paren-distance
7453 (narrow-to-region
7454 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7455 (- (point) blink-matching-paren-distance))
7456 oldpos))
7457 (let ((parse-sexp-ignore-comments
7458 (and parse-sexp-ignore-comments
7459 (not blink-matching-paren-dont-ignore-comments))))
7460 (condition-case ()
7461 (progn
7462 (syntax-propertize (point))
7463 (forward-sexp -1)
7464 ;; backward-sexp skips backward over prefix chars,
7465 ;; so move back to the matching paren.
7466 (while (and (< (point) (1- oldpos))
7467 (let ((code (syntax-after (point))))
7468 (or (eq (syntax-class code) 6)
7469 (eq (logand 1048576 (car code))
7470 1048576))))
7471 (forward-char 1))
7472 (point))
7473 (error nil))))))
7474 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7475 (cond
7476 (mismatch
7477 (if blinkpos
7478 (if (minibufferp)
7479 (minibuffer-message "Mismatched parentheses")
7480 (message "Mismatched parentheses"))
7481 (if (minibufferp)
7482 (minibuffer-message "No matching parenthesis found")
7483 (message "No matching parenthesis found"))))
7484 ((not blinkpos) nil)
7485 ((or
7486 (eq blink-matching-paren 'jump-offscreen)
7487 (pos-visible-in-window-p blinkpos))
7488 ;; Matching open within window, temporarily move to or highlight
7489 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7490 ;; is non-nil.
7491 (and blink-matching-paren-on-screen
7492 (not show-paren-mode)
7493 (if (memq blink-matching-paren '(jump jump-offscreen))
7494 (save-excursion
7495 (goto-char blinkpos)
7496 (sit-for blink-matching-delay))
7497 (unwind-protect
7498 (progn
7499 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7500 (current-buffer))
7501 (sit-for blink-matching-delay))
7502 (delete-overlay blink-matching--overlay)))))
7504 (let ((open-paren-line-string
7505 (save-excursion
7506 (goto-char blinkpos)
7507 ;; Show what precedes the open in its line, if anything.
7508 (cond
7509 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7510 (buffer-substring (line-beginning-position)
7511 (1+ blinkpos)))
7512 ;; Show what follows the open in its line, if anything.
7513 ((save-excursion
7514 (forward-char 1)
7515 (skip-chars-forward " \t")
7516 (not (eolp)))
7517 (buffer-substring blinkpos
7518 (line-end-position)))
7519 ;; Otherwise show the previous nonblank line,
7520 ;; if there is one.
7521 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7522 (concat
7523 (buffer-substring (progn
7524 (skip-chars-backward "\n \t")
7525 (line-beginning-position))
7526 (progn (end-of-line)
7527 (skip-chars-backward " \t")
7528 (point)))
7529 ;; Replace the newline and other whitespace with `...'.
7530 "..."
7531 (buffer-substring blinkpos (1+ blinkpos))))
7532 ;; There is nothing to show except the char itself.
7533 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7534 (minibuffer-message
7535 "Matches %s"
7536 (substring-no-properties open-paren-line-string))))))))
7538 (defvar blink-paren-function 'blink-matching-open
7539 "Function called, if non-nil, whenever a close parenthesis is inserted.
7540 More precisely, a char with closeparen syntax is self-inserted.")
7542 (defun blink-paren-post-self-insert-function ()
7543 (when (and (eq (char-before) last-command-event) ; Sanity check.
7544 (memq (char-syntax last-command-event) '(?\) ?\$))
7545 blink-paren-function
7546 (not executing-kbd-macro)
7547 (not noninteractive)
7548 ;; Verify an even number of quoting characters precede the close.
7549 ;; FIXME: Also check if this parenthesis closes a comment as
7550 ;; can happen in Pascal and SML.
7551 (= 1 (logand 1 (- (point)
7552 (save-excursion
7553 (forward-char -1)
7554 (skip-syntax-backward "/\\")
7555 (point))))))
7556 (funcall blink-paren-function)))
7558 (put 'blink-paren-post-self-insert-function 'priority 100)
7560 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7561 ;; Most likely, this hook is nil, so this arg doesn't matter,
7562 ;; but I use it as a reminder that this function usually
7563 ;; likes to be run after others since it does
7564 ;; `sit-for'. That's also the reason it get a `priority' prop
7565 ;; of 100.
7566 'append)
7568 ;; This executes C-g typed while Emacs is waiting for a command.
7569 ;; Quitting out of a program does not go through here;
7570 ;; that happens in the QUIT macro at the C code level.
7571 (defun keyboard-quit ()
7572 "Signal a `quit' condition.
7573 During execution of Lisp code, this character causes a quit directly.
7574 At top-level, as an editor command, this simply beeps."
7575 (interactive)
7576 ;; Avoid adding the region to the window selection.
7577 (setq saved-region-selection nil)
7578 (let (select-active-regions)
7579 (deactivate-mark))
7580 (if (fboundp 'kmacro-keyboard-quit)
7581 (kmacro-keyboard-quit))
7582 (when completion-in-region-mode
7583 (completion-in-region-mode -1))
7584 ;; Force the next redisplay cycle to remove the "Def" indicator from
7585 ;; all the mode lines.
7586 (if defining-kbd-macro
7587 (force-mode-line-update t))
7588 (setq defining-kbd-macro nil)
7589 (let ((debug-on-quit nil))
7590 (signal 'quit nil)))
7592 (defvar buffer-quit-function nil
7593 "Function to call to \"quit\" the current buffer, or nil if none.
7594 \\[keyboard-escape-quit] calls this function when its more local actions
7595 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7597 (defun keyboard-escape-quit ()
7598 "Exit the current \"mode\" (in a generalized sense of the word).
7599 This command can exit an interactive command such as `query-replace',
7600 can clear out a prefix argument or a region,
7601 can get out of the minibuffer or other recursive edit,
7602 cancel the use of the current buffer (for special-purpose buffers),
7603 or go back to just one window (by deleting all but the selected window)."
7604 (interactive)
7605 (cond ((eq last-command 'mode-exited) nil)
7606 ((region-active-p)
7607 (deactivate-mark))
7608 ((> (minibuffer-depth) 0)
7609 (abort-recursive-edit))
7610 (current-prefix-arg
7611 nil)
7612 ((> (recursion-depth) 0)
7613 (exit-recursive-edit))
7614 (buffer-quit-function
7615 (funcall buffer-quit-function))
7616 ((not (one-window-p t))
7617 (delete-other-windows))
7618 ((string-match "^ \\*" (buffer-name (current-buffer)))
7619 (bury-buffer))))
7621 (defun play-sound-file (file &optional volume device)
7622 "Play sound stored in FILE.
7623 VOLUME and DEVICE correspond to the keywords of the sound
7624 specification for `play-sound'."
7625 (interactive "fPlay sound file: ")
7626 (let ((sound (list :file file)))
7627 (if volume
7628 (plist-put sound :volume volume))
7629 (if device
7630 (plist-put sound :device device))
7631 (push 'sound sound)
7632 (play-sound sound)))
7635 (defcustom read-mail-command 'rmail
7636 "Your preference for a mail reading package.
7637 This is used by some keybindings which support reading mail.
7638 See also `mail-user-agent' concerning sending mail."
7639 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7640 (function-item :tag "Gnus" :format "%t\n" gnus)
7641 (function-item :tag "Emacs interface to MH"
7642 :format "%t\n" mh-rmail)
7643 (function :tag "Other"))
7644 :version "21.1"
7645 :group 'mail)
7647 (defcustom mail-user-agent 'message-user-agent
7648 "Your preference for a mail composition package.
7649 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7650 outgoing email message. This variable lets you specify which
7651 mail-sending package you prefer.
7653 Valid values include:
7655 `message-user-agent' -- use the Message package.
7656 See Info node `(message)'.
7657 `sendmail-user-agent' -- use the Mail package.
7658 See Info node `(emacs)Sending Mail'.
7659 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7660 See Info node `(mh-e)'.
7661 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7662 paraphernalia if Gnus is running, particularly
7663 the Gcc: header for archiving.
7665 Additional valid symbols may be available; check with the author of
7666 your package for details. The function should return non-nil if it
7667 succeeds.
7669 See also `read-mail-command' concerning reading mail."
7670 :type '(radio (function-item :tag "Message package"
7671 :format "%t\n"
7672 message-user-agent)
7673 (function-item :tag "Mail package"
7674 :format "%t\n"
7675 sendmail-user-agent)
7676 (function-item :tag "Emacs interface to MH"
7677 :format "%t\n"
7678 mh-e-user-agent)
7679 (function-item :tag "Message with full Gnus features"
7680 :format "%t\n"
7681 gnus-user-agent)
7682 (function :tag "Other"))
7683 :version "23.2" ; sendmail->message
7684 :group 'mail)
7686 (defcustom compose-mail-user-agent-warnings t
7687 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7688 If the value of `mail-user-agent' is the default, and the user
7689 appears to have customizations applying to the old default,
7690 `compose-mail' issues a warning."
7691 :type 'boolean
7692 :version "23.2"
7693 :group 'mail)
7695 (defun rfc822-goto-eoh ()
7696 "If the buffer starts with a mail header, move point to the header's end.
7697 Otherwise, moves to `point-min'.
7698 The end of the header is the start of the next line, if there is one,
7699 else the end of the last line. This function obeys RFC822."
7700 (goto-char (point-min))
7701 (when (re-search-forward
7702 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7703 (goto-char (match-beginning 0))))
7705 ;; Used by Rmail (e.g., rmail-forward).
7706 (defvar mail-encode-mml nil
7707 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7708 the outgoing message before sending it.")
7710 (defun compose-mail (&optional to subject other-headers continue
7711 switch-function yank-action send-actions
7712 return-action)
7713 "Start composing a mail message to send.
7714 This uses the user's chosen mail composition package
7715 as selected with the variable `mail-user-agent'.
7716 The optional arguments TO and SUBJECT specify recipients
7717 and the initial Subject field, respectively.
7719 OTHER-HEADERS is an alist specifying additional
7720 header fields. Elements look like (HEADER . VALUE) where both
7721 HEADER and VALUE are strings.
7723 CONTINUE, if non-nil, says to continue editing a message already
7724 being composed. Interactively, CONTINUE is the prefix argument.
7726 SWITCH-FUNCTION, if non-nil, is a function to use to
7727 switch to and display the buffer used for mail composition.
7729 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7730 to insert the raw text of the message being replied to.
7731 It has the form (FUNCTION . ARGS). The user agent will apply
7732 FUNCTION to ARGS, to insert the raw text of the original message.
7733 \(The user agent will also run `mail-citation-hook', *after* the
7734 original text has been inserted in this way.)
7736 SEND-ACTIONS is a list of actions to call when the message is sent.
7737 Each action has the form (FUNCTION . ARGS).
7739 RETURN-ACTION, if non-nil, is an action for returning to the
7740 caller. It has the form (FUNCTION . ARGS). The function is
7741 called after the mail has been sent or put aside, and the mail
7742 buffer buried."
7743 (interactive
7744 (list nil nil nil current-prefix-arg))
7746 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7747 ;; from sendmail-user-agent to message-user-agent. Some users may
7748 ;; encounter incompatibilities. This hack tries to detect problems
7749 ;; and warn about them.
7750 (and compose-mail-user-agent-warnings
7751 (eq mail-user-agent 'message-user-agent)
7752 (let (warn-vars)
7753 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7754 mail-yank-hooks mail-archive-file-name
7755 mail-default-reply-to mail-mailing-lists
7756 mail-self-blind))
7757 (and (boundp var)
7758 (symbol-value var)
7759 (push var warn-vars)))
7760 (when warn-vars
7761 (display-warning 'mail
7762 (format-message "\
7763 The default mail mode is now Message mode.
7764 You have the following Mail mode variable%s customized:
7765 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7766 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7767 (if (> (length warn-vars) 1) "s" "")
7768 (mapconcat 'symbol-name
7769 warn-vars " "))))))
7771 (let ((function (get mail-user-agent 'composefunc)))
7772 (funcall function to subject other-headers continue switch-function
7773 yank-action send-actions return-action)))
7775 (defun compose-mail-other-window (&optional to subject other-headers continue
7776 yank-action send-actions
7777 return-action)
7778 "Like \\[compose-mail], but edit the outgoing message in another window."
7779 (interactive (list nil nil nil current-prefix-arg))
7780 (compose-mail to subject other-headers continue
7781 'switch-to-buffer-other-window yank-action send-actions
7782 return-action))
7784 (defun compose-mail-other-frame (&optional to subject other-headers continue
7785 yank-action send-actions
7786 return-action)
7787 "Like \\[compose-mail], but edit the outgoing message in another frame."
7788 (interactive (list nil nil nil current-prefix-arg))
7789 (compose-mail to subject other-headers continue
7790 'switch-to-buffer-other-frame yank-action send-actions
7791 return-action))
7794 (defvar set-variable-value-history nil
7795 "History of values entered with `set-variable'.
7797 Maximum length of the history list is determined by the value
7798 of `history-length', which see.")
7800 (defun set-variable (variable value &optional make-local)
7801 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7802 VARIABLE should be a user option variable name, a Lisp variable
7803 meant to be customized by users. You should enter VALUE in Lisp syntax,
7804 so if you want VALUE to be a string, you must surround it with doublequotes.
7805 VALUE is used literally, not evaluated.
7807 If VARIABLE has a `variable-interactive' property, that is used as if
7808 it were the arg to `interactive' (which see) to interactively read VALUE.
7810 If VARIABLE has been defined with `defcustom', then the type information
7811 in the definition is used to check that VALUE is valid.
7813 Note that this function is at heart equivalent to the basic `set' function.
7814 For a variable defined with `defcustom', it does not pay attention to
7815 any :set property that the variable might have (if you want that, use
7816 \\[customize-set-variable] instead).
7818 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7819 (interactive
7820 (let* ((default-var (variable-at-point))
7821 (var (if (custom-variable-p default-var)
7822 (read-variable (format "Set variable (default %s): " default-var)
7823 default-var)
7824 (read-variable "Set variable: ")))
7825 (minibuffer-help-form '(describe-variable var))
7826 (prop (get var 'variable-interactive))
7827 (obsolete (car (get var 'byte-obsolete-variable)))
7828 (prompt (format "Set %s %s to value: " var
7829 (cond ((local-variable-p var)
7830 "(buffer-local)")
7831 ((or current-prefix-arg
7832 (local-variable-if-set-p var))
7833 "buffer-locally")
7834 (t "globally"))))
7835 (val (progn
7836 (when obsolete
7837 (message (concat "`%S' is obsolete; "
7838 (if (symbolp obsolete) "use `%S' instead" "%s"))
7839 var obsolete)
7840 (sit-for 3))
7841 (if prop
7842 ;; Use VAR's `variable-interactive' property
7843 ;; as an interactive spec for prompting.
7844 (call-interactively `(lambda (arg)
7845 (interactive ,prop)
7846 arg))
7847 (read-from-minibuffer prompt nil
7848 read-expression-map t
7849 'set-variable-value-history
7850 (format "%S" (symbol-value var)))))))
7851 (list var val current-prefix-arg)))
7853 (and (custom-variable-p variable)
7854 (not (get variable 'custom-type))
7855 (custom-load-symbol variable))
7856 (let ((type (get variable 'custom-type)))
7857 (when type
7858 ;; Match with custom type.
7859 (require 'cus-edit)
7860 (setq type (widget-convert type))
7861 (unless (widget-apply type :match value)
7862 (user-error "Value `%S' does not match type %S of %S"
7863 value (car type) variable))))
7865 (if make-local
7866 (make-local-variable variable))
7868 (set variable value)
7870 ;; Force a thorough redisplay for the case that the variable
7871 ;; has an effect on the display, like `tab-width' has.
7872 (force-mode-line-update))
7874 ;; Define the major mode for lists of completions.
7876 (defvar completion-list-mode-map
7877 (let ((map (make-sparse-keymap)))
7878 (define-key map [mouse-2] 'choose-completion)
7879 (define-key map [follow-link] 'mouse-face)
7880 (define-key map [down-mouse-2] nil)
7881 (define-key map "\C-m" 'choose-completion)
7882 (define-key map "\e\e\e" 'delete-completion-window)
7883 (define-key map [left] 'previous-completion)
7884 (define-key map [right] 'next-completion)
7885 (define-key map [?\t] 'next-completion)
7886 (define-key map [backtab] 'previous-completion)
7887 (define-key map "q" 'quit-window)
7888 (define-key map "z" 'kill-this-buffer)
7889 map)
7890 "Local map for completion list buffers.")
7892 ;; Completion mode is suitable only for specially formatted data.
7893 (put 'completion-list-mode 'mode-class 'special)
7895 (defvar completion-reference-buffer nil
7896 "Record the buffer that was current when the completion list was requested.
7897 This is a local variable in the completion list buffer.
7898 Initial value is nil to avoid some compiler warnings.")
7900 (defvar completion-no-auto-exit nil
7901 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7902 This also applies to other functions such as `choose-completion'.")
7904 (defvar completion-base-position nil
7905 "Position of the base of the text corresponding to the shown completions.
7906 This variable is used in the *Completions* buffers.
7907 Its value is a list of the form (START END) where START is the place
7908 where the completion should be inserted and END (if non-nil) is the end
7909 of the text to replace. If END is nil, point is used instead.")
7911 (defvar completion-list-insert-choice-function #'completion--replace
7912 "Function to use to insert the text chosen in *Completions*.
7913 Called with three arguments (BEG END TEXT), it should replace the text
7914 between BEG and END with TEXT. Expected to be set buffer-locally
7915 in the *Completions* buffer.")
7917 (defvar completion-base-size nil
7918 "Number of chars before point not involved in completion.
7919 This is a local variable in the completion list buffer.
7920 It refers to the chars in the minibuffer if completing in the
7921 minibuffer, or in `completion-reference-buffer' otherwise.
7922 Only characters in the field at point are included.
7924 If nil, Emacs determines which part of the tail end of the
7925 buffer's text is involved in completion by comparing the text
7926 directly.")
7927 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7929 (defun delete-completion-window ()
7930 "Delete the completion list window.
7931 Go to the window from which completion was requested."
7932 (interactive)
7933 (let ((buf completion-reference-buffer))
7934 (if (one-window-p t)
7935 (if (window-dedicated-p) (delete-frame))
7936 (delete-window (selected-window))
7937 (if (get-buffer-window buf)
7938 (select-window (get-buffer-window buf))))))
7940 (defun previous-completion (n)
7941 "Move to the previous item in the completion list."
7942 (interactive "p")
7943 (next-completion (- n)))
7945 (defun next-completion (n)
7946 "Move to the next item in the completion list.
7947 With prefix argument N, move N items (negative N means move backward)."
7948 (interactive "p")
7949 (let ((beg (point-min)) (end (point-max)))
7950 (while (and (> n 0) (not (eobp)))
7951 ;; If in a completion, move to the end of it.
7952 (when (get-text-property (point) 'mouse-face)
7953 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7954 ;; Move to start of next one.
7955 (unless (get-text-property (point) 'mouse-face)
7956 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7957 (setq n (1- n)))
7958 (while (and (< n 0) (not (bobp)))
7959 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7960 ;; If in a completion, move to the start of it.
7961 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7962 (goto-char (previous-single-property-change
7963 (point) 'mouse-face nil beg)))
7964 ;; Move to end of the previous completion.
7965 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7966 (goto-char (previous-single-property-change
7967 (point) 'mouse-face nil beg)))
7968 ;; Move to the start of that one.
7969 (goto-char (previous-single-property-change
7970 (point) 'mouse-face nil beg))
7971 (setq n (1+ n))))))
7973 (defun choose-completion (&optional event)
7974 "Choose the completion at point.
7975 If EVENT, use EVENT's position to determine the starting position."
7976 (interactive (list last-nonmenu-event))
7977 ;; In case this is run via the mouse, give temporary modes such as
7978 ;; isearch a chance to turn off.
7979 (run-hooks 'mouse-leave-buffer-hook)
7980 (with-current-buffer (window-buffer (posn-window (event-start event)))
7981 (let ((buffer completion-reference-buffer)
7982 (base-size completion-base-size)
7983 (base-position completion-base-position)
7984 (insert-function completion-list-insert-choice-function)
7985 (choice
7986 (save-excursion
7987 (goto-char (posn-point (event-start event)))
7988 (let (beg end)
7989 (cond
7990 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7991 (setq end (point) beg (1+ (point))))
7992 ((and (not (bobp))
7993 (get-text-property (1- (point)) 'mouse-face))
7994 (setq end (1- (point)) beg (point)))
7995 (t (error "No completion here")))
7996 (setq beg (previous-single-property-change beg 'mouse-face))
7997 (setq end (or (next-single-property-change end 'mouse-face)
7998 (point-max)))
7999 (buffer-substring-no-properties beg end)))))
8001 (unless (buffer-live-p buffer)
8002 (error "Destination buffer is dead"))
8003 (quit-window nil (posn-window (event-start event)))
8005 (with-current-buffer buffer
8006 (choose-completion-string
8007 choice buffer
8008 (or base-position
8009 (when base-size
8010 ;; Someone's using old completion code that doesn't know
8011 ;; about base-position yet.
8012 (list (+ base-size (field-beginning))))
8013 ;; If all else fails, just guess.
8014 (list (choose-completion-guess-base-position choice)))
8015 insert-function)))))
8017 ;; Delete the longest partial match for STRING
8018 ;; that can be found before POINT.
8019 (defun choose-completion-guess-base-position (string)
8020 (save-excursion
8021 (let ((opoint (point))
8022 len)
8023 ;; Try moving back by the length of the string.
8024 (goto-char (max (- (point) (length string))
8025 (minibuffer-prompt-end)))
8026 ;; See how far back we were actually able to move. That is the
8027 ;; upper bound on how much we can match and delete.
8028 (setq len (- opoint (point)))
8029 (if completion-ignore-case
8030 (setq string (downcase string)))
8031 (while (and (> len 0)
8032 (let ((tail (buffer-substring (point) opoint)))
8033 (if completion-ignore-case
8034 (setq tail (downcase tail)))
8035 (not (string= tail (substring string 0 len)))))
8036 (setq len (1- len))
8037 (forward-char 1))
8038 (point))))
8040 (defun choose-completion-delete-max-match (string)
8041 (declare (obsolete choose-completion-guess-base-position "23.2"))
8042 (delete-region (choose-completion-guess-base-position string) (point)))
8044 (defvar choose-completion-string-functions nil
8045 "Functions that may override the normal insertion of a completion choice.
8046 These functions are called in order with three arguments:
8047 CHOICE - the string to insert in the buffer,
8048 BUFFER - the buffer in which the choice should be inserted,
8049 BASE-POSITION - where to insert the completion.
8051 If a function in the list returns non-nil, that function is supposed
8052 to have inserted the CHOICE in the BUFFER, and possibly exited
8053 the minibuffer; no further functions will be called.
8055 If all functions in the list return nil, that means to use
8056 the default method of inserting the completion in BUFFER.")
8058 (defun choose-completion-string (choice &optional
8059 buffer base-position insert-function)
8060 "Switch to BUFFER and insert the completion choice CHOICE.
8061 BASE-POSITION says where to insert the completion.
8062 INSERT-FUNCTION says how to insert the completion and falls
8063 back on `completion-list-insert-choice-function' when nil."
8065 ;; If BUFFER is the minibuffer, exit the minibuffer
8066 ;; unless it is reading a file name and CHOICE is a directory,
8067 ;; or completion-no-auto-exit is non-nil.
8069 ;; Some older code may call us passing `base-size' instead of
8070 ;; `base-position'. It's difficult to make any use of `base-size',
8071 ;; so we just ignore it.
8072 (unless (consp base-position)
8073 (message "Obsolete `base-size' passed to choose-completion-string")
8074 (setq base-position nil))
8076 (let* ((buffer (or buffer completion-reference-buffer))
8077 (mini-p (minibufferp buffer)))
8078 ;; If BUFFER is a minibuffer, barf unless it's the currently
8079 ;; active minibuffer.
8080 (if (and mini-p
8081 (not (and (active-minibuffer-window)
8082 (equal buffer
8083 (window-buffer (active-minibuffer-window))))))
8084 (error "Minibuffer is not active for completion")
8085 ;; Set buffer so buffer-local choose-completion-string-functions works.
8086 (set-buffer buffer)
8087 (unless (run-hook-with-args-until-success
8088 'choose-completion-string-functions
8089 ;; The fourth arg used to be `mini-p' but was useless
8090 ;; (since minibufferp can be used on the `buffer' arg)
8091 ;; and indeed unused. The last used to be `base-size', so we
8092 ;; keep it to try and avoid breaking old code.
8093 choice buffer base-position nil)
8094 ;; This remove-text-properties should be unnecessary since `choice'
8095 ;; comes from buffer-substring-no-properties.
8096 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
8097 ;; Insert the completion into the buffer where it was requested.
8098 (funcall (or insert-function completion-list-insert-choice-function)
8099 (or (car base-position) (point))
8100 (or (cadr base-position) (point))
8101 choice)
8102 ;; Update point in the window that BUFFER is showing in.
8103 (let ((window (get-buffer-window buffer t)))
8104 (set-window-point window (point)))
8105 ;; If completing for the minibuffer, exit it with this choice.
8106 (and (not completion-no-auto-exit)
8107 (minibufferp buffer)
8108 minibuffer-completion-table
8109 ;; If this is reading a file name, and the file name chosen
8110 ;; is a directory, don't exit the minibuffer.
8111 (let* ((result (buffer-substring (field-beginning) (point)))
8112 (bounds
8113 (completion-boundaries result minibuffer-completion-table
8114 minibuffer-completion-predicate
8115 "")))
8116 (if (eq (car bounds) (length result))
8117 ;; The completion chosen leads to a new set of completions
8118 ;; (e.g. it's a directory): don't exit the minibuffer yet.
8119 (let ((mini (active-minibuffer-window)))
8120 (select-window mini)
8121 (when minibuffer-auto-raise
8122 (raise-frame (window-frame mini))))
8123 (exit-minibuffer))))))))
8125 (define-derived-mode completion-list-mode nil "Completion List"
8126 "Major mode for buffers showing lists of possible completions.
8127 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
8128 to select the completion near point.
8129 Or click to select one with the mouse.
8131 \\{completion-list-mode-map}"
8132 (set (make-local-variable 'completion-base-size) nil))
8134 (defun completion-list-mode-finish ()
8135 "Finish setup of the completions buffer.
8136 Called from `temp-buffer-show-hook'."
8137 (when (eq major-mode 'completion-list-mode)
8138 (setq buffer-read-only t)))
8140 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
8143 ;; Variables and faces used in `completion-setup-function'.
8145 (defcustom completion-show-help t
8146 "Non-nil means show help message in *Completions* buffer."
8147 :type 'boolean
8148 :version "22.1"
8149 :group 'completion)
8151 ;; This function goes in completion-setup-hook, so that it is called
8152 ;; after the text of the completion list buffer is written.
8153 (defun completion-setup-function ()
8154 (let* ((mainbuf (current-buffer))
8155 (base-dir
8156 ;; FIXME: This is a bad hack. We try to set the default-directory
8157 ;; in the *Completions* buffer so that the relative file names
8158 ;; displayed there can be treated as valid file names, independently
8159 ;; from the completion context. But this suffers from many problems:
8160 ;; - It's not clear when the completions are file names. With some
8161 ;; completion tables (e.g. bzr revision specs), the listed
8162 ;; completions can mix file names and other things.
8163 ;; - It doesn't pay attention to possible quoting.
8164 ;; - With fancy completion styles, the code below will not always
8165 ;; find the right base directory.
8166 (if minibuffer-completing-file-name
8167 (file-name-as-directory
8168 (expand-file-name
8169 (buffer-substring (minibuffer-prompt-end)
8170 (- (point) (or completion-base-size 0))))))))
8171 (with-current-buffer standard-output
8172 (let ((base-size completion-base-size) ;Read before killing localvars.
8173 (base-position completion-base-position)
8174 (insert-fun completion-list-insert-choice-function))
8175 (completion-list-mode)
8176 (set (make-local-variable 'completion-base-size) base-size)
8177 (set (make-local-variable 'completion-base-position) base-position)
8178 (set (make-local-variable 'completion-list-insert-choice-function)
8179 insert-fun))
8180 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8181 (if base-dir (setq default-directory base-dir))
8182 ;; Maybe insert help string.
8183 (when completion-show-help
8184 (goto-char (point-min))
8185 (if (display-mouse-p)
8186 (insert "Click on a completion to select it.\n"))
8187 (insert (substitute-command-keys
8188 "In this buffer, type \\[choose-completion] to \
8189 select the completion near point.\n\n"))))))
8191 (add-hook 'completion-setup-hook 'completion-setup-function)
8193 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8194 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8196 (defun switch-to-completions ()
8197 "Select the completion list window."
8198 (interactive)
8199 (let ((window (or (get-buffer-window "*Completions*" 0)
8200 ;; Make sure we have a completions window.
8201 (progn (minibuffer-completion-help)
8202 (get-buffer-window "*Completions*" 0)))))
8203 (when window
8204 (select-window window)
8205 ;; In the new buffer, go to the first completion.
8206 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8207 (when (bobp)
8208 (next-completion 1)))))
8210 ;;; Support keyboard commands to turn on various modifiers.
8212 ;; These functions -- which are not commands -- each add one modifier
8213 ;; to the following event.
8215 (defun event-apply-alt-modifier (_ignore-prompt)
8216 "\\<function-key-map>Add the Alt modifier to the following event.
8217 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8218 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8219 (defun event-apply-super-modifier (_ignore-prompt)
8220 "\\<function-key-map>Add the Super modifier to the following event.
8221 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8222 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8223 (defun event-apply-hyper-modifier (_ignore-prompt)
8224 "\\<function-key-map>Add the Hyper modifier to the following event.
8225 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8226 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8227 (defun event-apply-shift-modifier (_ignore-prompt)
8228 "\\<function-key-map>Add the Shift modifier to the following event.
8229 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8230 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8231 (defun event-apply-control-modifier (_ignore-prompt)
8232 "\\<function-key-map>Add the Ctrl modifier to the following event.
8233 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8234 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8235 (defun event-apply-meta-modifier (_ignore-prompt)
8236 "\\<function-key-map>Add the Meta modifier to the following event.
8237 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8238 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8240 (defun event-apply-modifier (event symbol lshiftby prefix)
8241 "Apply a modifier flag to event EVENT.
8242 SYMBOL is the name of this modifier, as a symbol.
8243 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8244 PREFIX is the string that represents this modifier in an event type symbol."
8245 (if (numberp event)
8246 (cond ((eq symbol 'control)
8247 (if (and (<= (downcase event) ?z)
8248 (>= (downcase event) ?a))
8249 (- (downcase event) ?a -1)
8250 (if (and (<= (downcase event) ?Z)
8251 (>= (downcase event) ?A))
8252 (- (downcase event) ?A -1)
8253 (logior (lsh 1 lshiftby) event))))
8254 ((eq symbol 'shift)
8255 (if (and (<= (downcase event) ?z)
8256 (>= (downcase event) ?a))
8257 (upcase event)
8258 (logior (lsh 1 lshiftby) event)))
8260 (logior (lsh 1 lshiftby) event)))
8261 (if (memq symbol (event-modifiers event))
8262 event
8263 (let ((event-type (if (symbolp event) event (car event))))
8264 (setq event-type (intern (concat prefix (symbol-name event-type))))
8265 (if (symbolp event)
8266 event-type
8267 (cons event-type (cdr event)))))))
8269 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8270 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8271 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8272 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8273 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8274 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8276 ;;;; Keypad support.
8278 ;; Make the keypad keys act like ordinary typing keys. If people add
8279 ;; bindings for the function key symbols, then those bindings will
8280 ;; override these, so this shouldn't interfere with any existing
8281 ;; bindings.
8283 ;; Also tell read-char how to handle these keys.
8284 (mapc
8285 (lambda (keypad-normal)
8286 (let ((keypad (nth 0 keypad-normal))
8287 (normal (nth 1 keypad-normal)))
8288 (put keypad 'ascii-character normal)
8289 (define-key function-key-map (vector keypad) (vector normal))))
8290 ;; See also kp-keys bound in bindings.el.
8291 '((kp-space ?\s)
8292 (kp-tab ?\t)
8293 (kp-enter ?\r)
8294 (kp-separator ?,)
8295 (kp-equal ?=)
8296 ;; Do the same for various keys that are represented as symbols under
8297 ;; GUIs but naturally correspond to characters.
8298 (backspace 127)
8299 (delete 127)
8300 (tab ?\t)
8301 (linefeed ?\n)
8302 (clear ?\C-l)
8303 (return ?\C-m)
8304 (escape ?\e)
8307 ;;;;
8308 ;;;; forking a twin copy of a buffer.
8309 ;;;;
8311 (defvar clone-buffer-hook nil
8312 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8314 (defvar clone-indirect-buffer-hook nil
8315 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8317 (defun clone-process (process &optional newname)
8318 "Create a twin copy of PROCESS.
8319 If NEWNAME is nil, it defaults to PROCESS' name;
8320 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8321 If PROCESS is associated with a buffer, the new process will be associated
8322 with the current buffer instead.
8323 Returns nil if PROCESS has already terminated."
8324 (setq newname (or newname (process-name process)))
8325 (if (string-match "<[0-9]+>\\'" newname)
8326 (setq newname (substring newname 0 (match-beginning 0))))
8327 (when (memq (process-status process) '(run stop open))
8328 (let* ((process-connection-type (process-tty-name process))
8329 (new-process
8330 (if (memq (process-status process) '(open))
8331 (let ((args (process-contact process t)))
8332 (setq args (plist-put args :name newname))
8333 (setq args (plist-put args :buffer
8334 (if (process-buffer process)
8335 (current-buffer))))
8336 (apply 'make-network-process args))
8337 (apply 'start-process newname
8338 (if (process-buffer process) (current-buffer))
8339 (process-command process)))))
8340 (set-process-query-on-exit-flag
8341 new-process (process-query-on-exit-flag process))
8342 (set-process-inherit-coding-system-flag
8343 new-process (process-inherit-coding-system-flag process))
8344 (set-process-filter new-process (process-filter process))
8345 (set-process-sentinel new-process (process-sentinel process))
8346 (set-process-plist new-process (copy-sequence (process-plist process)))
8347 new-process)))
8349 ;; things to maybe add (currently partly covered by `funcall mode'):
8350 ;; - syntax-table
8351 ;; - overlays
8352 (defun clone-buffer (&optional newname display-flag)
8353 "Create and return a twin copy of the current buffer.
8354 Unlike an indirect buffer, the new buffer can be edited
8355 independently of the old one (if it is not read-only).
8356 NEWNAME is the name of the new buffer. It may be modified by
8357 adding or incrementing <N> at the end as necessary to create a
8358 unique buffer name. If nil, it defaults to the name of the
8359 current buffer, with the proper suffix. If DISPLAY-FLAG is
8360 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8361 clone a file-visiting buffer, or a buffer whose major mode symbol
8362 has a non-nil `no-clone' property, results in an error.
8364 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8365 current buffer with appropriate suffix. However, if a prefix
8366 argument is given, then the command prompts for NEWNAME in the
8367 minibuffer.
8369 This runs the normal hook `clone-buffer-hook' in the new buffer
8370 after it has been set up properly in other respects."
8371 (interactive
8372 (progn
8373 (if buffer-file-name
8374 (error "Cannot clone a file-visiting buffer"))
8375 (if (get major-mode 'no-clone)
8376 (error "Cannot clone a buffer in %s mode" mode-name))
8377 (list (if current-prefix-arg
8378 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8379 t)))
8380 (if buffer-file-name
8381 (error "Cannot clone a file-visiting buffer"))
8382 (if (get major-mode 'no-clone)
8383 (error "Cannot clone a buffer in %s mode" mode-name))
8384 (setq newname (or newname (buffer-name)))
8385 (if (string-match "<[0-9]+>\\'" newname)
8386 (setq newname (substring newname 0 (match-beginning 0))))
8387 (let ((buf (current-buffer))
8388 (ptmin (point-min))
8389 (ptmax (point-max))
8390 (pt (point))
8391 (mk (if mark-active (mark t)))
8392 (modified (buffer-modified-p))
8393 (mode major-mode)
8394 (lvars (buffer-local-variables))
8395 (process (get-buffer-process (current-buffer)))
8396 (new (generate-new-buffer (or newname (buffer-name)))))
8397 (save-restriction
8398 (widen)
8399 (with-current-buffer new
8400 (insert-buffer-substring buf)))
8401 (with-current-buffer new
8402 (narrow-to-region ptmin ptmax)
8403 (goto-char pt)
8404 (if mk (set-mark mk))
8405 (set-buffer-modified-p modified)
8407 ;; Clone the old buffer's process, if any.
8408 (when process (clone-process process))
8410 ;; Now set up the major mode.
8411 (funcall mode)
8413 ;; Set up other local variables.
8414 (mapc (lambda (v)
8415 (condition-case () ;in case var is read-only
8416 (if (symbolp v)
8417 (makunbound v)
8418 (set (make-local-variable (car v)) (cdr v)))
8419 (error nil)))
8420 lvars)
8422 ;; Run any hooks (typically set up by the major mode
8423 ;; for cloning to work properly).
8424 (run-hooks 'clone-buffer-hook))
8425 (if display-flag
8426 ;; Presumably the current buffer is shown in the selected frame, so
8427 ;; we want to display the clone elsewhere.
8428 (let ((same-window-regexps nil)
8429 (same-window-buffer-names))
8430 (pop-to-buffer new)))
8431 new))
8434 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8435 "Create an indirect buffer that is a twin copy of the current buffer.
8437 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8438 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8439 or if not called with a prefix arg, NEWNAME defaults to the current
8440 buffer's name. The name is modified by adding a `<N>' suffix to it
8441 or by incrementing the N in an existing suffix. Trying to clone a
8442 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8443 property results in an error.
8445 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8446 This is always done when called interactively.
8448 Optional third arg NORECORD non-nil means do not put this buffer at the
8449 front of the list of recently selected ones.
8451 Returns the newly created indirect buffer."
8452 (interactive
8453 (progn
8454 (if (get major-mode 'no-clone-indirect)
8455 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8456 (list (if current-prefix-arg
8457 (read-buffer "Name of indirect buffer: " (current-buffer)))
8458 t)))
8459 (if (get major-mode 'no-clone-indirect)
8460 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8461 (setq newname (or newname (buffer-name)))
8462 (if (string-match "<[0-9]+>\\'" newname)
8463 (setq newname (substring newname 0 (match-beginning 0))))
8464 (let* ((name (generate-new-buffer-name newname))
8465 (buffer (make-indirect-buffer (current-buffer) name t)))
8466 (with-current-buffer buffer
8467 (run-hooks 'clone-indirect-buffer-hook))
8468 (when display-flag
8469 (pop-to-buffer buffer nil norecord))
8470 buffer))
8473 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8474 "Like `clone-indirect-buffer' but display in another window."
8475 (interactive
8476 (progn
8477 (if (get major-mode 'no-clone-indirect)
8478 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8479 (list (if current-prefix-arg
8480 (read-buffer "Name of indirect buffer: " (current-buffer)))
8481 t)))
8482 (let ((pop-up-windows t))
8483 (clone-indirect-buffer newname display-flag norecord)))
8486 ;;; Handling of Backspace and Delete keys.
8488 (defcustom normal-erase-is-backspace 'maybe
8489 "Set the default behavior of the Delete and Backspace keys.
8491 If set to t, Delete key deletes forward and Backspace key deletes
8492 backward.
8494 If set to nil, both Delete and Backspace keys delete backward.
8496 If set to `maybe' (which is the default), Emacs automatically
8497 selects a behavior. On window systems, the behavior depends on
8498 the keyboard used. If the keyboard has both a Backspace key and
8499 a Delete key, and both are mapped to their usual meanings, the
8500 option's default value is set to t, so that Backspace can be used
8501 to delete backward, and Delete can be used to delete forward.
8503 If not running under a window system, customizing this option
8504 accomplishes a similar effect by mapping C-h, which is usually
8505 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8506 via `keyboard-translate'. The former functionality of C-h is
8507 available on the F1 key. You should probably not use this
8508 setting if you don't have both Backspace, Delete and F1 keys.
8510 Setting this variable with setq doesn't take effect. Programmatically,
8511 call `normal-erase-is-backspace-mode' (which see) instead."
8512 :type '(choice (const :tag "Off" nil)
8513 (const :tag "Maybe" maybe)
8514 (other :tag "On" t))
8515 :group 'editing-basics
8516 :version "21.1"
8517 :set (lambda (symbol value)
8518 ;; The fboundp is because of a problem with :set when
8519 ;; dumping Emacs. It doesn't really matter.
8520 (if (fboundp 'normal-erase-is-backspace-mode)
8521 (normal-erase-is-backspace-mode (or value 0))
8522 (set-default symbol value))))
8524 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8525 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8526 (unless frame (setq frame (selected-frame)))
8527 (with-selected-frame frame
8528 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8529 (normal-erase-is-backspace-mode
8530 (if (if (eq normal-erase-is-backspace 'maybe)
8531 (and (not noninteractive)
8532 (or (memq system-type '(ms-dos windows-nt))
8533 (memq window-system '(w32 ns))
8534 (and (memq window-system '(x))
8535 (fboundp 'x-backspace-delete-keys-p)
8536 (x-backspace-delete-keys-p))
8537 ;; If the terminal Emacs is running on has erase char
8538 ;; set to ^H, use the Backspace key for deleting
8539 ;; backward, and the Delete key for deleting forward.
8540 (and (null window-system)
8541 (eq tty-erase-char ?\^H))))
8542 normal-erase-is-backspace)
8543 1 0)))))
8545 (define-minor-mode normal-erase-is-backspace-mode
8546 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8547 With a prefix argument ARG, enable this feature if ARG is
8548 positive, and disable it otherwise. If called from Lisp, enable
8549 the mode if ARG is omitted or nil.
8551 On window systems, when this mode is on, Delete is mapped to C-d
8552 and Backspace is mapped to DEL; when this mode is off, both
8553 Delete and Backspace are mapped to DEL. (The remapping goes via
8554 `local-function-key-map', so binding Delete or Backspace in the
8555 global or local keymap will override that.)
8557 In addition, on window systems, the bindings of C-Delete, M-Delete,
8558 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8559 the global keymap in accordance with the functionality of Delete and
8560 Backspace. For example, if Delete is remapped to C-d, which deletes
8561 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8562 to DEL, which deletes backward, C-Delete is bound to
8563 `backward-kill-word'.
8565 If not running on a window system, a similar effect is accomplished by
8566 remapping C-h (normally produced by the Backspace key) and DEL via
8567 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8568 to C-d; if it's off, the keys are not remapped.
8570 When not running on a window system, and this mode is turned on, the
8571 former functionality of C-h is available on the F1 key. You should
8572 probably not turn on this mode on a text-only terminal if you don't
8573 have both Backspace, Delete and F1 keys.
8575 See also `normal-erase-is-backspace'."
8576 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8577 . (lambda (v)
8578 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8579 (if v 1 0))))
8580 (let ((enabled (eq 1 (terminal-parameter
8581 nil 'normal-erase-is-backspace))))
8583 (cond ((or (memq window-system '(x w32 ns pc))
8584 (memq system-type '(ms-dos windows-nt)))
8585 (let ((bindings
8586 `(([M-delete] [M-backspace])
8587 ([C-M-delete] [C-M-backspace])
8588 ([?\e C-delete] [?\e C-backspace]))))
8590 (if enabled
8591 (progn
8592 (define-key local-function-key-map [delete] [deletechar])
8593 (define-key local-function-key-map [kp-delete] [deletechar])
8594 (define-key local-function-key-map [backspace] [?\C-?])
8595 (dolist (b bindings)
8596 ;; Not sure if input-decode-map is really right, but
8597 ;; keyboard-translate-table (used below) only works
8598 ;; for integer events, and key-translation-table is
8599 ;; global (like the global-map, used earlier).
8600 (define-key input-decode-map (car b) nil)
8601 (define-key input-decode-map (cadr b) nil)))
8602 (define-key local-function-key-map [delete] [?\C-?])
8603 (define-key local-function-key-map [kp-delete] [?\C-?])
8604 (define-key local-function-key-map [backspace] [?\C-?])
8605 (dolist (b bindings)
8606 (define-key input-decode-map (car b) (cadr b))
8607 (define-key input-decode-map (cadr b) (car b))))))
8609 (if enabled
8610 (progn
8611 (keyboard-translate ?\C-h ?\C-?)
8612 (keyboard-translate ?\C-? ?\C-d))
8613 (keyboard-translate ?\C-h ?\C-h)
8614 (keyboard-translate ?\C-? ?\C-?))))
8616 (if (called-interactively-p 'interactive)
8617 (message "Delete key deletes %s"
8618 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8619 "forward" "backward")))))
8621 (defvar vis-mode-saved-buffer-invisibility-spec nil
8622 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8624 (define-minor-mode read-only-mode
8625 "Change whether the current buffer is read-only.
8626 With prefix argument ARG, make the buffer read-only if ARG is
8627 positive, otherwise make it writable. If buffer is read-only
8628 and `view-read-only' is non-nil, enter view mode.
8630 Do not call this from a Lisp program unless you really intend to
8631 do the same thing as the \\[read-only-mode] command, including
8632 possibly enabling or disabling View mode. Also, note that this
8633 command works by setting the variable `buffer-read-only', which
8634 does not affect read-only regions caused by text properties. To
8635 ignore read-only status in a Lisp program (whether due to text
8636 properties or buffer state), bind `inhibit-read-only' temporarily
8637 to a non-nil value."
8638 :variable buffer-read-only
8639 (cond
8640 ((and (not buffer-read-only) view-mode)
8641 (View-exit-and-edit)
8642 (make-local-variable 'view-read-only)
8643 (setq view-read-only t)) ; Must leave view mode.
8644 ((and buffer-read-only view-read-only
8645 ;; If view-mode is already active, `view-mode-enter' is a nop.
8646 (not view-mode)
8647 (not (eq (get major-mode 'mode-class) 'special)))
8648 (view-mode-enter))))
8650 (define-minor-mode visible-mode
8651 "Toggle making all invisible text temporarily visible (Visible mode).
8652 With a prefix argument ARG, enable Visible mode if ARG is
8653 positive, and disable it otherwise. If called from Lisp, enable
8654 the mode if ARG is omitted or nil.
8656 This mode works by saving the value of `buffer-invisibility-spec'
8657 and setting it to nil."
8658 :lighter " Vis"
8659 :group 'editing-basics
8660 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8661 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8662 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8663 (when visible-mode
8664 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8665 buffer-invisibility-spec)
8666 (setq buffer-invisibility-spec nil)))
8668 (defvar messages-buffer-mode-map
8669 (let ((map (make-sparse-keymap)))
8670 (set-keymap-parent map special-mode-map)
8671 (define-key map "g" nil) ; nothing to revert
8672 map))
8674 (define-derived-mode messages-buffer-mode special-mode "Messages"
8675 "Major mode used in the \"*Messages*\" buffer.")
8677 (defun messages-buffer ()
8678 "Return the \"*Messages*\" buffer.
8679 If it does not exist, create and it switch it to `messages-buffer-mode'."
8680 (or (get-buffer "*Messages*")
8681 (with-current-buffer (get-buffer-create "*Messages*")
8682 (messages-buffer-mode)
8683 (current-buffer))))
8686 ;; Minibuffer prompt stuff.
8688 ;;(defun minibuffer-prompt-modification (start end)
8689 ;; (error "You cannot modify the prompt"))
8692 ;;(defun minibuffer-prompt-insertion (start end)
8693 ;; (let ((inhibit-modification-hooks t))
8694 ;; (delete-region start end)
8695 ;; ;; Discard undo information for the text insertion itself
8696 ;; ;; and for the text deletion.above.
8697 ;; (when (consp buffer-undo-list)
8698 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8699 ;; (message "You cannot modify the prompt")))
8702 ;;(setq minibuffer-prompt-properties
8703 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8704 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8707 ;;;; Problematic external packages.
8709 ;; rms says this should be done by specifying symbols that define
8710 ;; versions together with bad values. This is therefore not as
8711 ;; flexible as it could be. See the thread:
8712 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8713 (defconst bad-packages-alist
8714 ;; Not sure exactly which semantic versions have problems.
8715 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8716 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8717 "The version of `semantic' loaded does not work in Emacs 22.
8718 It can cause constant high CPU load.
8719 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8720 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8721 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8722 ;; provided the `CUA-mode' feature. Since this is no longer true,
8723 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8724 (CUA-mode t nil
8725 "CUA-mode is now part of the standard GNU Emacs distribution,
8726 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8728 You have loaded an older version of CUA-mode which does not work
8729 correctly with this version of Emacs. You should remove the old
8730 version and use the one distributed with Emacs."))
8731 "Alist of packages known to cause problems in this version of Emacs.
8732 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8733 PACKAGE is either a regular expression to match file names, or a
8734 symbol (a feature name), like for `with-eval-after-load'.
8735 SYMBOL is either the name of a string variable, or t. Upon
8736 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8737 warning using STRING as the message.")
8739 (defun bad-package-check (package)
8740 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8741 (condition-case nil
8742 (let* ((list (assoc package bad-packages-alist))
8743 (symbol (nth 1 list)))
8744 (and list
8745 (boundp symbol)
8746 (or (eq symbol t)
8747 (and (stringp (setq symbol (eval symbol)))
8748 (string-match-p (nth 2 list) symbol)))
8749 (display-warning package (nth 3 list) :warning)))
8750 (error nil)))
8752 (dolist (elem bad-packages-alist)
8753 (let ((pkg (car elem)))
8754 (with-eval-after-load pkg
8755 (bad-package-check pkg))))
8758 ;;; Generic dispatcher commands
8760 ;; Macro `define-alternatives' is used to create generic commands.
8761 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8762 ;; that can have different alternative implementations where choosing
8763 ;; among them is exclusively a matter of user preference.
8765 ;; (define-alternatives COMMAND) creates a new interactive command
8766 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8767 ;; Typically, the user will not need to customize this variable; packages
8768 ;; wanting to add alternative implementations should use
8770 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8772 (defmacro define-alternatives (command &rest customizations)
8773 "Define the new command `COMMAND'.
8775 The argument `COMMAND' should be a symbol.
8777 Running `M-x COMMAND RET' for the first time prompts for which
8778 alternative to use and records the selected command as a custom
8779 variable.
8781 Running `C-u M-x COMMAND RET' prompts again for an alternative
8782 and overwrites the previous choice.
8784 The variable `COMMAND-alternatives' contains an alist with
8785 alternative implementations of COMMAND. `define-alternatives'
8786 does not have any effect until this variable is set.
8788 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8789 `defcustom' keywords and values to add to the declaration of
8790 `COMMAND-alternatives' (typically :group and :version)."
8791 (let* ((command-name (symbol-name command))
8792 (varalt-name (concat command-name "-alternatives"))
8793 (varalt-sym (intern varalt-name))
8794 (varimp-sym (intern (concat command-name "--implementation"))))
8795 `(progn
8797 (defcustom ,varalt-sym nil
8798 ,(format "Alist of alternative implementations for the `%s' command.
8800 Each entry must be a pair (ALTNAME . ALTFUN), where:
8801 ALTNAME - The name shown at user to describe the alternative implementation.
8802 ALTFUN - The function called to implement this alternative."
8803 command-name)
8804 :type '(alist :key-type string :value-type function)
8805 ,@customizations)
8807 (put ',varalt-sym 'definition-name ',command)
8808 (defvar ,varimp-sym nil "Internal use only.")
8810 (defun ,command (&optional arg)
8811 ,(format "Run generic command `%s'.
8812 If used for the first time, or with interactive ARG, ask the user which
8813 implementation to use for `%s'. The variable `%s'
8814 contains the list of implementations currently supported for this command."
8815 command-name command-name varalt-name)
8816 (interactive "P")
8817 (when (or arg (null ,varimp-sym))
8818 (let ((val (completing-read
8819 ,(format-message
8820 "Select implementation for command `%s': "
8821 command-name)
8822 ,varalt-sym nil t)))
8823 (unless (string-equal val "")
8824 (when (null ,varimp-sym)
8825 (message
8826 "Use C-u M-x %s RET`to select another implementation"
8827 ,command-name)
8828 (sit-for 3))
8829 (customize-save-variable ',varimp-sym
8830 (cdr (assoc-string val ,varalt-sym))))))
8831 (if ,varimp-sym
8832 (call-interactively ,varimp-sym)
8833 (message "%s" ,(format-message
8834 "No implementation selected for command `%s'"
8835 command-name)))))))
8838 ;;; Functions for changing capitalization that Do What I Mean
8839 (defun upcase-dwim (arg)
8840 "Upcase words in the region, if active; if not, upcase word at point.
8841 If the region is active, this function calls `upcase-region'.
8842 Otherwise, it calls `upcase-word', with prefix argument passed to it
8843 to upcase ARG words."
8844 (interactive "*p")
8845 (if (use-region-p)
8846 (upcase-region (region-beginning) (region-end))
8847 (upcase-word arg)))
8849 (defun downcase-dwim (arg)
8850 "Downcase words in the region, if active; if not, downcase word at point.
8851 If the region is active, this function calls `downcase-region'.
8852 Otherwise, it calls `downcase-word', with prefix argument passed to it
8853 to downcase ARG words."
8854 (interactive "*p")
8855 (if (use-region-p)
8856 (downcase-region (region-beginning) (region-end))
8857 (downcase-word arg)))
8859 (defun capitalize-dwim (arg)
8860 "Capitalize words in the region, if active; if not, capitalize word at point.
8861 If the region is active, this function calls `capitalize-region'.
8862 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8863 to capitalize ARG words."
8864 (interactive "*p")
8865 (if (use-region-p)
8866 (capitalize-region (region-beginning) (region-end))
8867 (capitalize-word arg)))
8871 (provide 'simple)
8873 ;;; simple.el ends here