Fix bug#18964
[emacs.git] / lisp / simple.el
blob203ea514e15996a0574be6e727a068ee03a7cd50
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2014 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 idle-update-delay 0.5
41 "Idle time delay before updating various things on the screen.
42 Various Emacs features that update auxiliary information when point moves
43 wait this many seconds after Emacs becomes idle before doing an update."
44 :type 'number
45 :group 'display
46 :version "22.1")
48 (defgroup killing nil
49 "Killing and yanking commands."
50 :group 'editing)
52 (defgroup paren-matching nil
53 "Highlight (un)matching of parens and expressions."
54 :group 'matching)
56 ;;; next-error support framework
58 (defgroup next-error nil
59 "`next-error' support framework."
60 :group 'compilation
61 :version "22.1")
63 (defface next-error
64 '((t (:inherit region)))
65 "Face used to highlight next error locus."
66 :group 'next-error
67 :version "22.1")
69 (defcustom next-error-highlight 0.5
70 "Highlighting of locations in selected source buffers.
71 If a number, highlight the locus in `next-error' face for the given time
72 in seconds, or until the next command is executed.
73 If t, highlight the locus until the next command is executed, or until
74 some other locus replaces it.
75 If nil, don't highlight the locus in the source buffer.
76 If `fringe-arrow', indicate the locus by the fringe arrow
77 indefinitely until some other locus replaces it."
78 :type '(choice (number :tag "Highlight for specified time")
79 (const :tag "Semipermanent highlighting" t)
80 (const :tag "No highlighting" nil)
81 (const :tag "Fringe arrow" fringe-arrow))
82 :group 'next-error
83 :version "22.1")
85 (defcustom next-error-highlight-no-select 0.5
86 "Highlighting of locations in `next-error-no-select'.
87 If number, highlight the locus in `next-error' face for given time in seconds.
88 If t, highlight the locus indefinitely until some other locus replaces it.
89 If nil, don't highlight the locus in the source buffer.
90 If `fringe-arrow', indicate the locus by the fringe arrow
91 indefinitely until some other locus replaces it."
92 :type '(choice (number :tag "Highlight for specified time")
93 (const :tag "Semipermanent highlighting" t)
94 (const :tag "No highlighting" nil)
95 (const :tag "Fringe arrow" fringe-arrow))
96 :group 'next-error
97 :version "22.1")
99 (defcustom next-error-recenter nil
100 "Display the line in the visited source file recentered as specified.
101 If non-nil, the value is passed directly to `recenter'."
102 :type '(choice (integer :tag "Line to recenter to")
103 (const :tag "Center of window" (4))
104 (const :tag "No recentering" nil))
105 :group 'next-error
106 :version "23.1")
108 (defcustom next-error-hook nil
109 "List of hook functions run by `next-error' after visiting source file."
110 :type 'hook
111 :group 'next-error)
113 (defvar next-error-highlight-timer nil)
115 (defvar next-error-overlay-arrow-position nil)
116 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
117 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
119 (defvar next-error-last-buffer nil
120 "The most recent `next-error' buffer.
121 A buffer becomes most recent when its compilation, grep, or
122 similar mode is started, or when it is used with \\[next-error]
123 or \\[compile-goto-error].")
125 (defvar next-error-function nil
126 "Function to use to find the next error in the current buffer.
127 The function is called with 2 parameters:
128 ARG is an integer specifying by how many errors to move.
129 RESET is a boolean which, if non-nil, says to go back to the beginning
130 of the errors before moving.
131 Major modes providing compile-like functionality should set this variable
132 to indicate to `next-error' that this is a candidate buffer and how
133 to navigate in it.")
134 (make-variable-buffer-local 'next-error-function)
136 (defvar next-error-move-function nil
137 "Function to use to move to an error locus.
138 It takes two arguments, a buffer position in the error buffer
139 and a buffer position in the error locus buffer.
140 The buffer for the error locus should already be current.
141 nil means use goto-char using the second argument position.")
142 (make-variable-buffer-local 'next-error-move-function)
144 (defsubst next-error-buffer-p (buffer
145 &optional avoid-current
146 extra-test-inclusive
147 extra-test-exclusive)
148 "Test if BUFFER is a `next-error' capable buffer.
150 If AVOID-CURRENT is non-nil, treat the current buffer
151 as an absolute last resort only.
153 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
154 that normally would not qualify. If it returns t, the buffer
155 in question is treated as usable.
157 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
158 that would normally be considered usable. If it returns nil,
159 that buffer is rejected."
160 (and (buffer-name buffer) ;First make sure it's live.
161 (not (and avoid-current (eq buffer (current-buffer))))
162 (with-current-buffer buffer
163 (if next-error-function ; This is the normal test.
164 ;; Optionally reject some buffers.
165 (if extra-test-exclusive
166 (funcall extra-test-exclusive)
168 ;; Optionally accept some other buffers.
169 (and extra-test-inclusive
170 (funcall extra-test-inclusive))))))
172 (defun next-error-find-buffer (&optional avoid-current
173 extra-test-inclusive
174 extra-test-exclusive)
175 "Return a `next-error' capable buffer.
177 If AVOID-CURRENT is non-nil, treat the current buffer
178 as an absolute last resort only.
180 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
181 that normally would not qualify. If it returns t, the buffer
182 in question is treated as usable.
184 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
185 that would normally be considered usable. If it returns nil,
186 that buffer is rejected."
188 ;; 1. If one window on the selected frame displays such buffer, return it.
189 (let ((window-buffers
190 (delete-dups
191 (delq nil (mapcar (lambda (w)
192 (if (next-error-buffer-p
193 (window-buffer w)
194 avoid-current
195 extra-test-inclusive extra-test-exclusive)
196 (window-buffer w)))
197 (window-list))))))
198 (if (eq (length window-buffers) 1)
199 (car window-buffers)))
200 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
201 (if (and next-error-last-buffer
202 (next-error-buffer-p next-error-last-buffer avoid-current
203 extra-test-inclusive extra-test-exclusive))
204 next-error-last-buffer)
205 ;; 3. If the current buffer is acceptable, choose it.
206 (if (next-error-buffer-p (current-buffer) avoid-current
207 extra-test-inclusive extra-test-exclusive)
208 (current-buffer))
209 ;; 4. Look for any acceptable buffer.
210 (let ((buffers (buffer-list)))
211 (while (and buffers
212 (not (next-error-buffer-p
213 (car buffers) avoid-current
214 extra-test-inclusive extra-test-exclusive)))
215 (setq buffers (cdr buffers)))
216 (car buffers))
217 ;; 5. Use the current buffer as a last resort if it qualifies,
218 ;; even despite AVOID-CURRENT.
219 (and avoid-current
220 (next-error-buffer-p (current-buffer) nil
221 extra-test-inclusive extra-test-exclusive)
222 (progn
223 (message "This is the only buffer with error message locations")
224 (current-buffer)))
225 ;; 6. Give up.
226 (error "No buffers contain error message locations")))
228 (defun next-error (&optional arg reset)
229 "Visit next `next-error' message and corresponding source code.
231 If all the error messages parsed so far have been processed already,
232 the message buffer is checked for new ones.
234 A prefix ARG specifies how many error messages to move;
235 negative means move back to previous error messages.
236 Just \\[universal-argument] as a prefix means reparse the error message buffer
237 and start at the first error.
239 The RESET argument specifies that we should restart from the beginning.
241 \\[next-error] normally uses the most recently started
242 compilation, grep, or occur buffer. It can also operate on any
243 buffer with output from the \\[compile], \\[grep] commands, or,
244 more generally, on any buffer in Compilation mode or with
245 Compilation Minor mode enabled, or any buffer in which
246 `next-error-function' is bound to an appropriate function.
247 To specify use of a particular buffer for error messages, type
248 \\[next-error] in that buffer when it is the only one displayed
249 in the current frame.
251 Once \\[next-error] has chosen the buffer for error messages, it
252 runs `next-error-hook' with `run-hooks', and stays with that buffer
253 until you use it in some other buffer which uses Compilation mode
254 or Compilation Minor mode.
256 To control which errors are matched, customize the variable
257 `compilation-error-regexp-alist'."
258 (interactive "P")
259 (if (consp arg) (setq reset t arg nil))
260 (when (setq next-error-last-buffer (next-error-find-buffer))
261 ;; we know here that next-error-function is a valid symbol we can funcall
262 (with-current-buffer next-error-last-buffer
263 (funcall next-error-function (prefix-numeric-value arg) reset)
264 (when next-error-recenter
265 (recenter next-error-recenter))
266 (run-hooks 'next-error-hook))))
268 (defun next-error-internal ()
269 "Visit the source code corresponding to the `next-error' message at point."
270 (setq next-error-last-buffer (current-buffer))
271 ;; we know here that next-error-function is a valid symbol we can funcall
272 (with-current-buffer next-error-last-buffer
273 (funcall next-error-function 0 nil)
274 (when next-error-recenter
275 (recenter next-error-recenter))
276 (run-hooks 'next-error-hook)))
278 (defalias 'goto-next-locus 'next-error)
279 (defalias 'next-match 'next-error)
281 (defun previous-error (&optional n)
282 "Visit previous `next-error' message and corresponding source code.
284 Prefix arg N says how many error messages to move backwards (or
285 forwards, if negative).
287 This operates on the output from the \\[compile] and \\[grep] commands."
288 (interactive "p")
289 (next-error (- (or n 1))))
291 (defun first-error (&optional n)
292 "Restart at the first error.
293 Visit corresponding source code.
294 With prefix arg N, visit the source code of the Nth error.
295 This operates on the output from the \\[compile] command, for instance."
296 (interactive "p")
297 (next-error n t))
299 (defun next-error-no-select (&optional n)
300 "Move point to the next error in the `next-error' buffer and highlight match.
301 Prefix arg N says how many error messages to move forwards (or
302 backwards, if negative).
303 Finds and highlights the source line like \\[next-error], but does not
304 select the source buffer."
305 (interactive "p")
306 (let ((next-error-highlight next-error-highlight-no-select))
307 (next-error n))
308 (pop-to-buffer next-error-last-buffer))
310 (defun previous-error-no-select (&optional n)
311 "Move point to the previous error in the `next-error' buffer and highlight match.
312 Prefix arg N says how many error messages to move backwards (or
313 forwards, if negative).
314 Finds and highlights the source line like \\[previous-error], but does not
315 select the source buffer."
316 (interactive "p")
317 (next-error-no-select (- (or n 1))))
319 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
320 (defvar next-error-follow-last-line nil)
322 (define-minor-mode next-error-follow-minor-mode
323 "Minor mode for compilation, occur and diff modes.
324 With a prefix argument ARG, enable mode if ARG is positive, and
325 disable it otherwise. If called from Lisp, enable mode if ARG is
326 omitted or nil.
327 When turned on, cursor motion in the compilation, grep, occur or diff
328 buffer causes automatic display of the corresponding source code location."
329 :group 'next-error :init-value nil :lighter " Fol"
330 (if (not next-error-follow-minor-mode)
331 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
332 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
333 (make-local-variable 'next-error-follow-last-line)))
335 ;; Used as a `post-command-hook' by `next-error-follow-mode'
336 ;; for the *Compilation* *grep* and *Occur* buffers.
337 (defun next-error-follow-mode-post-command-hook ()
338 (unless (equal next-error-follow-last-line (line-number-at-pos))
339 (setq next-error-follow-last-line (line-number-at-pos))
340 (condition-case nil
341 (let ((compilation-context-lines nil))
342 (setq compilation-current-error (point))
343 (next-error-no-select 0))
344 (error t))))
349 (defun fundamental-mode ()
350 "Major mode not specialized for anything in particular.
351 Other major modes are defined by comparison with this one."
352 (interactive)
353 (kill-all-local-variables)
354 (run-mode-hooks))
356 ;; Special major modes to view specially formatted data rather than files.
358 (defvar special-mode-map
359 (let ((map (make-sparse-keymap)))
360 (suppress-keymap map)
361 (define-key map "q" 'quit-window)
362 (define-key map " " 'scroll-up-command)
363 (define-key map [?\S-\ ] 'scroll-down-command)
364 (define-key map "\C-?" 'scroll-down-command)
365 (define-key map "?" 'describe-mode)
366 (define-key map "h" 'describe-mode)
367 (define-key map ">" 'end-of-buffer)
368 (define-key map "<" 'beginning-of-buffer)
369 (define-key map "g" 'revert-buffer)
370 map))
372 (put 'special-mode 'mode-class 'special)
373 (define-derived-mode special-mode nil "Special"
374 "Parent major mode from which special major modes should inherit."
375 (setq buffer-read-only t))
377 ;; Making and deleting lines.
379 (defvar self-insert-uses-region-functions nil
380 "Special hook to tell if `self-insert-command' will use the region.
381 It must be called via `run-hook-with-args-until-success' with no arguments.
382 Any `post-self-insert-command' which consumes the region should
383 register a function on this hook so that things like `delete-selection-mode'
384 can refrain from consuming the region.")
386 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
387 "Propertized string representing a hard newline character.")
389 (defun newline (&optional arg interactive)
390 "Insert a newline, and move to left margin of the new line if it's blank.
391 If option `use-hard-newlines' is non-nil, the newline is marked with the
392 text-property `hard'.
393 With ARG, insert that many newlines.
395 If `electric-indent-mode' is enabled, this indents the final new line
396 that it adds, and reindents the preceding line. To just insert
397 a newline, use \\[electric-indent-just-newline].
399 Calls `auto-fill-function' if the current column number is greater
400 than the value of `fill-column' and ARG is nil.
401 A non-nil INTERACTIVE argument means to run the `post-self-insert-hook'."
402 (interactive "*P\np")
403 (barf-if-buffer-read-only)
404 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
405 ;; Set last-command-event to tell self-insert what to insert.
406 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
407 (beforepos (point))
408 (last-command-event ?\n)
409 ;; Don't auto-fill if we have a numeric argument.
410 (auto-fill-function (if arg nil auto-fill-function))
411 (postproc
412 ;; Do the rest in post-self-insert-hook, because we want to do it
413 ;; *before* other functions on that hook.
414 (lambda ()
415 (cl-assert (eq ?\n (char-before)))
416 ;; Mark the newline(s) `hard'.
417 (if use-hard-newlines
418 (set-hard-newline-properties
419 (- (point) (prefix-numeric-value arg)) (point)))
420 ;; If the newline leaves the previous line blank, and we
421 ;; have a left margin, delete that from the blank line.
422 (save-excursion
423 (goto-char beforepos)
424 (beginning-of-line)
425 (and (looking-at "[ \t]$")
426 (> (current-left-margin) 0)
427 (delete-region (point)
428 (line-end-position))))
429 ;; Indent the line after the newline, except in one case:
430 ;; when we added the newline at the beginning of a line which
431 ;; starts a page.
432 (or was-page-start
433 (move-to-left-margin nil t)))))
434 (unwind-protect
435 (if (not interactive)
436 ;; FIXME: For non-interactive uses, many calls actually just want
437 ;; (insert "\n"), so maybe we should do just that, so as to avoid
438 ;; the risk of filling or running abbrevs unexpectedly.
439 (let ((post-self-insert-hook (list postproc)))
440 (self-insert-command (prefix-numeric-value arg)))
441 (unwind-protect
442 (progn
443 (add-hook 'post-self-insert-hook postproc)
444 (self-insert-command (prefix-numeric-value arg)))
445 ;; We first used let-binding to protect the hook, but that was naive
446 ;; since add-hook affects the symbol-default value of the variable,
447 ;; whereas the let-binding might only protect the buffer-local value.
448 (remove-hook 'post-self-insert-hook postproc)))
449 (cl-assert (not (member postproc post-self-insert-hook)))
450 (cl-assert (not (member postproc (default-value 'post-self-insert-hook))))))
451 nil)
453 (defun set-hard-newline-properties (from to)
454 (let ((sticky (get-text-property from 'rear-nonsticky)))
455 (put-text-property from to 'hard 't)
456 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
457 (if (and (listp sticky) (not (memq 'hard sticky)))
458 (put-text-property from (point) 'rear-nonsticky
459 (cons 'hard sticky)))))
461 (defun open-line (n)
462 "Insert a newline and leave point before it.
463 If there is a fill prefix and/or a `left-margin', insert them
464 on the new line if the line would have been blank.
465 With arg N, insert N newlines."
466 (interactive "*p")
467 (let* ((do-fill-prefix (and fill-prefix (bolp)))
468 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
469 (loc (point-marker))
470 ;; Don't expand an abbrev before point.
471 (abbrev-mode nil))
472 (newline n)
473 (goto-char loc)
474 (while (> n 0)
475 (cond ((bolp)
476 (if do-left-margin (indent-to (current-left-margin)))
477 (if do-fill-prefix (insert-and-inherit fill-prefix))))
478 (forward-line 1)
479 (setq n (1- n)))
480 (goto-char loc)
481 (end-of-line)))
483 (defun split-line (&optional arg)
484 "Split current line, moving portion beyond point vertically down.
485 If the current line starts with `fill-prefix', insert it on the new
486 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
488 When called from Lisp code, ARG may be a prefix string to copy."
489 (interactive "*P")
490 (skip-chars-forward " \t")
491 (let* ((col (current-column))
492 (pos (point))
493 ;; What prefix should we check for (nil means don't).
494 (prefix (cond ((stringp arg) arg)
495 (arg nil)
496 (t fill-prefix)))
497 ;; Does this line start with it?
498 (have-prfx (and prefix
499 (save-excursion
500 (beginning-of-line)
501 (looking-at (regexp-quote prefix))))))
502 (newline 1)
503 (if have-prfx (insert-and-inherit prefix))
504 (indent-to col 0)
505 (goto-char pos)))
507 (defun delete-indentation (&optional arg)
508 "Join this line to previous and fix up whitespace at join.
509 If there is a fill prefix, delete it from the beginning of this line.
510 With argument, join this line to following line."
511 (interactive "*P")
512 (beginning-of-line)
513 (if arg (forward-line 1))
514 (if (eq (preceding-char) ?\n)
515 (progn
516 (delete-region (point) (1- (point)))
517 ;; If the second line started with the fill prefix,
518 ;; delete the prefix.
519 (if (and fill-prefix
520 (<= (+ (point) (length fill-prefix)) (point-max))
521 (string= fill-prefix
522 (buffer-substring (point)
523 (+ (point) (length fill-prefix)))))
524 (delete-region (point) (+ (point) (length fill-prefix))))
525 (fixup-whitespace))))
527 (defalias 'join-line #'delete-indentation) ; easier to find
529 (defun delete-blank-lines ()
530 "On blank line, delete all surrounding blank lines, leaving just one.
531 On isolated blank line, delete that one.
532 On nonblank line, delete any immediately following blank lines."
533 (interactive "*")
534 (let (thisblank singleblank)
535 (save-excursion
536 (beginning-of-line)
537 (setq thisblank (looking-at "[ \t]*$"))
538 ;; Set singleblank if there is just one blank line here.
539 (setq singleblank
540 (and thisblank
541 (not (looking-at "[ \t]*\n[ \t]*$"))
542 (or (bobp)
543 (progn (forward-line -1)
544 (not (looking-at "[ \t]*$")))))))
545 ;; Delete preceding blank lines, and this one too if it's the only one.
546 (if thisblank
547 (progn
548 (beginning-of-line)
549 (if singleblank (forward-line 1))
550 (delete-region (point)
551 (if (re-search-backward "[^ \t\n]" nil t)
552 (progn (forward-line 1) (point))
553 (point-min)))))
554 ;; Delete following blank lines, unless the current line is blank
555 ;; and there are no following blank lines.
556 (if (not (and thisblank singleblank))
557 (save-excursion
558 (end-of-line)
559 (forward-line 1)
560 (delete-region (point)
561 (if (re-search-forward "[^ \t\n]" nil t)
562 (progn (beginning-of-line) (point))
563 (point-max)))))
564 ;; Handle the special case where point is followed by newline and eob.
565 ;; Delete the line, leaving point at eob.
566 (if (looking-at "^[ \t]*\n\\'")
567 (delete-region (point) (point-max)))))
569 (defcustom delete-trailing-lines t
570 "If non-nil, \\[delete-trailing-whitespace] deletes trailing lines.
571 Trailing lines are deleted only if `delete-trailing-whitespace'
572 is called on the entire buffer (rather than an active region)."
573 :type 'boolean
574 :group 'editing
575 :version "24.3")
577 (defun delete-trailing-whitespace (&optional start end)
578 "Delete trailing whitespace between START and END.
579 If called interactively, START and END are the start/end of the
580 region if the mark is active, or of the buffer's accessible
581 portion if the mark is inactive.
583 This command deletes whitespace characters after the last
584 non-whitespace character in each line between START and END. It
585 does not consider formfeed characters to be whitespace.
587 If this command acts on the entire buffer (i.e. if called
588 interactively with the mark inactive, or called from Lisp with
589 END nil), it also deletes all trailing lines at the end of the
590 buffer if the variable `delete-trailing-lines' is non-nil."
591 (interactive (progn
592 (barf-if-buffer-read-only)
593 (if (use-region-p)
594 (list (region-beginning) (region-end))
595 (list nil nil))))
596 (save-match-data
597 (save-excursion
598 (let ((end-marker (copy-marker (or end (point-max))))
599 (start (or start (point-min))))
600 (goto-char start)
601 (while (re-search-forward "\\s-$" end-marker t)
602 (skip-syntax-backward "-" (line-beginning-position))
603 ;; Don't delete formfeeds, even if they are considered whitespace.
604 (if (looking-at-p ".*\f")
605 (goto-char (match-end 0)))
606 (delete-region (point) (match-end 0)))
607 ;; Delete trailing empty lines.
608 (goto-char end-marker)
609 (when (and (not end)
610 delete-trailing-lines
611 ;; Really the end of buffer.
612 (= (point-max) (1+ (buffer-size)))
613 (<= (skip-chars-backward "\n") -2))
614 (delete-region (1+ (point)) end-marker))
615 (set-marker end-marker nil))))
616 ;; Return nil for the benefit of `write-file-functions'.
617 nil)
619 (defun newline-and-indent ()
620 "Insert a newline, then indent according to major mode.
621 Indentation is done using the value of `indent-line-function'.
622 In programming language modes, this is the same as TAB.
623 In some text modes, where TAB inserts a tab, this command indents to the
624 column specified by the function `current-left-margin'."
625 (interactive "*")
626 (delete-horizontal-space t)
627 (newline nil t)
628 (indent-according-to-mode))
630 (defun reindent-then-newline-and-indent ()
631 "Reindent current line, insert newline, then indent the new line.
632 Indentation of both lines is done according to the current major mode,
633 which means calling the current value of `indent-line-function'.
634 In programming language modes, this is the same as TAB.
635 In some text modes, where TAB inserts a tab, this indents to the
636 column specified by the function `current-left-margin'."
637 (interactive "*")
638 (let ((pos (point)))
639 ;; Be careful to insert the newline before indenting the line.
640 ;; Otherwise, the indentation might be wrong.
641 (newline)
642 (save-excursion
643 (goto-char pos)
644 ;; We are at EOL before the call to indent-according-to-mode, and
645 ;; after it we usually are as well, but not always. We tried to
646 ;; address it with `save-excursion' but that uses a normal marker
647 ;; whereas we need `move after insertion', so we do the save/restore
648 ;; by hand.
649 (setq pos (copy-marker pos t))
650 (indent-according-to-mode)
651 (goto-char pos)
652 ;; Remove the trailing white-space after indentation because
653 ;; indentation may introduce the whitespace.
654 (delete-horizontal-space t))
655 (indent-according-to-mode)))
657 (defcustom read-quoted-char-radix 8
658 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
659 Legitimate radix values are 8, 10 and 16."
660 :type '(choice (const 8) (const 10) (const 16))
661 :group 'editing-basics)
663 (defun read-quoted-char (&optional prompt)
664 "Like `read-char', but do not allow quitting.
665 Also, if the first character read is an octal digit,
666 we read any number of octal digits and return the
667 specified character code. Any nondigit terminates the sequence.
668 If the terminator is RET, it is discarded;
669 any other terminator is used itself as input.
671 The optional argument PROMPT specifies a string to use to prompt the user.
672 The variable `read-quoted-char-radix' controls which radix to use
673 for numeric input."
674 (let ((message-log-max nil)
675 (help-events (delq nil (mapcar (lambda (c) (unless (characterp c) c))
676 help-event-list)))
677 done (first t) (code 0) translated)
678 (while (not done)
679 (let ((inhibit-quit first)
680 ;; Don't let C-h or other help chars get the help
681 ;; message--only help function keys. See bug#16617.
682 (help-char nil)
683 (help-event-list help-events)
684 (help-form
685 "Type the special character you want to use,
686 or the octal character code.
687 RET terminates the character code and is discarded;
688 any other non-digit terminates the character code and is then used as input."))
689 (setq translated (read-key (and prompt (format "%s-" prompt))))
690 (if inhibit-quit (setq quit-flag nil)))
691 (if (integerp translated)
692 (setq translated (char-resolve-modifiers translated)))
693 (cond ((null translated))
694 ((not (integerp translated))
695 (setq unread-command-events
696 (listify-key-sequence (this-single-command-raw-keys))
697 done t))
698 ((/= (logand translated ?\M-\^@) 0)
699 ;; Turn a meta-character into a character with the 0200 bit set.
700 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
701 done t))
702 ((and (<= ?0 translated)
703 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
704 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
705 (and prompt (setq prompt (message "%s %c" prompt translated))))
706 ((and (<= ?a (downcase translated))
707 (< (downcase translated)
708 (+ ?a -10 (min 36 read-quoted-char-radix))))
709 (setq code (+ (* code read-quoted-char-radix)
710 (+ 10 (- (downcase translated) ?a))))
711 (and prompt (setq prompt (message "%s %c" prompt translated))))
712 ((and (not first) (eq translated ?\C-m))
713 (setq done t))
714 ((not first)
715 (setq unread-command-events
716 (listify-key-sequence (this-single-command-raw-keys))
717 done t))
718 (t (setq code translated
719 done t)))
720 (setq first nil))
721 code))
723 (defun quoted-insert (arg)
724 "Read next input character and insert it.
725 This is useful for inserting control characters.
726 With argument, insert ARG copies of the character.
728 If the first character you type after this command is an octal digit,
729 you should type a sequence of octal digits which specify a character code.
730 Any nondigit terminates the sequence. If the terminator is a RET,
731 it is discarded; any other terminator is used itself as input.
732 The variable `read-quoted-char-radix' specifies the radix for this feature;
733 set it to 10 or 16 to use decimal or hex instead of octal.
735 In overwrite mode, this function inserts the character anyway, and
736 does not handle octal digits specially. This means that if you use
737 overwrite as your normal editing mode, you can use this function to
738 insert characters when necessary.
740 In binary overwrite mode, this function does overwrite, and octal
741 digits are interpreted as a character code. This is intended to be
742 useful for editing binary files."
743 (interactive "*p")
744 (let* ((char
745 ;; Avoid "obsolete" warnings for translation-table-for-input.
746 (with-no-warnings
747 (let (translation-table-for-input input-method-function)
748 (if (or (not overwrite-mode)
749 (eq overwrite-mode 'overwrite-mode-binary))
750 (read-quoted-char)
751 (read-char))))))
752 ;; This used to assume character codes 0240 - 0377 stand for
753 ;; characters in some single-byte character set, and converted them
754 ;; to Emacs characters. But in 23.1 this feature is deprecated
755 ;; in favor of inserting the corresponding Unicode characters.
756 ;; (if (and enable-multibyte-characters
757 ;; (>= char ?\240)
758 ;; (<= char ?\377))
759 ;; (setq char (unibyte-char-to-multibyte char)))
760 (unless (characterp char)
761 (user-error "%s is not a valid character"
762 (key-description (vector char))))
763 (if (> arg 0)
764 (if (eq overwrite-mode 'overwrite-mode-binary)
765 (delete-char arg)))
766 (while (> arg 0)
767 (insert-and-inherit char)
768 (setq arg (1- arg)))))
770 (defun forward-to-indentation (&optional arg)
771 "Move forward ARG lines and position at first nonblank character."
772 (interactive "^p")
773 (forward-line (or arg 1))
774 (skip-chars-forward " \t"))
776 (defun backward-to-indentation (&optional arg)
777 "Move backward ARG lines and position at first nonblank character."
778 (interactive "^p")
779 (forward-line (- (or arg 1)))
780 (skip-chars-forward " \t"))
782 (defun back-to-indentation ()
783 "Move point to the first non-whitespace character on this line."
784 (interactive "^")
785 (beginning-of-line 1)
786 (skip-syntax-forward " " (line-end-position))
787 ;; Move back over chars that have whitespace syntax but have the p flag.
788 (backward-prefix-chars))
790 (defun fixup-whitespace ()
791 "Fixup white space between objects around point.
792 Leave one space or none, according to the context."
793 (interactive "*")
794 (save-excursion
795 (delete-horizontal-space)
796 (if (or (looking-at "^\\|\\s)")
797 (save-excursion (forward-char -1)
798 (looking-at "$\\|\\s(\\|\\s'")))
800 (insert ?\s))))
802 (defun delete-horizontal-space (&optional backward-only)
803 "Delete all spaces and tabs around point.
804 If BACKWARD-ONLY is non-nil, only delete them before point."
805 (interactive "*P")
806 (let ((orig-pos (point)))
807 (delete-region
808 (if backward-only
809 orig-pos
810 (progn
811 (skip-chars-forward " \t")
812 (constrain-to-field nil orig-pos t)))
813 (progn
814 (skip-chars-backward " \t")
815 (constrain-to-field nil orig-pos)))))
817 (defun just-one-space (&optional n)
818 "Delete all spaces and tabs around point, leaving one space (or N spaces).
819 If N is negative, delete newlines as well, leaving -N spaces.
820 See also `cycle-spacing'."
821 (interactive "*p")
822 (cycle-spacing n nil 'single-shot))
824 (defvar cycle-spacing--context nil
825 "Store context used in consecutive calls to `cycle-spacing' command.
826 The first time `cycle-spacing' runs, it saves in this variable:
827 its N argument, the original point position, and the original spacing
828 around point.")
830 (defun cycle-spacing (&optional n preserve-nl-back mode)
831 "Manipulate whitespace around point in a smart way.
832 In interactive use, this function behaves differently in successive
833 consecutive calls.
835 The first call in a sequence acts like `just-one-space'.
836 It deletes all spaces and tabs around point, leaving one space
837 \(or N spaces). N is the prefix argument. If N is negative,
838 it deletes newlines as well, leaving -N spaces.
839 \(If PRESERVE-NL-BACK is non-nil, it does not delete newlines before point.)
841 The second call in a sequence deletes all spaces.
843 The third call in a sequence restores the original whitespace (and point).
845 If MODE is `single-shot', it only performs the first step in the sequence.
846 If MODE is `fast' and the first step would not result in any change
847 \(i.e., there are exactly (abs N) spaces around point),
848 the function goes straight to the second step.
850 Repeatedly calling the function with different values of N starts a
851 new sequence each time."
852 (interactive "*p")
853 (let ((orig-pos (point))
854 (skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
855 (num (abs (or n 1))))
856 (skip-chars-backward (if preserve-nl-back " \t" skip-characters))
857 (constrain-to-field nil orig-pos)
858 (cond
859 ;; Command run for the first time, single-shot mode or different argument
860 ((or (eq 'single-shot mode)
861 (not (equal last-command this-command))
862 (not cycle-spacing--context)
863 (not (eq (car cycle-spacing--context) n)))
864 (let* ((start (point))
865 (num (- num (skip-chars-forward " " (+ num (point)))))
866 (mid (point))
867 (end (progn
868 (skip-chars-forward skip-characters)
869 (constrain-to-field nil orig-pos t))))
870 (setq cycle-spacing--context ;; Save for later.
871 ;; Special handling for case where there was no space at all.
872 (unless (= start end)
873 (cons n (cons orig-pos (buffer-substring start (point))))))
874 ;; If this run causes no change in buffer content, delete all spaces,
875 ;; otherwise delete all excess spaces.
876 (delete-region (if (and (eq mode 'fast) (zerop num) (= mid end))
877 start mid) end)
878 (insert (make-string num ?\s))))
880 ;; Command run for the second time.
881 ((not (equal orig-pos (point)))
882 (delete-region (point) orig-pos))
884 ;; Command run for the third time.
886 (insert (cddr cycle-spacing--context))
887 (goto-char (cadr cycle-spacing--context))
888 (setq cycle-spacing--context nil)))))
890 (defun beginning-of-buffer (&optional arg)
891 "Move point to the beginning of the buffer.
892 With numeric arg N, put point N/10 of the way from the beginning.
893 If the buffer is narrowed, this command uses the beginning of the
894 accessible part of the buffer.
896 If Transient Mark mode is disabled, leave mark at previous
897 position, unless a \\[universal-argument] prefix is supplied."
898 (declare (interactive-only "use `(goto-char (point-min))' instead."))
899 (interactive "^P")
900 (or (consp arg)
901 (region-active-p)
902 (push-mark))
903 (let ((size (- (point-max) (point-min))))
904 (goto-char (if (and arg (not (consp arg)))
905 (+ (point-min)
906 (if (> size 10000)
907 ;; Avoid overflow for large buffer sizes!
908 (* (prefix-numeric-value arg)
909 (/ size 10))
910 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
911 (point-min))))
912 (if (and arg (not (consp arg))) (forward-line 1)))
914 (defun end-of-buffer (&optional arg)
915 "Move point to the end of the buffer.
916 With numeric arg N, put point N/10 of the way from the end.
917 If the buffer is narrowed, this command uses the end of the
918 accessible part of the buffer.
920 If Transient Mark mode is disabled, leave mark at previous
921 position, unless a \\[universal-argument] prefix is supplied."
922 (declare (interactive-only "use `(goto-char (point-max))' instead."))
923 (interactive "^P")
924 (or (consp arg) (region-active-p) (push-mark))
925 (let ((size (- (point-max) (point-min))))
926 (goto-char (if (and arg (not (consp arg)))
927 (- (point-max)
928 (if (> size 10000)
929 ;; Avoid overflow for large buffer sizes!
930 (* (prefix-numeric-value arg)
931 (/ size 10))
932 (/ (* size (prefix-numeric-value arg)) 10)))
933 (point-max))))
934 ;; If we went to a place in the middle of the buffer,
935 ;; adjust it to the beginning of a line.
936 (cond ((and arg (not (consp arg))) (forward-line 1))
937 ((and (eq (current-buffer) (window-buffer))
938 (> (point) (window-end nil t)))
939 ;; If the end of the buffer is not already on the screen,
940 ;; then scroll specially to put it near, but not at, the bottom.
941 (overlay-recenter (point))
942 (recenter -3))))
944 (defcustom delete-active-region t
945 "Whether single-char deletion commands delete an active region.
946 This has an effect only if Transient Mark mode is enabled, and
947 affects `delete-forward-char' and `delete-backward-char', though
948 not `delete-char'.
950 If the value is the symbol `kill', the active region is killed
951 instead of deleted."
952 :type '(choice (const :tag "Delete active region" t)
953 (const :tag "Kill active region" kill)
954 (const :tag "Do ordinary deletion" nil))
955 :group 'killing
956 :version "24.1")
958 (defvar region-extract-function
959 (lambda (delete)
960 (when (region-beginning)
961 (if (eq delete 'delete-only)
962 (delete-region (region-beginning) (region-end))
963 (filter-buffer-substring (region-beginning) (region-end) delete))))
964 "Function to get the region's content.
965 Called with one argument DELETE.
966 If DELETE is `delete-only', then only delete the region and the return value
967 is undefined. If DELETE is nil, just return the content as a string.
968 If anything else, delete the region and return its content as a string.")
970 (defun delete-backward-char (n &optional killflag)
971 "Delete the previous N characters (following if N is negative).
972 If Transient Mark mode is enabled, the mark is active, and N is 1,
973 delete the text in the region and deactivate the mark instead.
974 To disable this, set option `delete-active-region' to nil.
976 Optional second arg KILLFLAG, if non-nil, means to kill (save in
977 kill ring) instead of delete. Interactively, N is the prefix
978 arg, and KILLFLAG is set if N is explicitly specified.
980 In Overwrite mode, single character backward deletion may replace
981 tabs with spaces so as to back over columns, unless point is at
982 the end of the line."
983 (declare (interactive-only delete-char))
984 (interactive "p\nP")
985 (unless (integerp n)
986 (signal 'wrong-type-argument (list 'integerp n)))
987 (cond ((and (use-region-p)
988 delete-active-region
989 (= n 1))
990 ;; If a region is active, kill or delete it.
991 (if (eq delete-active-region 'kill)
992 (kill-region (region-beginning) (region-end) 'region)
993 (funcall region-extract-function 'delete-only)))
994 ;; In Overwrite mode, maybe untabify while deleting
995 ((null (or (null overwrite-mode)
996 (<= n 0)
997 (memq (char-before) '(?\t ?\n))
998 (eobp)
999 (eq (char-after) ?\n)))
1000 (let ((ocol (current-column)))
1001 (delete-char (- n) killflag)
1002 (save-excursion
1003 (insert-char ?\s (- ocol (current-column)) nil))))
1004 ;; Otherwise, do simple deletion.
1005 (t (delete-char (- n) killflag))))
1007 (defun delete-forward-char (n &optional killflag)
1008 "Delete the following N characters (previous if N is negative).
1009 If Transient Mark mode is enabled, the mark is active, and N is 1,
1010 delete the text in the region and deactivate the mark instead.
1011 To disable this, set variable `delete-active-region' to nil.
1013 Optional second arg KILLFLAG non-nil means to kill (save in kill
1014 ring) instead of delete. Interactively, N is the prefix arg, and
1015 KILLFLAG is set if N was explicitly specified."
1016 (declare (interactive-only delete-char))
1017 (interactive "p\nP")
1018 (unless (integerp n)
1019 (signal 'wrong-type-argument (list 'integerp n)))
1020 (cond ((and (use-region-p)
1021 delete-active-region
1022 (= n 1))
1023 ;; If a region is active, kill or delete it.
1024 (if (eq delete-active-region 'kill)
1025 (kill-region (region-beginning) (region-end) 'region)
1026 (funcall region-extract-function 'delete-only)))
1028 ;; Otherwise, do simple deletion.
1029 (t (delete-char n killflag))))
1031 (defun mark-whole-buffer ()
1032 "Put point at beginning and mark at end of buffer.
1033 If narrowing is in effect, only uses the accessible part of the buffer.
1034 You probably should not use this function in Lisp programs;
1035 it is usually a mistake for a Lisp function to use any subroutine
1036 that uses or sets the mark."
1037 (declare (interactive-only t))
1038 (interactive)
1039 (push-mark (point))
1040 (push-mark (point-max) nil t)
1041 (goto-char (point-min)))
1044 ;; Counting lines, one way or another.
1046 (defun goto-line (line &optional buffer)
1047 "Go to LINE, counting from line 1 at beginning of buffer.
1048 If called interactively, a numeric prefix argument specifies
1049 LINE; without a numeric prefix argument, read LINE from the
1050 minibuffer.
1052 If optional argument BUFFER is non-nil, switch to that buffer and
1053 move to line LINE there. If called interactively with \\[universal-argument]
1054 as argument, BUFFER is the most recently selected other buffer.
1056 Prior to moving point, this function sets the mark (without
1057 activating it), unless Transient Mark mode is enabled and the
1058 mark is already active.
1060 This function is usually the wrong thing to use in a Lisp program.
1061 What you probably want instead is something like:
1062 (goto-char (point-min))
1063 (forward-line (1- N))
1064 If at all possible, an even better solution is to use char counts
1065 rather than line counts."
1066 (declare (interactive-only forward-line))
1067 (interactive
1068 (if (and current-prefix-arg (not (consp current-prefix-arg)))
1069 (list (prefix-numeric-value current-prefix-arg))
1070 ;; Look for a default, a number in the buffer at point.
1071 (let* ((default
1072 (save-excursion
1073 (skip-chars-backward "0-9")
1074 (if (looking-at "[0-9]")
1075 (string-to-number
1076 (buffer-substring-no-properties
1077 (point)
1078 (progn (skip-chars-forward "0-9")
1079 (point)))))))
1080 ;; Decide if we're switching buffers.
1081 (buffer
1082 (if (consp current-prefix-arg)
1083 (other-buffer (current-buffer) t)))
1084 (buffer-prompt
1085 (if buffer
1086 (concat " in " (buffer-name buffer))
1087 "")))
1088 ;; Read the argument, offering that number (if any) as default.
1089 (list (read-number (format "Goto line%s: " buffer-prompt)
1090 (list default (line-number-at-pos)))
1091 buffer))))
1092 ;; Switch to the desired buffer, one way or another.
1093 (if buffer
1094 (let ((window (get-buffer-window buffer)))
1095 (if window (select-window window)
1096 (switch-to-buffer-other-window buffer))))
1097 ;; Leave mark at previous position
1098 (or (region-active-p) (push-mark))
1099 ;; Move to the specified line number in that buffer.
1100 (save-restriction
1101 (widen)
1102 (goto-char (point-min))
1103 (if (eq selective-display t)
1104 (re-search-forward "[\n\C-m]" nil 'end (1- line))
1105 (forward-line (1- line)))))
1107 (defun count-words-region (start end &optional arg)
1108 "Count the number of words in the region.
1109 If called interactively, print a message reporting the number of
1110 lines, words, and characters in the region (whether or not the
1111 region is active); with prefix ARG, report for the entire buffer
1112 rather than the region.
1114 If called from Lisp, return the number of words between positions
1115 START and END."
1116 (interactive (if current-prefix-arg
1117 (list nil nil current-prefix-arg)
1118 (list (region-beginning) (region-end) nil)))
1119 (cond ((not (called-interactively-p 'any))
1120 (count-words start end))
1121 (arg
1122 (count-words--buffer-message))
1124 (count-words--message "Region" start end))))
1126 (defun count-words (start end)
1127 "Count words between START and END.
1128 If called interactively, START and END are normally the start and
1129 end of the buffer; but if the region is active, START and END are
1130 the start and end of the region. Print a message reporting the
1131 number of lines, words, and chars.
1133 If called from Lisp, return the number of words between START and
1134 END, without printing any message."
1135 (interactive (list nil nil))
1136 (cond ((not (called-interactively-p 'any))
1137 (let ((words 0))
1138 (save-excursion
1139 (save-restriction
1140 (narrow-to-region start end)
1141 (goto-char (point-min))
1142 (while (forward-word 1)
1143 (setq words (1+ words)))))
1144 words))
1145 ((use-region-p)
1146 (call-interactively 'count-words-region))
1148 (count-words--buffer-message))))
1150 (defun count-words--buffer-message ()
1151 (count-words--message
1152 (if (buffer-narrowed-p) "Narrowed part of buffer" "Buffer")
1153 (point-min) (point-max)))
1155 (defun count-words--message (str start end)
1156 (let ((lines (count-lines start end))
1157 (words (count-words start end))
1158 (chars (- end start)))
1159 (message "%s has %d line%s, %d word%s, and %d character%s."
1161 lines (if (= lines 1) "" "s")
1162 words (if (= words 1) "" "s")
1163 chars (if (= chars 1) "" "s"))))
1165 (define-obsolete-function-alias 'count-lines-region 'count-words-region "24.1")
1167 (defun what-line ()
1168 "Print the current buffer line number and narrowed line number of point."
1169 (interactive)
1170 (let ((start (point-min))
1171 (n (line-number-at-pos)))
1172 (if (= start 1)
1173 (message "Line %d" n)
1174 (save-excursion
1175 (save-restriction
1176 (widen)
1177 (message "line %d (narrowed line %d)"
1178 (+ n (line-number-at-pos start) -1) n))))))
1180 (defun count-lines (start end)
1181 "Return number of lines between START and END.
1182 This is usually the number of newlines between them,
1183 but can be one more if START is not equal to END
1184 and the greater of them is not at the start of a line."
1185 (save-excursion
1186 (save-restriction
1187 (narrow-to-region start end)
1188 (goto-char (point-min))
1189 (if (eq selective-display t)
1190 (save-match-data
1191 (let ((done 0))
1192 (while (re-search-forward "[\n\C-m]" nil t 40)
1193 (setq done (+ 40 done)))
1194 (while (re-search-forward "[\n\C-m]" nil t 1)
1195 (setq done (+ 1 done)))
1196 (goto-char (point-max))
1197 (if (and (/= start end)
1198 (not (bolp)))
1199 (1+ done)
1200 done)))
1201 (- (buffer-size) (forward-line (buffer-size)))))))
1203 (defun line-number-at-pos (&optional pos)
1204 "Return (narrowed) buffer line number at position POS.
1205 If POS is nil, use current buffer location.
1206 Counting starts at (point-min), so the value refers
1207 to the contents of the accessible portion of the buffer."
1208 (let ((opoint (or pos (point))) start)
1209 (save-excursion
1210 (goto-char (point-min))
1211 (setq start (point))
1212 (goto-char opoint)
1213 (forward-line 0)
1214 (1+ (count-lines start (point))))))
1216 (defun what-cursor-position (&optional detail)
1217 "Print info on cursor position (on screen and within buffer).
1218 Also describe the character after point, and give its character code
1219 in octal, decimal and hex.
1221 For a non-ASCII multibyte character, also give its encoding in the
1222 buffer's selected coding system if the coding system encodes the
1223 character safely. If the character is encoded into one byte, that
1224 code is shown in hex. If the character is encoded into more than one
1225 byte, just \"...\" is shown.
1227 In addition, with prefix argument, show details about that character
1228 in *Help* buffer. See also the command `describe-char'."
1229 (interactive "P")
1230 (let* ((char (following-char))
1231 (bidi-fixer
1232 ;; If the character is one of LRE, LRO, RLE, RLO, it will
1233 ;; start a directional embedding, which could completely
1234 ;; disrupt the rest of the line (e.g., RLO will display the
1235 ;; rest of the line right-to-left). So we put an invisible
1236 ;; PDF character after these characters, to end the
1237 ;; embedding, which eliminates any effects on the rest of
1238 ;; the line. For RLE and RLO we also append an invisible
1239 ;; LRM, to avoid reordering the following numerical
1240 ;; characters. For LRI/RLI/FSI we append a PDI.
1241 (cond ((memq char '(?\x202a ?\x202d))
1242 (propertize (string ?\x202c) 'invisible t))
1243 ((memq char '(?\x202b ?\x202e))
1244 (propertize (string ?\x202c ?\x200e) 'invisible t))
1245 ((memq char '(?\x2066 ?\x2067 ?\x2068))
1246 (propertize (string ?\x2069) 'invisible t))
1247 ;; Strong right-to-left characters cause reordering of
1248 ;; the following numerical characters which show the
1249 ;; codepoint, so append LRM to countermand that.
1250 ((memq (get-char-code-property char 'bidi-class) '(R AL))
1251 (propertize (string ?\x200e) 'invisible t))
1253 "")))
1254 (beg (point-min))
1255 (end (point-max))
1256 (pos (point))
1257 (total (buffer-size))
1258 (percent (if (> total 50000)
1259 ;; Avoid overflow from multiplying by 100!
1260 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
1261 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
1262 (hscroll (if (= (window-hscroll) 0)
1264 (format " Hscroll=%d" (window-hscroll))))
1265 (col (current-column)))
1266 (if (= pos end)
1267 (if (or (/= beg 1) (/= end (1+ total)))
1268 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1269 pos total percent beg end col hscroll)
1270 (message "point=%d of %d (EOB) column=%d%s"
1271 pos total col hscroll))
1272 (let ((coding buffer-file-coding-system)
1273 encoded encoding-msg display-prop under-display)
1274 (if (or (not coding)
1275 (eq (coding-system-type coding) t))
1276 (setq coding (default-value 'buffer-file-coding-system)))
1277 (if (eq (char-charset char) 'eight-bit)
1278 (setq encoding-msg
1279 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1280 ;; Check if the character is displayed with some `display'
1281 ;; text property. In that case, set under-display to the
1282 ;; buffer substring covered by that property.
1283 (setq display-prop (get-char-property pos 'display))
1284 (if display-prop
1285 (let ((to (or (next-single-char-property-change pos 'display)
1286 (point-max))))
1287 (if (< to (+ pos 4))
1288 (setq under-display "")
1289 (setq under-display "..."
1290 to (+ pos 4)))
1291 (setq under-display
1292 (concat (buffer-substring-no-properties pos to)
1293 under-display)))
1294 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1295 (setq encoding-msg
1296 (if display-prop
1297 (if (not (stringp display-prop))
1298 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1299 char char char under-display)
1300 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1301 char char char under-display display-prop))
1302 (if encoded
1303 (format "(%d, #o%o, #x%x, file %s)"
1304 char char char
1305 (if (> (length encoded) 1)
1306 "..."
1307 (encoded-string-description encoded coding)))
1308 (format "(%d, #o%o, #x%x)" char char char)))))
1309 (if detail
1310 ;; We show the detailed information about CHAR.
1311 (describe-char (point)))
1312 (if (or (/= beg 1) (/= end (1+ total)))
1313 (message "Char: %s%s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1314 (if (< char 256)
1315 (single-key-description char)
1316 (buffer-substring-no-properties (point) (1+ (point))))
1317 bidi-fixer
1318 encoding-msg pos total percent beg end col hscroll)
1319 (message "Char: %s%s %s point=%d of %d (%d%%) column=%d%s"
1320 (if enable-multibyte-characters
1321 (if (< char 128)
1322 (single-key-description char)
1323 (buffer-substring-no-properties (point) (1+ (point))))
1324 (single-key-description char))
1325 bidi-fixer encoding-msg pos total percent col hscroll))))))
1327 ;; Initialize read-expression-map. It is defined at C level.
1328 (defvar read-expression-map
1329 (let ((m (make-sparse-keymap)))
1330 (define-key m "\M-\t" 'completion-at-point)
1331 ;; Might as well bind TAB to completion, since inserting a TAB char is
1332 ;; much too rarely useful.
1333 (define-key m "\t" 'completion-at-point)
1334 (set-keymap-parent m minibuffer-local-map)
1337 (defun read-minibuffer (prompt &optional initial-contents)
1338 "Return a Lisp object read using the minibuffer, unevaluated.
1339 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1340 is a string to insert in the minibuffer before reading.
1341 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1342 Such arguments are used as in `read-from-minibuffer'.)"
1343 ;; Used for interactive spec `x'.
1344 (read-from-minibuffer prompt initial-contents minibuffer-local-map
1345 t 'minibuffer-history))
1347 (defun eval-minibuffer (prompt &optional initial-contents)
1348 "Return value of Lisp expression read using the minibuffer.
1349 Prompt with PROMPT. If non-nil, optional second arg INITIAL-CONTENTS
1350 is a string to insert in the minibuffer before reading.
1351 \(INITIAL-CONTENTS can also be a cons of a string and an integer.
1352 Such arguments are used as in `read-from-minibuffer'.)"
1353 ;; Used for interactive spec `X'.
1354 (eval (read--expression prompt initial-contents)))
1356 (defvar minibuffer-completing-symbol nil
1357 "Non-nil means completing a Lisp symbol in the minibuffer.")
1358 (make-obsolete-variable 'minibuffer-completing-symbol nil "24.1" 'get)
1360 (defvar minibuffer-default nil
1361 "The current default value or list of default values in the minibuffer.
1362 The functions `read-from-minibuffer' and `completing-read' bind
1363 this variable locally.")
1365 (defcustom eval-expression-print-level 4
1366 "Value for `print-level' while printing value in `eval-expression'.
1367 A value of nil means no limit."
1368 :group 'lisp
1369 :type '(choice (const :tag "No Limit" nil) integer)
1370 :version "21.1")
1372 (defcustom eval-expression-print-length 12
1373 "Value for `print-length' while printing value in `eval-expression'.
1374 A value of nil means no limit."
1375 :group 'lisp
1376 :type '(choice (const :tag "No Limit" nil) integer)
1377 :version "21.1")
1379 (defcustom eval-expression-debug-on-error t
1380 "If non-nil set `debug-on-error' to t in `eval-expression'.
1381 If nil, don't change the value of `debug-on-error'."
1382 :group 'lisp
1383 :type 'boolean
1384 :version "21.1")
1386 (defun eval-expression-print-format (value)
1387 "Format VALUE as a result of evaluated expression.
1388 Return a formatted string which is displayed in the echo area
1389 in addition to the value printed by prin1 in functions which
1390 display the result of expression evaluation."
1391 (if (and (integerp value)
1392 (or (eq standard-output t)
1393 (zerop (prefix-numeric-value current-prefix-arg))))
1394 (let ((char-string
1395 (if (and (characterp value)
1396 (char-displayable-p value))
1397 (prin1-char value))))
1398 (if char-string
1399 (format " (#o%o, #x%x, %s)" value value char-string)
1400 (format " (#o%o, #x%x)" value value)))))
1402 (defvar eval-expression-minibuffer-setup-hook nil
1403 "Hook run by `eval-expression' when entering the minibuffer.")
1405 (defun read--expression (prompt &optional initial-contents)
1406 (let ((minibuffer-completing-symbol t))
1407 (minibuffer-with-setup-hook
1408 (lambda ()
1409 ;; FIXME: call emacs-lisp-mode?
1410 (setq-local eldoc-documentation-function
1411 #'elisp-eldoc-documentation-function)
1412 (add-hook 'completion-at-point-functions
1413 #'elisp-completion-at-point nil t)
1414 (run-hooks 'eval-expression-minibuffer-setup-hook))
1415 (read-from-minibuffer prompt initial-contents
1416 read-expression-map t
1417 'read-expression-history))))
1419 ;; We define this, rather than making `eval' interactive,
1420 ;; for the sake of completion of names like eval-region, eval-buffer.
1421 (defun eval-expression (exp &optional insert-value)
1422 "Evaluate EXP and print value in the echo area.
1423 When called interactively, read an Emacs Lisp expression and evaluate it.
1424 Value is also consed on to front of the variable `values'.
1425 Optional argument INSERT-VALUE non-nil (interactively, with prefix
1426 argument) means insert the result into the current buffer instead of
1427 printing it in the echo area.
1429 Normally, this function truncates long output according to the value
1430 of the variables `eval-expression-print-length' and
1431 `eval-expression-print-level'. With a prefix argument of zero,
1432 however, there is no such truncation. Such a prefix argument
1433 also causes integers to be printed in several additional formats
1434 \(octal, hexadecimal, and character).
1436 Runs the hook `eval-expression-minibuffer-setup-hook' on entering the
1437 minibuffer.
1439 If `eval-expression-debug-on-error' is non-nil, which is the default,
1440 this command arranges for all errors to enter the debugger."
1441 (interactive
1442 (list (read--expression "Eval: ")
1443 current-prefix-arg))
1445 (if (null eval-expression-debug-on-error)
1446 (push (eval exp lexical-binding) values)
1447 (let ((old-value (make-symbol "t")) new-value)
1448 ;; Bind debug-on-error to something unique so that we can
1449 ;; detect when evalled code changes it.
1450 (let ((debug-on-error old-value))
1451 (push (eval exp lexical-binding) values)
1452 (setq new-value debug-on-error))
1453 ;; If evalled code has changed the value of debug-on-error,
1454 ;; propagate that change to the global binding.
1455 (unless (eq old-value new-value)
1456 (setq debug-on-error new-value))))
1458 (let ((print-length (and (not (zerop (prefix-numeric-value insert-value)))
1459 eval-expression-print-length))
1460 (print-level (and (not (zerop (prefix-numeric-value insert-value)))
1461 eval-expression-print-level))
1462 (deactivate-mark))
1463 (if insert-value
1464 (with-no-warnings
1465 (let ((standard-output (current-buffer)))
1466 (prog1
1467 (prin1 (car values))
1468 (when (zerop (prefix-numeric-value insert-value))
1469 (let ((str (eval-expression-print-format (car values))))
1470 (if str (princ str)))))))
1471 (prog1
1472 (prin1 (car values) t)
1473 (let ((str (eval-expression-print-format (car values))))
1474 (if str (princ str t)))))))
1476 (defun edit-and-eval-command (prompt command)
1477 "Prompting with PROMPT, let user edit COMMAND and eval result.
1478 COMMAND is a Lisp expression. Let user edit that expression in
1479 the minibuffer, then read and evaluate the result."
1480 (let ((command
1481 (let ((print-level nil)
1482 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1483 (unwind-protect
1484 (read-from-minibuffer prompt
1485 (prin1-to-string command)
1486 read-expression-map t
1487 'command-history)
1488 ;; If command was added to command-history as a string,
1489 ;; get rid of that. We want only evaluable expressions there.
1490 (if (stringp (car command-history))
1491 (setq command-history (cdr command-history)))))))
1493 ;; If command to be redone does not match front of history,
1494 ;; add it to the history.
1495 (or (equal command (car command-history))
1496 (setq command-history (cons command command-history)))
1497 (eval command)))
1499 (defun repeat-complex-command (arg)
1500 "Edit and re-evaluate last complex command, or ARGth from last.
1501 A complex command is one which used the minibuffer.
1502 The command is placed in the minibuffer as a Lisp form for editing.
1503 The result is executed, repeating the command as changed.
1504 If the command has been changed or is not the most recent previous
1505 command it is added to the front of the command history.
1506 You can use the minibuffer history commands \
1507 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1508 to get different commands to edit and resubmit."
1509 (interactive "p")
1510 (let ((elt (nth (1- arg) command-history))
1511 newcmd)
1512 (if elt
1513 (progn
1514 (setq newcmd
1515 (let ((print-level nil)
1516 (minibuffer-history-position arg)
1517 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1518 (unwind-protect
1519 (read-from-minibuffer
1520 "Redo: " (prin1-to-string elt) read-expression-map t
1521 (cons 'command-history arg))
1523 ;; If command was added to command-history as a
1524 ;; string, get rid of that. We want only
1525 ;; evaluable expressions there.
1526 (if (stringp (car command-history))
1527 (setq command-history (cdr command-history))))))
1529 ;; If command to be redone does not match front of history,
1530 ;; add it to the history.
1531 (or (equal newcmd (car command-history))
1532 (setq command-history (cons newcmd command-history)))
1533 (apply #'funcall-interactively
1534 (car newcmd)
1535 (mapcar (lambda (e) (eval e t)) (cdr newcmd))))
1536 (if command-history
1537 (error "Argument %d is beyond length of command history" arg)
1538 (error "There are no previous complex commands to repeat")))))
1541 (defvar extended-command-history nil)
1542 (defvar execute-extended-command--last-typed nil)
1544 (defun read-extended-command ()
1545 "Read command name to invoke in `execute-extended-command'."
1546 (minibuffer-with-setup-hook
1547 (lambda ()
1548 (add-hook 'post-self-insert-hook
1549 (lambda ()
1550 (setq execute-extended-command--last-typed
1551 (minibuffer-contents)))
1552 nil 'local)
1553 (set (make-local-variable 'minibuffer-default-add-function)
1554 (lambda ()
1555 ;; Get a command name at point in the original buffer
1556 ;; to propose it after M-n.
1557 (with-current-buffer (window-buffer (minibuffer-selected-window))
1558 (and (commandp (function-called-at-point))
1559 (format "%S" (function-called-at-point)))))))
1560 ;; Read a string, completing from and restricting to the set of
1561 ;; all defined commands. Don't provide any initial input.
1562 ;; Save the command read on the extended-command history list.
1563 (completing-read
1564 (concat (cond
1565 ((eq current-prefix-arg '-) "- ")
1566 ((and (consp current-prefix-arg)
1567 (eq (car current-prefix-arg) 4)) "C-u ")
1568 ((and (consp current-prefix-arg)
1569 (integerp (car current-prefix-arg)))
1570 (format "%d " (car current-prefix-arg)))
1571 ((integerp current-prefix-arg)
1572 (format "%d " current-prefix-arg)))
1573 ;; This isn't strictly correct if `execute-extended-command'
1574 ;; is bound to anything else (e.g. [menu]).
1575 ;; It could use (key-description (this-single-command-keys)),
1576 ;; but actually a prompt other than "M-x" would be confusing,
1577 ;; because "M-x" is a well-known prompt to read a command
1578 ;; and it serves as a shorthand for "Extended command: ".
1579 "M-x ")
1580 (lambda (string pred action)
1581 (let ((pred
1582 (if (memq action '(nil t))
1583 ;; Exclude obsolete commands from completions.
1584 (lambda (sym)
1585 (and (funcall pred sym)
1586 (or (equal string (symbol-name sym))
1587 (not (get sym 'byte-obsolete-info)))))
1588 pred)))
1589 (complete-with-action action obarray string pred)))
1590 #'commandp t nil 'extended-command-history)))
1592 (defcustom suggest-key-bindings t
1593 "Non-nil means show the equivalent key-binding when M-x command has one.
1594 The value can be a length of time to show the message for.
1595 If the value is non-nil and not a number, we wait 2 seconds."
1596 :group 'keyboard
1597 :type '(choice (const :tag "off" nil)
1598 (integer :tag "time" 2)
1599 (other :tag "on")))
1601 (defun execute-extended-command--shorter-1 (name length)
1602 (cond
1603 ((zerop length) (list ""))
1604 ((equal name "") nil)
1606 (nconc (mapcar (lambda (s) (concat (substring name 0 1) s))
1607 (execute-extended-command--shorter-1
1608 (substring name 1) (1- length)))
1609 (when (string-match "\\`\\(-\\)?[^-]*" name)
1610 (execute-extended-command--shorter-1
1611 (substring name (match-end 0)) length))))))
1613 (defun execute-extended-command--shorter (name typed)
1614 (let ((candidates '())
1615 (max (length (or typed name)))
1616 (len 1)
1617 binding)
1618 (while (and (not binding)
1619 (progn
1620 (unless candidates
1621 (setq len (1+ len))
1622 (setq candidates (execute-extended-command--shorter-1
1623 name len)))
1624 (< len max)))
1625 (let ((candidate (pop candidates)))
1626 (when (equal name
1627 (car-safe (completion-try-completion
1628 candidate obarray 'commandp len)))
1629 (setq binding candidate))))
1630 binding))
1632 (defun execute-extended-command (prefixarg &optional command-name typed)
1633 ;; Based on Fexecute_extended_command in keyboard.c of Emacs.
1634 ;; Aaron S. Hawley <aaron.s.hawley(at)gmail.com> 2009-08-24
1635 "Read a command name, then read the arguments and call the command.
1636 To pass a prefix argument to the command you are
1637 invoking, give a prefix argument to `execute-extended-command'."
1638 (declare (interactive-only command-execute))
1639 ;; FIXME: Remember the actual text typed by the user before completion,
1640 ;; so that we don't later on suggest the same shortening.
1641 (interactive
1642 (let ((execute-extended-command--last-typed nil))
1643 (list current-prefix-arg
1644 (read-extended-command)
1645 execute-extended-command--last-typed)))
1646 ;; Emacs<24 calling-convention was with a single `prefixarg' argument.
1647 (unless command-name
1648 (let ((current-prefix-arg prefixarg) ; for prompt
1649 (execute-extended-command--last-typed nil))
1650 (setq command-name (read-extended-command))
1651 (setq typed execute-extended-command--last-typed)))
1652 (let* ((function (and (stringp command-name) (intern-soft command-name)))
1653 (binding (and suggest-key-bindings
1654 (not executing-kbd-macro)
1655 (where-is-internal function overriding-local-map t))))
1656 (unless (commandp function)
1657 (error "`%s' is not a valid command name" command-name))
1658 (setq this-command function)
1659 ;; Normally `real-this-command' should never be changed, but here we really
1660 ;; want to pretend that M-x <cmd> RET is nothing more than a "key
1661 ;; binding" for <cmd>, so the command the user really wanted to run is
1662 ;; `function' and not `execute-extended-command'. The difference is
1663 ;; visible in cases such as M-x <cmd> RET and then C-x z (bug#11506).
1664 (setq real-this-command function)
1665 (let ((prefix-arg prefixarg))
1666 (command-execute function 'record))
1667 ;; If enabled, show which key runs this command.
1668 ;; (when binding
1669 ;; But first wait, and skip the message if there is input.
1670 (let* ((waited
1671 ;; If this command displayed something in the echo area;
1672 ;; wait a few seconds, then display our suggestion message.
1673 ;; FIXME: Wait *after* running post-command-hook!
1674 ;; FIXME: Don't wait if execute-extended-command--shorter won't
1675 ;; find a better answer anyway!
1676 (sit-for (cond
1677 ((zerop (length (current-message))) 0)
1678 ((numberp suggest-key-bindings) suggest-key-bindings)
1679 (t 2)))))
1680 (when (and waited (not (consp unread-command-events)))
1681 (unless (or binding executing-kbd-macro (not (symbolp function))
1682 (<= (length (symbol-name function)) 2))
1683 ;; There's no binding for CMD. Let's try and find the shortest
1684 ;; string to use in M-x.
1685 ;; FIXME: Can be slow. Cache it maybe?
1686 (while-no-input
1687 (setq binding (execute-extended-command--shorter
1688 (symbol-name function) typed))))
1689 (when binding
1690 (with-temp-message
1691 (format "You can run the command `%s' with %s"
1692 function
1693 (if (stringp binding)
1694 (concat "M-x " binding " RET")
1695 (key-description binding)))
1696 (sit-for (if (numberp suggest-key-bindings)
1697 suggest-key-bindings
1698 2))))))))
1700 (defun command-execute (cmd &optional record-flag keys special)
1701 ;; BEWARE: Called directly from the C code.
1702 "Execute CMD as an editor command.
1703 CMD must be a symbol that satisfies the `commandp' predicate.
1704 Optional second arg RECORD-FLAG non-nil
1705 means unconditionally put this command in the variable `command-history'.
1706 Otherwise, that is done only if an arg is read using the minibuffer.
1707 The argument KEYS specifies the value to use instead of (this-command-keys)
1708 when reading the arguments; if it is nil, (this-command-keys) is used.
1709 The argument SPECIAL, if non-nil, means that this command is executing
1710 a special event, so ignore the prefix argument and don't clear it."
1711 (setq debug-on-next-call nil)
1712 (let ((prefixarg (unless special
1713 (prog1 prefix-arg
1714 (setq current-prefix-arg prefix-arg)
1715 (setq prefix-arg nil)))))
1716 (if (and (symbolp cmd)
1717 (get cmd 'disabled)
1718 disabled-command-function)
1719 ;; FIXME: Weird calling convention!
1720 (run-hooks 'disabled-command-function)
1721 (let ((final cmd))
1722 (while
1723 (progn
1724 (setq final (indirect-function final))
1725 (if (autoloadp final)
1726 (setq final (autoload-do-load final cmd)))))
1727 (cond
1728 ((arrayp final)
1729 ;; If requested, place the macro in the command history. For
1730 ;; other sorts of commands, call-interactively takes care of this.
1731 (when record-flag
1732 (push `(execute-kbd-macro ,final ,prefixarg) command-history)
1733 ;; Don't keep command history around forever.
1734 (when (and (numberp history-length) (> history-length 0))
1735 (let ((cell (nthcdr history-length command-history)))
1736 (if (consp cell) (setcdr cell nil)))))
1737 (execute-kbd-macro final prefixarg))
1739 ;; Pass `cmd' rather than `final', for the backtrace's sake.
1740 (prog1 (call-interactively cmd record-flag keys)
1741 (when (and (symbolp cmd)
1742 (get cmd 'byte-obsolete-info)
1743 (not (get cmd 'command-execute-obsolete-warned)))
1744 (put cmd 'command-execute-obsolete-warned t)
1745 (message "%s" (macroexp--obsolete-warning
1746 cmd (get cmd 'byte-obsolete-info) "command"))))))))))
1748 (defvar minibuffer-history nil
1749 "Default minibuffer history list.
1750 This is used for all minibuffer input
1751 except when an alternate history list is specified.
1753 Maximum length of the history list is determined by the value
1754 of `history-length', which see.")
1755 (defvar minibuffer-history-sexp-flag nil
1756 "Control whether history list elements are expressions or strings.
1757 If the value of this variable equals current minibuffer depth,
1758 they are expressions; otherwise they are strings.
1759 \(That convention is designed to do the right thing for
1760 recursive uses of the minibuffer.)")
1761 (setq minibuffer-history-variable 'minibuffer-history)
1762 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1763 (defvar minibuffer-history-search-history nil)
1765 (defvar minibuffer-text-before-history nil
1766 "Text that was in this minibuffer before any history commands.
1767 This is nil if there have not yet been any history commands
1768 in this use of the minibuffer.")
1770 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1772 (defun minibuffer-history-initialize ()
1773 (setq minibuffer-text-before-history nil))
1775 (defun minibuffer-avoid-prompt (_new _old)
1776 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1777 (constrain-to-field nil (point-max)))
1779 (defcustom minibuffer-history-case-insensitive-variables nil
1780 "Minibuffer history variables for which matching should ignore case.
1781 If a history variable is a member of this list, then the
1782 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1783 commands ignore case when searching it, regardless of `case-fold-search'."
1784 :type '(repeat variable)
1785 :group 'minibuffer)
1787 (defun previous-matching-history-element (regexp n)
1788 "Find the previous history element that matches REGEXP.
1789 \(Previous history elements refer to earlier actions.)
1790 With prefix argument N, search for Nth previous match.
1791 If N is negative, find the next or Nth next match.
1792 Normally, history elements are matched case-insensitively if
1793 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1794 makes the search case-sensitive.
1795 See also `minibuffer-history-case-insensitive-variables'."
1796 (interactive
1797 (let* ((enable-recursive-minibuffers t)
1798 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1800 minibuffer-local-map
1802 'minibuffer-history-search-history
1803 (car minibuffer-history-search-history))))
1804 ;; Use the last regexp specified, by default, if input is empty.
1805 (list (if (string= regexp "")
1806 (if minibuffer-history-search-history
1807 (car minibuffer-history-search-history)
1808 (user-error "No previous history search regexp"))
1809 regexp)
1810 (prefix-numeric-value current-prefix-arg))))
1811 (unless (zerop n)
1812 (if (and (zerop minibuffer-history-position)
1813 (null minibuffer-text-before-history))
1814 (setq minibuffer-text-before-history
1815 (minibuffer-contents-no-properties)))
1816 (let ((history (symbol-value minibuffer-history-variable))
1817 (case-fold-search
1818 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1819 ;; On some systems, ignore case for file names.
1820 (if (memq minibuffer-history-variable
1821 minibuffer-history-case-insensitive-variables)
1823 ;; Respect the user's setting for case-fold-search:
1824 case-fold-search)
1825 nil))
1826 prevpos
1827 match-string
1828 match-offset
1829 (pos minibuffer-history-position))
1830 (while (/= n 0)
1831 (setq prevpos pos)
1832 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1833 (when (= pos prevpos)
1834 (user-error (if (= pos 1)
1835 "No later matching history item"
1836 "No earlier matching history item")))
1837 (setq match-string
1838 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1839 (let ((print-level nil))
1840 (prin1-to-string (nth (1- pos) history)))
1841 (nth (1- pos) history)))
1842 (setq match-offset
1843 (if (< n 0)
1844 (and (string-match regexp match-string)
1845 (match-end 0))
1846 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1847 (match-beginning 1))))
1848 (when match-offset
1849 (setq n (+ n (if (< n 0) 1 -1)))))
1850 (setq minibuffer-history-position pos)
1851 (goto-char (point-max))
1852 (delete-minibuffer-contents)
1853 (insert match-string)
1854 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1855 (if (memq (car (car command-history)) '(previous-matching-history-element
1856 next-matching-history-element))
1857 (setq command-history (cdr command-history))))
1859 (defun next-matching-history-element (regexp n)
1860 "Find the next history element that matches REGEXP.
1861 \(The next history element refers to a more recent action.)
1862 With prefix argument N, search for Nth next match.
1863 If N is negative, find the previous or Nth previous match.
1864 Normally, history elements are matched case-insensitively if
1865 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1866 makes the search case-sensitive."
1867 (interactive
1868 (let* ((enable-recursive-minibuffers t)
1869 (regexp (read-from-minibuffer "Next element matching (regexp): "
1871 minibuffer-local-map
1873 'minibuffer-history-search-history
1874 (car minibuffer-history-search-history))))
1875 ;; Use the last regexp specified, by default, if input is empty.
1876 (list (if (string= regexp "")
1877 (if minibuffer-history-search-history
1878 (car minibuffer-history-search-history)
1879 (user-error "No previous history search regexp"))
1880 regexp)
1881 (prefix-numeric-value current-prefix-arg))))
1882 (previous-matching-history-element regexp (- n)))
1884 (defvar minibuffer-temporary-goal-position nil)
1886 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1887 "Function run by `goto-history-element' before consuming default values.
1888 This is useful to dynamically add more elements to the list of default values
1889 when `goto-history-element' reaches the end of this list.
1890 Before calling this function `goto-history-element' sets the variable
1891 `minibuffer-default-add-done' to t, so it will call this function only
1892 once. In special cases, when this function needs to be called more
1893 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1894 overriding the setting of this variable to t in `goto-history-element'.")
1896 (defvar minibuffer-default-add-done nil
1897 "When nil, add more elements to the end of the list of default values.
1898 The value nil causes `goto-history-element' to add more elements to
1899 the list of defaults when it reaches the end of this list. It does
1900 this by calling a function defined by `minibuffer-default-add-function'.")
1902 (make-variable-buffer-local 'minibuffer-default-add-done)
1904 (defun minibuffer-default-add-completions ()
1905 "Return a list of all completions without the default value.
1906 This function is used to add all elements of the completion table to
1907 the end of the list of defaults just after the default value."
1908 (let ((def minibuffer-default)
1909 (all (all-completions ""
1910 minibuffer-completion-table
1911 minibuffer-completion-predicate)))
1912 (if (listp def)
1913 (append def all)
1914 (cons def (delete def all)))))
1916 (defun goto-history-element (nabs)
1917 "Puts element of the minibuffer history in the minibuffer.
1918 The argument NABS specifies the absolute history position."
1919 (interactive "p")
1920 (when (and (not minibuffer-default-add-done)
1921 (functionp minibuffer-default-add-function)
1922 (< nabs (- (if (listp minibuffer-default)
1923 (length minibuffer-default)
1924 1))))
1925 (setq minibuffer-default-add-done t
1926 minibuffer-default (funcall minibuffer-default-add-function)))
1927 (let ((minimum (if minibuffer-default
1928 (- (if (listp minibuffer-default)
1929 (length minibuffer-default)
1932 elt minibuffer-returned-to-present)
1933 (if (and (zerop minibuffer-history-position)
1934 (null minibuffer-text-before-history))
1935 (setq minibuffer-text-before-history
1936 (minibuffer-contents-no-properties)))
1937 (if (< nabs minimum)
1938 (user-error (if minibuffer-default
1939 "End of defaults; no next item"
1940 "End of history; no default available")))
1941 (if (> nabs (length (symbol-value minibuffer-history-variable)))
1942 (user-error "Beginning of history; no preceding item"))
1943 (unless (memq last-command '(next-history-element
1944 previous-history-element))
1945 (let ((prompt-end (minibuffer-prompt-end)))
1946 (set (make-local-variable 'minibuffer-temporary-goal-position)
1947 (cond ((<= (point) prompt-end) prompt-end)
1948 ((eobp) nil)
1949 (t (point))))))
1950 (goto-char (point-max))
1951 (delete-minibuffer-contents)
1952 (setq minibuffer-history-position nabs)
1953 (cond ((< nabs 0)
1954 (setq elt (if (listp minibuffer-default)
1955 (nth (1- (abs nabs)) minibuffer-default)
1956 minibuffer-default)))
1957 ((= nabs 0)
1958 (setq elt (or minibuffer-text-before-history ""))
1959 (setq minibuffer-returned-to-present t)
1960 (setq minibuffer-text-before-history nil))
1961 (t (setq elt (nth (1- minibuffer-history-position)
1962 (symbol-value minibuffer-history-variable)))))
1963 (insert
1964 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1965 (not minibuffer-returned-to-present))
1966 (let ((print-level nil))
1967 (prin1-to-string elt))
1968 elt))
1969 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
1971 (defun next-history-element (n)
1972 "Puts next element of the minibuffer history in the minibuffer.
1973 With argument N, it uses the Nth following element."
1974 (interactive "p")
1975 (or (zerop n)
1976 (goto-history-element (- minibuffer-history-position n))))
1978 (defun previous-history-element (n)
1979 "Puts previous element of the minibuffer history in the minibuffer.
1980 With argument N, it uses the Nth previous element."
1981 (interactive "p")
1982 (or (zerop n)
1983 (goto-history-element (+ minibuffer-history-position n))))
1985 (defun next-complete-history-element (n)
1986 "Get next history element which completes the minibuffer before the point.
1987 The contents of the minibuffer after the point are deleted, and replaced
1988 by the new completion."
1989 (interactive "p")
1990 (let ((point-at-start (point)))
1991 (next-matching-history-element
1992 (concat
1993 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1995 ;; next-matching-history-element always puts us at (point-min).
1996 ;; Move to the position we were at before changing the buffer contents.
1997 ;; This is still sensible, because the text before point has not changed.
1998 (goto-char point-at-start)))
2000 (defun previous-complete-history-element (n)
2002 Get previous history element which completes the minibuffer before the point.
2003 The contents of the minibuffer after the point are deleted, and replaced
2004 by the new completion."
2005 (interactive "p")
2006 (next-complete-history-element (- n)))
2008 ;; For compatibility with the old subr of the same name.
2009 (defun minibuffer-prompt-width ()
2010 "Return the display width of the minibuffer prompt.
2011 Return 0 if current buffer is not a minibuffer."
2012 ;; Return the width of everything before the field at the end of
2013 ;; the buffer; this should be 0 for normal buffers.
2014 (1- (minibuffer-prompt-end)))
2016 ;; isearch minibuffer history
2017 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
2019 (defvar minibuffer-history-isearch-message-overlay)
2020 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
2022 (defun minibuffer-history-isearch-setup ()
2023 "Set up a minibuffer for using isearch to search the minibuffer history.
2024 Intended to be added to `minibuffer-setup-hook'."
2025 (set (make-local-variable 'isearch-search-fun-function)
2026 'minibuffer-history-isearch-search)
2027 (set (make-local-variable 'isearch-message-function)
2028 'minibuffer-history-isearch-message)
2029 (set (make-local-variable 'isearch-wrap-function)
2030 'minibuffer-history-isearch-wrap)
2031 (set (make-local-variable 'isearch-push-state-function)
2032 'minibuffer-history-isearch-push-state)
2033 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
2035 (defun minibuffer-history-isearch-end ()
2036 "Clean up the minibuffer after terminating isearch in the minibuffer."
2037 (if minibuffer-history-isearch-message-overlay
2038 (delete-overlay minibuffer-history-isearch-message-overlay)))
2040 (defun minibuffer-history-isearch-search ()
2041 "Return the proper search function, for isearch in minibuffer history."
2042 (lambda (string bound noerror)
2043 (let ((search-fun
2044 ;; Use standard functions to search within minibuffer text
2045 (isearch-search-fun-default))
2046 found)
2047 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
2048 ;; searching forward. Lazy-highlight calls this lambda with the
2049 ;; bound arg, so skip the minibuffer prompt.
2050 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
2051 (goto-char (minibuffer-prompt-end)))
2053 ;; 1. First try searching in the initial minibuffer text
2054 (funcall search-fun string
2055 (if isearch-forward bound (minibuffer-prompt-end))
2056 noerror)
2057 ;; 2. If the above search fails, start putting next/prev history
2058 ;; elements in the minibuffer successively, and search the string
2059 ;; in them. Do this only when bound is nil (i.e. not while
2060 ;; lazy-highlighting search strings in the current minibuffer text).
2061 (unless bound
2062 (condition-case nil
2063 (progn
2064 (while (not found)
2065 (cond (isearch-forward
2066 (next-history-element 1)
2067 (goto-char (minibuffer-prompt-end)))
2069 (previous-history-element 1)
2070 (goto-char (point-max))))
2071 (setq isearch-barrier (point) isearch-opoint (point))
2072 ;; After putting the next/prev history element, search
2073 ;; the string in them again, until next-history-element
2074 ;; or previous-history-element raises an error at the
2075 ;; beginning/end of history.
2076 (setq found (funcall search-fun string
2077 (unless isearch-forward
2078 ;; For backward search, don't search
2079 ;; in the minibuffer prompt
2080 (minibuffer-prompt-end))
2081 noerror)))
2082 ;; Return point of the new search result
2083 (point))
2084 ;; Return nil when next(prev)-history-element fails
2085 (error nil)))))))
2087 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
2088 "Display the minibuffer history search prompt.
2089 If there are no search errors, this function displays an overlay with
2090 the isearch prompt which replaces the original minibuffer prompt.
2091 Otherwise, it displays the standard isearch message returned from
2092 the function `isearch-message'."
2093 (if (not (and (minibufferp) isearch-success (not isearch-error)))
2094 ;; Use standard function `isearch-message' when not in the minibuffer,
2095 ;; or search fails, or has an error (like incomplete regexp).
2096 ;; This function overwrites minibuffer text with isearch message,
2097 ;; so it's possible to see what is wrong in the search string.
2098 (isearch-message c-q-hack ellipsis)
2099 ;; Otherwise, put the overlay with the standard isearch prompt over
2100 ;; the initial minibuffer prompt.
2101 (if (overlayp minibuffer-history-isearch-message-overlay)
2102 (move-overlay minibuffer-history-isearch-message-overlay
2103 (point-min) (minibuffer-prompt-end))
2104 (setq minibuffer-history-isearch-message-overlay
2105 (make-overlay (point-min) (minibuffer-prompt-end)))
2106 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
2107 (overlay-put minibuffer-history-isearch-message-overlay
2108 'display (isearch-message-prefix c-q-hack ellipsis))
2109 ;; And clear any previous isearch message.
2110 (message "")))
2112 (defun minibuffer-history-isearch-wrap ()
2113 "Wrap the minibuffer history search when search fails.
2114 Move point to the first history element for a forward search,
2115 or to the last history element for a backward search."
2116 ;; When `minibuffer-history-isearch-search' fails on reaching the
2117 ;; beginning/end of the history, wrap the search to the first/last
2118 ;; minibuffer history element.
2119 (if isearch-forward
2120 (goto-history-element (length (symbol-value minibuffer-history-variable)))
2121 (goto-history-element 0))
2122 (setq isearch-success t)
2123 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
2125 (defun minibuffer-history-isearch-push-state ()
2126 "Save a function restoring the state of minibuffer history search.
2127 Save `minibuffer-history-position' to the additional state parameter
2128 in the search status stack."
2129 (let ((pos minibuffer-history-position))
2130 (lambda (cmd)
2131 (minibuffer-history-isearch-pop-state cmd pos))))
2133 (defun minibuffer-history-isearch-pop-state (_cmd hist-pos)
2134 "Restore the minibuffer history search state.
2135 Go to the history element by the absolute history position HIST-POS."
2136 (goto-history-element hist-pos))
2139 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
2140 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2142 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
2143 "Table mapping redo records to the corresponding undo one.
2144 A redo record for undo-in-region maps to t.
2145 A redo record for ordinary undo maps to the following (earlier) undo.")
2147 (defvar undo-in-region nil
2148 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
2150 (defvar undo-no-redo nil
2151 "If t, `undo' doesn't go through redo entries.")
2153 (defvar pending-undo-list nil
2154 "Within a run of consecutive undo commands, list remaining to be undone.
2155 If t, we undid all the way to the end of it.")
2157 (defun undo (&optional arg)
2158 "Undo some previous changes.
2159 Repeat this command to undo more changes.
2160 A numeric ARG serves as a repeat count.
2162 In Transient Mark mode when the mark is active, only undo changes within
2163 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
2164 as an argument limits undo to changes within the current region."
2165 (interactive "*P")
2166 ;; Make last-command indicate for the next command that this was an undo.
2167 ;; That way, another undo will undo more.
2168 ;; If we get to the end of the undo history and get an error,
2169 ;; another undo command will find the undo history empty
2170 ;; and will get another error. To begin undoing the undos,
2171 ;; you must type some other command.
2172 (let* ((modified (buffer-modified-p))
2173 ;; For an indirect buffer, look in the base buffer for the
2174 ;; auto-save data.
2175 (base-buffer (or (buffer-base-buffer) (current-buffer)))
2176 (recent-save (with-current-buffer base-buffer
2177 (recent-auto-save-p)))
2178 message)
2179 ;; If we get an error in undo-start,
2180 ;; the next command should not be a "consecutive undo".
2181 ;; So set `this-command' to something other than `undo'.
2182 (setq this-command 'undo-start)
2184 (unless (and (eq last-command 'undo)
2185 (or (eq pending-undo-list t)
2186 ;; If something (a timer or filter?) changed the buffer
2187 ;; since the previous command, don't continue the undo seq.
2188 (let ((list buffer-undo-list))
2189 (while (eq (car list) nil)
2190 (setq list (cdr list)))
2191 ;; If the last undo record made was made by undo
2192 ;; it shows nothing else happened in between.
2193 (gethash list undo-equiv-table))))
2194 (setq undo-in-region
2195 (or (region-active-p) (and arg (not (numberp arg)))))
2196 (if undo-in-region
2197 (undo-start (region-beginning) (region-end))
2198 (undo-start))
2199 ;; get rid of initial undo boundary
2200 (undo-more 1))
2201 ;; If we got this far, the next command should be a consecutive undo.
2202 (setq this-command 'undo)
2203 ;; Check to see whether we're hitting a redo record, and if
2204 ;; so, ask the user whether she wants to skip the redo/undo pair.
2205 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
2206 (or (eq (selected-window) (minibuffer-window))
2207 (setq message (format "%s%s!"
2208 (if (or undo-no-redo (not equiv))
2209 "Undo" "Redo")
2210 (if undo-in-region " in region" ""))))
2211 (when (and (consp equiv) undo-no-redo)
2212 ;; The equiv entry might point to another redo record if we have done
2213 ;; undo-redo-undo-redo-... so skip to the very last equiv.
2214 (while (let ((next (gethash equiv undo-equiv-table)))
2215 (if next (setq equiv next))))
2216 (setq pending-undo-list equiv)))
2217 (undo-more
2218 (if (numberp arg)
2219 (prefix-numeric-value arg)
2221 ;; Record the fact that the just-generated undo records come from an
2222 ;; undo operation--that is, they are redo records.
2223 ;; In the ordinary case (not within a region), map the redo
2224 ;; record to the following undos.
2225 ;; I don't know how to do that in the undo-in-region case.
2226 (let ((list buffer-undo-list))
2227 ;; Strip any leading undo boundaries there might be, like we do
2228 ;; above when checking.
2229 (while (eq (car list) nil)
2230 (setq list (cdr list)))
2231 (puthash list
2232 ;; Prevent identity mapping. This can happen if
2233 ;; consecutive nils are erroneously in undo list.
2234 (if (or undo-in-region (eq list pending-undo-list))
2236 pending-undo-list)
2237 undo-equiv-table))
2238 ;; Don't specify a position in the undo record for the undo command.
2239 ;; Instead, undoing this should move point to where the change is.
2240 (let ((tail buffer-undo-list)
2241 (prev nil))
2242 (while (car tail)
2243 (when (integerp (car tail))
2244 (let ((pos (car tail)))
2245 (if prev
2246 (setcdr prev (cdr tail))
2247 (setq buffer-undo-list (cdr tail)))
2248 (setq tail (cdr tail))
2249 (while (car tail)
2250 (if (eq pos (car tail))
2251 (if prev
2252 (setcdr prev (cdr tail))
2253 (setq buffer-undo-list (cdr tail)))
2254 (setq prev tail))
2255 (setq tail (cdr tail)))
2256 (setq tail nil)))
2257 (setq prev tail tail (cdr tail))))
2258 ;; Record what the current undo list says,
2259 ;; so the next command can tell if the buffer was modified in between.
2260 (and modified (not (buffer-modified-p))
2261 (with-current-buffer base-buffer
2262 (delete-auto-save-file-if-necessary recent-save)))
2263 ;; Display a message announcing success.
2264 (if message
2265 (message "%s" message))))
2267 (defun buffer-disable-undo (&optional buffer)
2268 "Make BUFFER stop keeping undo information.
2269 No argument or nil as argument means do this for the current buffer."
2270 (interactive)
2271 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
2272 (setq buffer-undo-list t)))
2274 (defun undo-only (&optional arg)
2275 "Undo some previous changes.
2276 Repeat this command to undo more changes.
2277 A numeric ARG serves as a repeat count.
2278 Contrary to `undo', this will not redo a previous undo."
2279 (interactive "*p")
2280 (let ((undo-no-redo t)) (undo arg)))
2282 (defvar undo-in-progress nil
2283 "Non-nil while performing an undo.
2284 Some change-hooks test this variable to do something different.")
2286 (defun undo-more (n)
2287 "Undo back N undo-boundaries beyond what was already undone recently.
2288 Call `undo-start' to get ready to undo recent changes,
2289 then call `undo-more' one or more times to undo them."
2290 (or (listp pending-undo-list)
2291 (user-error (concat "No further undo information"
2292 (and undo-in-region " for region"))))
2293 (let ((undo-in-progress t))
2294 ;; Note: The following, while pulling elements off
2295 ;; `pending-undo-list' will call primitive change functions which
2296 ;; will push more elements onto `buffer-undo-list'.
2297 (setq pending-undo-list (primitive-undo n pending-undo-list))
2298 (if (null pending-undo-list)
2299 (setq pending-undo-list t))))
2301 (defun primitive-undo (n list)
2302 "Undo N records from the front of the list LIST.
2303 Return what remains of the list."
2305 ;; This is a good feature, but would make undo-start
2306 ;; unable to do what is expected.
2307 ;;(when (null (car (list)))
2308 ;; ;; If the head of the list is a boundary, it is the boundary
2309 ;; ;; preceding this command. Get rid of it and don't count it.
2310 ;; (setq list (cdr list))))
2312 (let ((arg n)
2313 ;; In a writable buffer, enable undoing read-only text that is
2314 ;; so because of text properties.
2315 (inhibit-read-only t)
2316 ;; Don't let `intangible' properties interfere with undo.
2317 (inhibit-point-motion-hooks t)
2318 ;; We use oldlist only to check for EQ. ++kfs
2319 (oldlist buffer-undo-list)
2320 (did-apply nil)
2321 (next nil))
2322 (while (> arg 0)
2323 (while (setq next (pop list)) ;Exit inner loop at undo boundary.
2324 ;; Handle an integer by setting point to that value.
2325 (pcase next
2326 ((pred integerp) (goto-char next))
2327 ;; Element (t . TIME) records previous modtime.
2328 ;; Preserve any flag of NONEXISTENT_MODTIME_NSECS or
2329 ;; UNKNOWN_MODTIME_NSECS.
2330 (`(t . ,time)
2331 ;; If this records an obsolete save
2332 ;; (not matching the actual disk file)
2333 ;; then don't mark unmodified.
2334 (when (or (equal time (visited-file-modtime))
2335 (and (consp time)
2336 (equal (list (car time) (cdr time))
2337 (visited-file-modtime))))
2338 (when (fboundp 'unlock-buffer)
2339 (unlock-buffer))
2340 (set-buffer-modified-p nil)))
2341 ;; Element (nil PROP VAL BEG . END) is property change.
2342 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2343 (when (or (> (point-min) beg) (< (point-max) end))
2344 (error "Changes to be undone are outside visible portion of buffer"))
2345 (put-text-property beg end prop val))
2346 ;; Element (BEG . END) means range was inserted.
2347 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2348 ;; (and `(,beg . ,end) `(,(pred integerp) . ,(pred integerp)))
2349 ;; Ideally: `(,(pred integerp beg) . ,(pred integerp end))
2350 (when (or (> (point-min) beg) (< (point-max) end))
2351 (error "Changes to be undone are outside visible portion of buffer"))
2352 ;; Set point first thing, so that undoing this undo
2353 ;; does not send point back to where it is now.
2354 (goto-char beg)
2355 (delete-region beg end))
2356 ;; Element (apply FUN . ARGS) means call FUN to undo.
2357 (`(apply . ,fun-args)
2358 (let ((currbuff (current-buffer)))
2359 (if (integerp (car fun-args))
2360 ;; Long format: (apply DELTA START END FUN . ARGS).
2361 (pcase-let* ((`(,delta ,start ,end ,fun . ,args) fun-args)
2362 (start-mark (copy-marker start nil))
2363 (end-mark (copy-marker end t)))
2364 (when (or (> (point-min) start) (< (point-max) end))
2365 (error "Changes to be undone are outside visible portion of buffer"))
2366 (apply fun args) ;; Use `save-current-buffer'?
2367 ;; Check that the function did what the entry
2368 ;; said it would do.
2369 (unless (and (= start start-mark)
2370 (= (+ delta end) end-mark))
2371 (error "Changes to be undone by function different than announced"))
2372 (set-marker start-mark nil)
2373 (set-marker end-mark nil))
2374 (apply fun-args))
2375 (unless (eq currbuff (current-buffer))
2376 (error "Undo function switched buffer"))
2377 (setq did-apply t)))
2378 ;; Element (STRING . POS) means STRING was deleted.
2379 (`(,(and string (pred stringp)) . ,(and pos (pred integerp)))
2380 (when (let ((apos (abs pos)))
2381 (or (< apos (point-min)) (> apos (point-max))))
2382 (error "Changes to be undone are outside visible portion of buffer"))
2383 (let (valid-marker-adjustments)
2384 ;; Check that marker adjustments which were recorded
2385 ;; with the (STRING . POS) record are still valid, ie
2386 ;; the markers haven't moved. We check their validity
2387 ;; before reinserting the string so as we don't need to
2388 ;; mind marker insertion-type.
2389 (while (and (markerp (car-safe (car list)))
2390 (integerp (cdr-safe (car list))))
2391 (let* ((marker-adj (pop list))
2392 (m (car marker-adj)))
2393 (and (eq (marker-buffer m) (current-buffer))
2394 (= pos m)
2395 (push marker-adj valid-marker-adjustments))))
2396 ;; Insert string and adjust point
2397 (if (< pos 0)
2398 (progn
2399 (goto-char (- pos))
2400 (insert string))
2401 (goto-char pos)
2402 (insert string)
2403 (goto-char pos))
2404 ;; Adjust the valid marker adjustments
2405 (dolist (adj valid-marker-adjustments)
2406 (set-marker (car adj)
2407 (- (car adj) (cdr adj))))))
2408 ;; (MARKER . OFFSET) means a marker MARKER was adjusted by OFFSET.
2409 (`(,(and marker (pred markerp)) . ,(and offset (pred integerp)))
2410 (warn "Encountered %S entry in undo list with no matching (TEXT . POS) entry"
2411 next)
2412 ;; Even though these elements are not expected in the undo
2413 ;; list, adjust them to be conservative for the 24.4
2414 ;; release. (Bug#16818)
2415 (when (marker-buffer marker)
2416 (set-marker marker
2417 (- marker offset)
2418 (marker-buffer marker))))
2419 (_ (error "Unrecognized entry in undo list %S" next))))
2420 (setq arg (1- arg)))
2421 ;; Make sure an apply entry produces at least one undo entry,
2422 ;; so the test in `undo' for continuing an undo series
2423 ;; will work right.
2424 (if (and did-apply
2425 (eq oldlist buffer-undo-list))
2426 (setq buffer-undo-list
2427 (cons (list 'apply 'cdr nil) buffer-undo-list))))
2428 list)
2430 ;; Deep copy of a list
2431 (defun undo-copy-list (list)
2432 "Make a copy of undo list LIST."
2433 (mapcar 'undo-copy-list-1 list))
2435 (defun undo-copy-list-1 (elt)
2436 (if (consp elt)
2437 (cons (car elt) (undo-copy-list-1 (cdr elt)))
2438 elt))
2440 (defun undo-start (&optional beg end)
2441 "Set `pending-undo-list' to the front of the undo list.
2442 The next call to `undo-more' will undo the most recently made change.
2443 If BEG and END are specified, then only undo elements
2444 that apply to text between BEG and END are used; other undo elements
2445 are ignored. If BEG and END are nil, all undo elements are used."
2446 (if (eq buffer-undo-list t)
2447 (user-error "No undo information in this buffer"))
2448 (setq pending-undo-list
2449 (if (and beg end (not (= beg end)))
2450 (undo-make-selective-list (min beg end) (max beg end))
2451 buffer-undo-list)))
2453 ;; The positions given in elements of the undo list are the positions
2454 ;; as of the time that element was recorded to undo history. In
2455 ;; general, subsequent buffer edits render those positions invalid in
2456 ;; the current buffer, unless adjusted according to the intervening
2457 ;; undo elements.
2459 ;; Undo in region is a use case that requires adjustments to undo
2460 ;; elements. It must adjust positions of elements in the region based
2461 ;; on newer elements not in the region so as they may be correctly
2462 ;; applied in the current buffer. undo-make-selective-list
2463 ;; accomplishes this with its undo-deltas list of adjustments. An
2464 ;; example undo history from oldest to newest:
2466 ;; buf pos:
2467 ;; 123456789 buffer-undo-list undo-deltas
2468 ;; --------- ---------------- -----------
2469 ;; aaa (1 . 4) (1 . -3)
2470 ;; aaba (3 . 4) N/A (in region)
2471 ;; ccaaba (1 . 3) (1 . -2)
2472 ;; ccaabaddd (7 . 10) (7 . -3)
2473 ;; ccaabdd ("ad" . 6) (6 . 2)
2474 ;; ccaabaddd (6 . 8) (6 . -2)
2475 ;; | |<-- region: "caab", from 2 to 6
2477 ;; When the user starts a run of undos in region,
2478 ;; undo-make-selective-list is called to create the full list of in
2479 ;; region elements. Each element is adjusted forward chronologically
2480 ;; through undo-deltas to determine if it is in the region.
2482 ;; In the above example, the insertion of "b" is (3 . 4) in the
2483 ;; buffer-undo-list. The undo-delta (1 . -2) causes (3 . 4) to become
2484 ;; (5 . 6). The next three undo-deltas cause no adjustment, so (5
2485 ;; . 6) is assessed as in the region and placed in the selective list.
2486 ;; Notably, the end of region itself adjusts from "2 to 6" to "2 to 5"
2487 ;; due to the selected element. The "b" insertion is the only element
2488 ;; fully in the region, so in this example undo-make-selective-list
2489 ;; returns (nil (5 . 6)).
2491 ;; The adjustment of the (7 . 10) insertion of "ddd" shows an edge
2492 ;; case. It is adjusted through the undo-deltas: ((6 . 2) (6 . -2)).
2493 ;; Normally an undo-delta of (6 . 2) would cause positions after 6 to
2494 ;; adjust by 2. However, they shouldn't adjust to less than 6, so (7
2495 ;; . 10) adjusts to (6 . 8) due to the first undo delta.
2497 ;; More interesting is how to adjust the "ddd" insertion due to the
2498 ;; next undo-delta: (6 . -2), corresponding to reinsertion of "ad".
2499 ;; If the reinsertion was a manual retyping of "ad", then the total
2500 ;; adjustment should be (7 . 10) -> (6 . 8) -> (8 . 10). However, if
2501 ;; the reinsertion was due to undo, one might expect the first "d"
2502 ;; character would again be a part of the "ddd" text, meaning its
2503 ;; total adjustment would be (7 . 10) -> (6 . 8) -> (7 . 10).
2505 ;; undo-make-selective-list assumes in this situation that "ad" was a
2506 ;; new edit, even if it was inserted because of an undo.
2507 ;; Consequently, if the user undos in region "8 to 10" of the
2508 ;; "ccaabaddd" buffer, they could be surprised that it becomes
2509 ;; "ccaabad", as though the first "d" became detached from the
2510 ;; original "ddd" insertion. This quirk is a FIXME.
2512 (defun undo-make-selective-list (start end)
2513 "Return a list of undo elements for the region START to END.
2514 The elements come from `buffer-undo-list', but we keep only the
2515 elements inside this region, and discard those outside this
2516 region. The elements' positions are adjusted so as the returned
2517 list can be applied to the current buffer."
2518 (let ((ulist buffer-undo-list)
2519 ;; A list of position adjusted undo elements in the region.
2520 (selective-list (list nil))
2521 ;; A list of undo-deltas for out of region undo elements.
2522 undo-deltas
2523 undo-elt)
2524 (while ulist
2525 (when undo-no-redo
2526 (while (gethash ulist undo-equiv-table)
2527 (setq ulist (gethash ulist undo-equiv-table))))
2528 (setq undo-elt (car ulist))
2529 (cond
2530 ((null undo-elt)
2531 ;; Don't put two nils together in the list
2532 (when (car selective-list)
2533 (push nil selective-list)))
2534 ((and (consp undo-elt) (eq (car undo-elt) t))
2535 ;; This is a "was unmodified" element. Keep it
2536 ;; if we have kept everything thus far.
2537 (when (not undo-deltas)
2538 (push undo-elt selective-list)))
2539 ;; Skip over marker adjustments, instead relying
2540 ;; on finding them after (TEXT . POS) elements
2541 ((markerp (car-safe undo-elt))
2542 nil)
2544 (let ((adjusted-undo-elt (undo-adjust-elt undo-elt
2545 undo-deltas)))
2546 (if (undo-elt-in-region adjusted-undo-elt start end)
2547 (progn
2548 (setq end (+ end (cdr (undo-delta adjusted-undo-elt))))
2549 (push adjusted-undo-elt selective-list)
2550 ;; Keep (MARKER . ADJUSTMENT) if their (TEXT . POS) was
2551 ;; kept. primitive-undo may discard them later.
2552 (when (and (stringp (car-safe adjusted-undo-elt))
2553 (integerp (cdr-safe adjusted-undo-elt)))
2554 (let ((list-i (cdr ulist)))
2555 (while (markerp (car-safe (car list-i)))
2556 (push (pop list-i) selective-list)))))
2557 (let ((delta (undo-delta undo-elt)))
2558 (when (/= 0 (cdr delta))
2559 (push delta undo-deltas)))))))
2560 (pop ulist))
2561 (nreverse selective-list)))
2563 (defun undo-elt-in-region (undo-elt start end)
2564 "Determine whether UNDO-ELT falls inside the region START ... END.
2565 If it crosses the edge, we return nil.
2567 Generally this function is not useful for determining
2568 whether (MARKER . ADJUSTMENT) undo elements are in the region,
2569 because markers can be arbitrarily relocated. Instead, pass the
2570 marker adjustment's corresponding (TEXT . POS) element."
2571 (cond ((integerp undo-elt)
2572 (and (>= undo-elt start)
2573 (<= undo-elt end)))
2574 ((eq undo-elt nil)
2576 ((atom undo-elt)
2577 nil)
2578 ((stringp (car undo-elt))
2579 ;; (TEXT . POSITION)
2580 (and (>= (abs (cdr undo-elt)) start)
2581 (<= (abs (cdr undo-elt)) end)))
2582 ((and (consp undo-elt) (markerp (car undo-elt)))
2583 ;; (MARKER . ADJUSTMENT)
2584 (<= start (car undo-elt) end))
2585 ((null (car undo-elt))
2586 ;; (nil PROPERTY VALUE BEG . END)
2587 (let ((tail (nthcdr 3 undo-elt)))
2588 (and (>= (car tail) start)
2589 (<= (cdr tail) end))))
2590 ((integerp (car undo-elt))
2591 ;; (BEGIN . END)
2592 (and (>= (car undo-elt) start)
2593 (<= (cdr undo-elt) end)))))
2595 (defun undo-elt-crosses-region (undo-elt start end)
2596 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2597 This assumes we have already decided that UNDO-ELT
2598 is not *inside* the region START...END."
2599 (declare (obsolete nil "25.1"))
2600 (cond ((atom undo-elt) nil)
2601 ((null (car undo-elt))
2602 ;; (nil PROPERTY VALUE BEG . END)
2603 (let ((tail (nthcdr 3 undo-elt)))
2604 (and (< (car tail) end)
2605 (> (cdr tail) start))))
2606 ((integerp (car undo-elt))
2607 ;; (BEGIN . END)
2608 (and (< (car undo-elt) end)
2609 (> (cdr undo-elt) start)))))
2611 (defun undo-adjust-elt (elt deltas)
2612 "Return adjustment of undo element ELT by the undo DELTAS
2613 list."
2614 (pcase elt
2615 ;; POSITION
2616 ((pred integerp)
2617 (undo-adjust-pos elt deltas))
2618 ;; (BEG . END)
2619 (`(,(and beg (pred integerp)) . ,(and end (pred integerp)))
2620 (undo-adjust-beg-end beg end deltas))
2621 ;; (TEXT . POSITION)
2622 (`(,(and text (pred stringp)) . ,(and pos (pred integerp)))
2623 (cons text (* (if (< pos 0) -1 1)
2624 (undo-adjust-pos (abs pos) deltas))))
2625 ;; (nil PROPERTY VALUE BEG . END)
2626 (`(nil . ,(or `(,prop ,val ,beg . ,end) pcase--dontcare))
2627 `(nil ,prop ,val . ,(undo-adjust-beg-end beg end deltas)))
2628 ;; (apply DELTA START END FUN . ARGS)
2629 ;; FIXME
2630 ;; All others return same elt
2631 (_ elt)))
2633 ;; (BEG . END) can adjust to the same positions, commonly when an
2634 ;; insertion was undone and they are out of region, for example:
2636 ;; buf pos:
2637 ;; 123456789 buffer-undo-list undo-deltas
2638 ;; --------- ---------------- -----------
2639 ;; [...]
2640 ;; abbaa (2 . 4) (2 . -2)
2641 ;; aaa ("bb" . 2) (2 . 2)
2642 ;; [...]
2644 ;; "bb" insertion (2 . 4) adjusts to (2 . 2) because of the subsequent
2645 ;; undo. Further adjustments to such an element should be the same as
2646 ;; for (TEXT . POSITION) elements. The options are:
2648 ;; 1: POSITION adjusts using <= (use-< nil), resulting in behavior
2649 ;; analogous to marker insertion-type t.
2651 ;; 2: POSITION adjusts using <, resulting in behavior analogous to
2652 ;; marker insertion-type nil.
2654 ;; There was no strong reason to prefer one or the other, except that
2655 ;; the first is more consistent with prior undo in region behavior.
2656 (defun undo-adjust-beg-end (beg end deltas)
2657 "Return cons of adjustments to BEG and END by the undo DELTAS
2658 list."
2659 (let ((adj-beg (undo-adjust-pos beg deltas)))
2660 ;; Note: option 2 above would be like (cons (min ...) adj-end)
2661 (cons adj-beg
2662 (max adj-beg (undo-adjust-pos end deltas t)))))
2664 (defun undo-adjust-pos (pos deltas &optional use-<)
2665 "Return adjustment of POS by the undo DELTAS list, comparing
2666 with < or <= based on USE-<."
2667 (dolist (d deltas pos)
2668 (when (if use-<
2669 (< (car d) pos)
2670 (<= (car d) pos))
2671 (setq pos
2672 ;; Don't allow pos to become less than the undo-delta
2673 ;; position. This edge case is described in the overview
2674 ;; comments.
2675 (max (car d) (- pos (cdr d)))))))
2677 ;; Return the first affected buffer position and the delta for an undo element
2678 ;; delta is defined as the change in subsequent buffer positions if we *did*
2679 ;; the undo.
2680 (defun undo-delta (undo-elt)
2681 (if (consp undo-elt)
2682 (cond ((stringp (car undo-elt))
2683 ;; (TEXT . POSITION)
2684 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2685 ((integerp (car undo-elt))
2686 ;; (BEGIN . END)
2687 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2689 '(0 . 0)))
2690 '(0 . 0)))
2692 (defcustom undo-ask-before-discard nil
2693 "If non-nil ask about discarding undo info for the current command.
2694 Normally, Emacs discards the undo info for the current command if
2695 it exceeds `undo-outer-limit'. But if you set this option
2696 non-nil, it asks in the echo area whether to discard the info.
2697 If you answer no, there is a slight risk that Emacs might crash, so
2698 only do it if you really want to undo the command.
2700 This option is mainly intended for debugging. You have to be
2701 careful if you use it for other purposes. Garbage collection is
2702 inhibited while the question is asked, meaning that Emacs might
2703 leak memory. So you should make sure that you do not wait
2704 excessively long before answering the question."
2705 :type 'boolean
2706 :group 'undo
2707 :version "22.1")
2709 (defvar undo-extra-outer-limit nil
2710 "If non-nil, an extra level of size that's ok in an undo item.
2711 We don't ask the user about truncating the undo list until the
2712 current item gets bigger than this amount.
2714 This variable only matters if `undo-ask-before-discard' is non-nil.")
2715 (make-variable-buffer-local 'undo-extra-outer-limit)
2717 ;; When the first undo batch in an undo list is longer than
2718 ;; undo-outer-limit, this function gets called to warn the user that
2719 ;; the undo info for the current command was discarded. Garbage
2720 ;; collection is inhibited around the call, so it had better not do a
2721 ;; lot of consing.
2722 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
2723 (defun undo-outer-limit-truncate (size)
2724 (if undo-ask-before-discard
2725 (when (or (null undo-extra-outer-limit)
2726 (> size undo-extra-outer-limit))
2727 ;; Don't ask the question again unless it gets even bigger.
2728 ;; This applies, in particular, if the user quits from the question.
2729 ;; Such a quit quits out of GC, but something else will call GC
2730 ;; again momentarily. It will call this function again,
2731 ;; but we don't want to ask the question again.
2732 (setq undo-extra-outer-limit (+ size 50000))
2733 (if (let (use-dialog-box track-mouse executing-kbd-macro )
2734 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
2735 (buffer-name) size)))
2736 (progn (setq buffer-undo-list nil)
2737 (setq undo-extra-outer-limit nil)
2739 nil))
2740 (display-warning '(undo discard-info)
2741 (concat
2742 (format "Buffer `%s' undo info was %d bytes long.\n"
2743 (buffer-name) size)
2744 "The undo info was discarded because it exceeded \
2745 `undo-outer-limit'.
2747 This is normal if you executed a command that made a huge change
2748 to the buffer. In that case, to prevent similar problems in the
2749 future, set `undo-outer-limit' to a value that is large enough to
2750 cover the maximum size of normal changes you expect a single
2751 command to make, but not so large that it might exceed the
2752 maximum memory allotted to Emacs.
2754 If you did not execute any such command, the situation is
2755 probably due to a bug and you should report it.
2757 You can disable the popping up of this buffer by adding the entry
2758 \(undo discard-info) to the user option `warning-suppress-types',
2759 which is defined in the `warnings' library.\n")
2760 :warning)
2761 (setq buffer-undo-list nil)
2764 (defcustom password-word-equivalents
2765 '("password" "passphrase" "pass phrase"
2766 ; These are sorted according to the GNU en_US locale.
2767 "암호" ; ko
2768 "パスワード" ; ja
2769 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
2770 "ពាក្យសម្ងាត់" ; km
2771 "adgangskode" ; da
2772 "contraseña" ; es
2773 "contrasenya" ; ca
2774 "geslo" ; sl
2775 "hasło" ; pl
2776 "heslo" ; cs, sk
2777 "iphasiwedi" ; zu
2778 "jelszó" ; hu
2779 "lösenord" ; sv
2780 "lozinka" ; hr, sr
2781 "mật khẩu" ; vi
2782 "mot de passe" ; fr
2783 "parola" ; tr
2784 "pasahitza" ; eu
2785 "passord" ; nb
2786 "passwort" ; de
2787 "pasvorto" ; eo
2788 "salasana" ; fi
2789 "senha" ; pt
2790 "slaptažodis" ; lt
2791 "wachtwoord" ; nl
2792 "كلمة السر" ; ar
2793 "ססמה" ; he
2794 "лозинка" ; sr
2795 "пароль" ; kk, ru, uk
2796 "गुप्तशब्द" ; mr
2797 "शब्दकूट" ; hi
2798 "પાસવર્ડ" ; gu
2799 "సంకేతపదము" ; te
2800 "ਪਾਸਵਰਡ" ; pa
2801 "ಗುಪ್ತಪದ" ; kn
2802 "கடவுச்சொல்" ; ta
2803 "അടയാളവാക്ക്" ; ml
2804 "গুপ্তশব্দ" ; as
2805 "পাসওয়ার্ড" ; bn_IN
2806 "රහස්පදය" ; si
2807 "密码" ; zh_CN
2808 "密碼" ; zh_TW
2810 "List of words equivalent to \"password\".
2811 This is used by Shell mode and other parts of Emacs to recognize
2812 password prompts, including prompts in languages other than
2813 English. Different case choices should not be assumed to be
2814 included; callers should bind `case-fold-search' to t."
2815 :type '(repeat string)
2816 :version "24.4"
2817 :group 'processes)
2819 (defvar shell-command-history nil
2820 "History list for some commands that read shell commands.
2822 Maximum length of the history list is determined by the value
2823 of `history-length', which see.")
2825 (defvar shell-command-switch (purecopy "-c")
2826 "Switch used to have the shell execute its command line argument.")
2828 (defvar shell-command-default-error-buffer nil
2829 "Buffer name for `shell-command' and `shell-command-on-region' error output.
2830 This buffer is used when `shell-command' or `shell-command-on-region'
2831 is run interactively. A value of nil means that output to stderr and
2832 stdout will be intermixed in the output stream.")
2834 (declare-function mailcap-file-default-commands "mailcap" (files))
2835 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2837 (defun minibuffer-default-add-shell-commands ()
2838 "Return a list of all commands associated with the current file.
2839 This function is used to add all related commands retrieved by `mailcap'
2840 to the end of the list of defaults just after the default value."
2841 (interactive)
2842 (let* ((filename (if (listp minibuffer-default)
2843 (car minibuffer-default)
2844 minibuffer-default))
2845 (commands (and filename (require 'mailcap nil t)
2846 (mailcap-file-default-commands (list filename)))))
2847 (setq commands (mapcar (lambda (command)
2848 (concat command " " filename))
2849 commands))
2850 (if (listp minibuffer-default)
2851 (append minibuffer-default commands)
2852 (cons minibuffer-default commands))))
2854 (declare-function shell-completion-vars "shell" ())
2856 (defvar minibuffer-local-shell-command-map
2857 (let ((map (make-sparse-keymap)))
2858 (set-keymap-parent map minibuffer-local-map)
2859 (define-key map "\t" 'completion-at-point)
2860 map)
2861 "Keymap used for completing shell commands in minibuffer.")
2863 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
2864 "Read a shell command from the minibuffer.
2865 The arguments are the same as the ones of `read-from-minibuffer',
2866 except READ and KEYMAP are missing and HIST defaults
2867 to `shell-command-history'."
2868 (require 'shell)
2869 (minibuffer-with-setup-hook
2870 (lambda ()
2871 (shell-completion-vars)
2872 (set (make-local-variable 'minibuffer-default-add-function)
2873 'minibuffer-default-add-shell-commands))
2874 (apply 'read-from-minibuffer prompt initial-contents
2875 minibuffer-local-shell-command-map
2877 (or hist 'shell-command-history)
2878 args)))
2880 (defcustom async-shell-command-buffer 'confirm-new-buffer
2881 "What to do when the output buffer is used by another shell command.
2882 This option specifies how to resolve the conflict where a new command
2883 wants to direct its output to the buffer `*Async Shell Command*',
2884 but this buffer is already taken by another running shell command.
2886 The value `confirm-kill-process' is used to ask for confirmation before
2887 killing the already running process and running a new process
2888 in the same buffer, `confirm-new-buffer' for confirmation before running
2889 the command in a new buffer with a name other than the default buffer name,
2890 `new-buffer' for doing the same without confirmation,
2891 `confirm-rename-buffer' for confirmation before renaming the existing
2892 output buffer and running a new command in the default buffer,
2893 `rename-buffer' for doing the same without confirmation."
2894 :type '(choice (const :tag "Confirm killing of running command"
2895 confirm-kill-process)
2896 (const :tag "Confirm creation of a new buffer"
2897 confirm-new-buffer)
2898 (const :tag "Create a new buffer"
2899 new-buffer)
2900 (const :tag "Confirm renaming of existing buffer"
2901 confirm-rename-buffer)
2902 (const :tag "Rename the existing buffer"
2903 rename-buffer))
2904 :group 'shell
2905 :version "24.3")
2907 (defun async-shell-command (command &optional output-buffer error-buffer)
2908 "Execute string COMMAND asynchronously in background.
2910 Like `shell-command', but adds `&' at the end of COMMAND
2911 to execute it asynchronously.
2913 The output appears in the buffer `*Async Shell Command*'.
2914 That buffer is in shell mode.
2916 You can configure `async-shell-command-buffer' to specify what to do in
2917 case when `*Async Shell Command*' buffer is already taken by another
2918 running shell command. To run COMMAND without displaying the output
2919 in a window you can configure `display-buffer-alist' to use the action
2920 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
2922 In Elisp, you will often be better served by calling `start-process'
2923 directly, since it offers more control and does not impose the use of a
2924 shell (with its need to quote arguments)."
2925 (interactive
2926 (list
2927 (read-shell-command "Async shell command: " nil nil
2928 (let ((filename
2929 (cond
2930 (buffer-file-name)
2931 ((eq major-mode 'dired-mode)
2932 (dired-get-filename nil t)))))
2933 (and filename (file-relative-name filename))))
2934 current-prefix-arg
2935 shell-command-default-error-buffer))
2936 (unless (string-match "&[ \t]*\\'" command)
2937 (setq command (concat command " &")))
2938 (shell-command command output-buffer error-buffer))
2940 (defun shell-command (command &optional output-buffer error-buffer)
2941 "Execute string COMMAND in inferior shell; display output, if any.
2942 With prefix argument, insert the COMMAND's output at point.
2944 If COMMAND ends in `&', execute it asynchronously.
2945 The output appears in the buffer `*Async Shell Command*'.
2946 That buffer is in shell mode. You can also use
2947 `async-shell-command' that automatically adds `&'.
2949 Otherwise, COMMAND is executed synchronously. The output appears in
2950 the buffer `*Shell Command Output*'. If the output is short enough to
2951 display in the echo area (which is determined by the variables
2952 `resize-mini-windows' and `max-mini-window-height'), it is shown
2953 there, but it is nonetheless available in buffer `*Shell Command
2954 Output*' even though that buffer is not automatically displayed.
2956 To specify a coding system for converting non-ASCII characters
2957 in the shell command output, use \\[universal-coding-system-argument] \
2958 before this command.
2960 Noninteractive callers can specify coding systems by binding
2961 `coding-system-for-read' and `coding-system-for-write'.
2963 The optional second argument OUTPUT-BUFFER, if non-nil,
2964 says to put the output in some other buffer.
2965 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2966 If OUTPUT-BUFFER is not a buffer and not nil,
2967 insert output in current buffer. (This cannot be done asynchronously.)
2968 In either case, the buffer is first erased, and the output is
2969 inserted after point (leaving mark after it).
2971 If the command terminates without error, but generates output,
2972 and you did not specify \"insert it in the current buffer\",
2973 the output can be displayed in the echo area or in its buffer.
2974 If the output is short enough to display in the echo area
2975 \(determined by the variable `max-mini-window-height' if
2976 `resize-mini-windows' is non-nil), it is shown there.
2977 Otherwise,the buffer containing the output is displayed.
2979 If there is output and an error, and you did not specify \"insert it
2980 in the current buffer\", a message about the error goes at the end
2981 of the output.
2983 If there is no output, or if output is inserted in the current buffer,
2984 then `*Shell Command Output*' is deleted.
2986 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2987 or buffer name to which to direct the command's standard error output.
2988 If it is nil, error output is mingled with regular output.
2989 In an interactive call, the variable `shell-command-default-error-buffer'
2990 specifies the value of ERROR-BUFFER.
2992 In Elisp, you will often be better served by calling `call-process' or
2993 `start-process' directly, since it offers more control and does not impose
2994 the use of a shell (with its need to quote arguments)."
2996 (interactive
2997 (list
2998 (read-shell-command "Shell command: " nil nil
2999 (let ((filename
3000 (cond
3001 (buffer-file-name)
3002 ((eq major-mode 'dired-mode)
3003 (dired-get-filename nil t)))))
3004 (and filename (file-relative-name filename))))
3005 current-prefix-arg
3006 shell-command-default-error-buffer))
3007 ;; Look for a handler in case default-directory is a remote file name.
3008 (let ((handler
3009 (find-file-name-handler (directory-file-name default-directory)
3010 'shell-command)))
3011 (if handler
3012 (funcall handler 'shell-command command output-buffer error-buffer)
3013 (if (and output-buffer
3014 (not (or (bufferp output-buffer) (stringp output-buffer))))
3015 ;; Output goes in current buffer.
3016 (let ((error-file
3017 (if error-buffer
3018 (make-temp-file
3019 (expand-file-name "scor"
3020 (or small-temporary-file-directory
3021 temporary-file-directory)))
3022 nil)))
3023 (barf-if-buffer-read-only)
3024 (push-mark nil t)
3025 ;; We do not use -f for csh; we will not support broken use of
3026 ;; .cshrcs. Even the BSD csh manual says to use
3027 ;; "if ($?prompt) exit" before things which are not useful
3028 ;; non-interactively. Besides, if someone wants their other
3029 ;; aliases for shell commands then they can still have them.
3030 (call-process shell-file-name nil
3031 (if error-file
3032 (list t error-file)
3034 nil shell-command-switch command)
3035 (when (and error-file (file-exists-p error-file))
3036 (if (< 0 (nth 7 (file-attributes error-file)))
3037 (with-current-buffer (get-buffer-create error-buffer)
3038 (let ((pos-from-end (- (point-max) (point))))
3039 (or (bobp)
3040 (insert "\f\n"))
3041 ;; Do no formatting while reading error file,
3042 ;; because that can run a shell command, and we
3043 ;; don't want that to cause an infinite recursion.
3044 (format-insert-file error-file nil)
3045 ;; Put point after the inserted errors.
3046 (goto-char (- (point-max) pos-from-end)))
3047 (display-buffer (current-buffer))))
3048 (delete-file error-file))
3049 ;; This is like exchange-point-and-mark, but doesn't
3050 ;; activate the mark. It is cleaner to avoid activation,
3051 ;; even though the command loop would deactivate the mark
3052 ;; because we inserted text.
3053 (goto-char (prog1 (mark t)
3054 (set-marker (mark-marker) (point)
3055 (current-buffer)))))
3056 ;; Output goes in a separate buffer.
3057 ;; Preserve the match data in case called from a program.
3058 (save-match-data
3059 (if (string-match "[ \t]*&[ \t]*\\'" command)
3060 ;; Command ending with ampersand means asynchronous.
3061 (let ((buffer (get-buffer-create
3062 (or output-buffer "*Async Shell Command*")))
3063 (directory default-directory)
3064 proc)
3065 ;; Remove the ampersand.
3066 (setq command (substring command 0 (match-beginning 0)))
3067 ;; Ask the user what to do with already running process.
3068 (setq proc (get-buffer-process buffer))
3069 (when proc
3070 (cond
3071 ((eq async-shell-command-buffer 'confirm-kill-process)
3072 ;; If will kill a process, query first.
3073 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3074 (kill-process proc)
3075 (error "Shell command in progress")))
3076 ((eq async-shell-command-buffer 'confirm-new-buffer)
3077 ;; If will create a new buffer, query first.
3078 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3079 (setq buffer (generate-new-buffer
3080 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3081 output-buffer "*Async Shell Command*")))
3082 (error "Shell command in progress")))
3083 ((eq async-shell-command-buffer 'new-buffer)
3084 ;; It will create a new buffer.
3085 (setq buffer (generate-new-buffer
3086 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3087 output-buffer "*Async Shell Command*"))))
3088 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3089 ;; If will rename the buffer, query first.
3090 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3091 (progn
3092 (with-current-buffer buffer
3093 (rename-uniquely))
3094 (setq buffer (get-buffer-create
3095 (or output-buffer "*Async Shell Command*"))))
3096 (error "Shell command in progress")))
3097 ((eq async-shell-command-buffer 'rename-buffer)
3098 ;; It will rename the buffer.
3099 (with-current-buffer buffer
3100 (rename-uniquely))
3101 (setq buffer (get-buffer-create
3102 (or output-buffer "*Async Shell Command*"))))))
3103 (with-current-buffer buffer
3104 (setq buffer-read-only nil)
3105 ;; Setting buffer-read-only to nil doesn't suffice
3106 ;; if some text has a non-nil read-only property,
3107 ;; which comint sometimes adds for prompts.
3108 (let ((inhibit-read-only t))
3109 (erase-buffer))
3110 (display-buffer buffer '(nil (allow-no-window . t)))
3111 (setq default-directory directory)
3112 (setq proc (start-process "Shell" buffer shell-file-name
3113 shell-command-switch command))
3114 (setq mode-line-process '(":%s"))
3115 (require 'shell) (shell-mode)
3116 (set-process-sentinel proc 'shell-command-sentinel)
3117 ;; Use the comint filter for proper handling of carriage motion
3118 ;; (see `comint-inhibit-carriage-motion'),.
3119 (set-process-filter proc 'comint-output-filter)
3121 ;; Otherwise, command is executed synchronously.
3122 (shell-command-on-region (point) (point) command
3123 output-buffer nil error-buffer)))))))
3125 (defun display-message-or-buffer (message
3126 &optional buffer-name not-this-window frame)
3127 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3128 MESSAGE may be either a string or a buffer.
3130 A buffer is displayed using `display-buffer' if MESSAGE is too long for
3131 the maximum height of the echo area, as defined by `max-mini-window-height'
3132 if `resize-mini-windows' is non-nil.
3134 Returns either the string shown in the echo area, or when a pop-up
3135 buffer is used, the window used to display it.
3137 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3138 name of the buffer used to display it in the case where a pop-up buffer
3139 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3140 string and it is displayed in the echo area, it is not specified whether
3141 the contents are inserted into the buffer anyway.
3143 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
3144 and only used if a buffer is displayed."
3145 (cond ((and (stringp message) (not (string-match "\n" message)))
3146 ;; Trivial case where we can use the echo area
3147 (message "%s" message))
3148 ((and (stringp message)
3149 (= (string-match "\n" message) (1- (length message))))
3150 ;; Trivial case where we can just remove single trailing newline
3151 (message "%s" (substring message 0 (1- (length message)))))
3153 ;; General case
3154 (with-current-buffer
3155 (if (bufferp message)
3156 message
3157 (get-buffer-create (or buffer-name "*Message*")))
3159 (unless (bufferp message)
3160 (erase-buffer)
3161 (insert message))
3163 (let ((lines
3164 (if (= (buffer-size) 0)
3166 (count-screen-lines nil nil nil (minibuffer-window)))))
3167 (cond ((= lines 0))
3168 ((and (or (<= lines 1)
3169 (<= lines
3170 (if resize-mini-windows
3171 (cond ((floatp max-mini-window-height)
3172 (* (frame-height)
3173 max-mini-window-height))
3174 ((integerp max-mini-window-height)
3175 max-mini-window-height)
3178 1)))
3179 ;; Don't use the echo area if the output buffer is
3180 ;; already displayed in the selected frame.
3181 (not (get-buffer-window (current-buffer))))
3182 ;; Echo area
3183 (goto-char (point-max))
3184 (when (bolp)
3185 (backward-char 1))
3186 (message "%s" (buffer-substring (point-min) (point))))
3188 ;; Buffer
3189 (goto-char (point-min))
3190 (display-buffer (current-buffer)
3191 not-this-window frame))))))))
3194 ;; We have a sentinel to prevent insertion of a termination message
3195 ;; in the buffer itself.
3196 (defun shell-command-sentinel (process signal)
3197 (if (memq (process-status process) '(exit signal))
3198 (message "%s: %s."
3199 (car (cdr (cdr (process-command process))))
3200 (substring signal 0 -1))))
3202 (defun shell-command-on-region (start end command
3203 &optional output-buffer replace
3204 error-buffer display-error-buffer)
3205 "Execute string COMMAND in inferior shell with region as input.
3206 Normally display output (if any) in temp buffer `*Shell Command Output*';
3207 Prefix arg means replace the region with it. Return the exit code of
3208 COMMAND.
3210 To specify a coding system for converting non-ASCII characters
3211 in the input and output to the shell command, use \\[universal-coding-system-argument]
3212 before this command. By default, the input (from the current buffer)
3213 is encoded using coding-system specified by `process-coding-system-alist',
3214 falling back to `default-process-coding-system' if no match for COMMAND
3215 is found in `process-coding-system-alist'.
3217 Noninteractive callers can specify coding systems by binding
3218 `coding-system-for-read' and `coding-system-for-write'.
3220 If the command generates output, the output may be displayed
3221 in the echo area or in a buffer.
3222 If the output is short enough to display in the echo area
3223 \(determined by the variable `max-mini-window-height' if
3224 `resize-mini-windows' is non-nil), it is shown there.
3225 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3226 The output is available in that buffer in both cases.
3228 If there is output and an error, a message about the error
3229 appears at the end of the output. If there is no output, or if
3230 output is inserted in the current buffer, the buffer `*Shell
3231 Command Output*' is deleted.
3233 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3234 command's output. If the value is a buffer or buffer name,
3235 put the output there. If the value is nil, use the buffer
3236 `*Shell Command Output*'. Any other value, excluding nil,
3237 means to insert the output in the current buffer. In either case,
3238 the output is inserted after point (leaving mark after it).
3240 Optional fifth arg REPLACE, if non-nil, means to insert the
3241 output in place of text from START to END, putting point and mark
3242 around it.
3244 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3245 or buffer name to which to direct the command's standard error
3246 output. If nil, error output is mingled with regular output.
3247 When called interactively, `shell-command-default-error-buffer'
3248 is used for ERROR-BUFFER.
3250 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3251 display the error buffer if there were any errors. When called
3252 interactively, this is t."
3253 (interactive (let (string)
3254 (unless (mark)
3255 (error "The mark is not set now, so there is no region"))
3256 ;; Do this before calling region-beginning
3257 ;; and region-end, in case subprocess output
3258 ;; relocates them while we are in the minibuffer.
3259 (setq string (read-shell-command "Shell command on region: "))
3260 ;; call-interactively recognizes region-beginning and
3261 ;; region-end specially, leaving them in the history.
3262 (list (region-beginning) (region-end)
3263 string
3264 current-prefix-arg
3265 current-prefix-arg
3266 shell-command-default-error-buffer
3267 t)))
3268 (let ((error-file
3269 (if error-buffer
3270 (make-temp-file
3271 (expand-file-name "scor"
3272 (or small-temporary-file-directory
3273 temporary-file-directory)))
3274 nil))
3275 exit-status)
3276 (if (or replace
3277 (and output-buffer
3278 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3279 ;; Replace specified region with output from command.
3280 (let ((swap (and replace (< start end))))
3281 ;; Don't muck with mark unless REPLACE says we should.
3282 (goto-char start)
3283 (and replace (push-mark (point) 'nomsg))
3284 (setq exit-status
3285 (call-process-region start end shell-file-name replace
3286 (if error-file
3287 (list t error-file)
3289 nil shell-command-switch command))
3290 ;; It is rude to delete a buffer which the command is not using.
3291 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3292 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3293 ;; (kill-buffer shell-buffer)))
3294 ;; Don't muck with mark unless REPLACE says we should.
3295 (and replace swap (exchange-point-and-mark)))
3296 ;; No prefix argument: put the output in a temp buffer,
3297 ;; replacing its entire contents.
3298 (let ((buffer (get-buffer-create
3299 (or output-buffer "*Shell Command Output*"))))
3300 (unwind-protect
3301 (if (eq buffer (current-buffer))
3302 ;; If the input is the same buffer as the output,
3303 ;; delete everything but the specified region,
3304 ;; then replace that region with the output.
3305 (progn (setq buffer-read-only nil)
3306 (delete-region (max start end) (point-max))
3307 (delete-region (point-min) (min start end))
3308 (setq exit-status
3309 (call-process-region (point-min) (point-max)
3310 shell-file-name t
3311 (if error-file
3312 (list t error-file)
3314 nil shell-command-switch
3315 command)))
3316 ;; Clear the output buffer, then run the command with
3317 ;; output there.
3318 (let ((directory default-directory))
3319 (with-current-buffer buffer
3320 (setq buffer-read-only nil)
3321 (if (not output-buffer)
3322 (setq default-directory directory))
3323 (erase-buffer)))
3324 (setq exit-status
3325 (call-process-region start end shell-file-name nil
3326 (if error-file
3327 (list buffer error-file)
3328 buffer)
3329 nil shell-command-switch command)))
3330 ;; Report the output.
3331 (with-current-buffer buffer
3332 (setq mode-line-process
3333 (cond ((null exit-status)
3334 " - Error")
3335 ((stringp exit-status)
3336 (format " - Signal [%s]" exit-status))
3337 ((not (equal 0 exit-status))
3338 (format " - Exit [%d]" exit-status)))))
3339 (if (with-current-buffer buffer (> (point-max) (point-min)))
3340 ;; There's some output, display it
3341 (display-message-or-buffer buffer)
3342 ;; No output; error?
3343 (let ((output
3344 (if (and error-file
3345 (< 0 (nth 7 (file-attributes error-file))))
3346 (format "some error output%s"
3347 (if shell-command-default-error-buffer
3348 (format " to the \"%s\" buffer"
3349 shell-command-default-error-buffer)
3350 ""))
3351 "no output")))
3352 (cond ((null exit-status)
3353 (message "(Shell command failed with error)"))
3354 ((equal 0 exit-status)
3355 (message "(Shell command succeeded with %s)"
3356 output))
3357 ((stringp exit-status)
3358 (message "(Shell command killed by signal %s)"
3359 exit-status))
3361 (message "(Shell command failed with code %d and %s)"
3362 exit-status output))))
3363 ;; Don't kill: there might be useful info in the undo-log.
3364 ;; (kill-buffer buffer)
3365 ))))
3367 (when (and error-file (file-exists-p error-file))
3368 (if (< 0 (nth 7 (file-attributes error-file)))
3369 (with-current-buffer (get-buffer-create error-buffer)
3370 (let ((pos-from-end (- (point-max) (point))))
3371 (or (bobp)
3372 (insert "\f\n"))
3373 ;; Do no formatting while reading error file,
3374 ;; because that can run a shell command, and we
3375 ;; don't want that to cause an infinite recursion.
3376 (format-insert-file error-file nil)
3377 ;; Put point after the inserted errors.
3378 (goto-char (- (point-max) pos-from-end)))
3379 (and display-error-buffer
3380 (display-buffer (current-buffer)))))
3381 (delete-file error-file))
3382 exit-status))
3384 (defun shell-command-to-string (command)
3385 "Execute shell command COMMAND and return its output as a string."
3386 (with-output-to-string
3387 (with-current-buffer
3388 standard-output
3389 (process-file shell-file-name nil t nil shell-command-switch command))))
3391 (defun process-file (program &optional infile buffer display &rest args)
3392 "Process files synchronously in a separate process.
3393 Similar to `call-process', but may invoke a file handler based on
3394 `default-directory'. The current working directory of the
3395 subprocess is `default-directory'.
3397 File names in INFILE and BUFFER are handled normally, but file
3398 names in ARGS should be relative to `default-directory', as they
3399 are passed to the process verbatim. (This is a difference to
3400 `call-process' which does not support file handlers for INFILE
3401 and BUFFER.)
3403 Some file handlers might not support all variants, for example
3404 they might behave as if DISPLAY was nil, regardless of the actual
3405 value passed."
3406 (let ((fh (find-file-name-handler default-directory 'process-file))
3407 lc stderr-file)
3408 (unwind-protect
3409 (if fh (apply fh 'process-file program infile buffer display args)
3410 (when infile (setq lc (file-local-copy infile)))
3411 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3412 (make-temp-file "emacs")))
3413 (prog1
3414 (apply 'call-process program
3415 (or lc infile)
3416 (if stderr-file (list (car buffer) stderr-file) buffer)
3417 display args)
3418 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3419 (when stderr-file (delete-file stderr-file))
3420 (when lc (delete-file lc)))))
3422 (defvar process-file-side-effects t
3423 "Whether a call of `process-file' changes remote files.
3425 By default, this variable is always set to `t', meaning that a
3426 call of `process-file' could potentially change any file on a
3427 remote host. When set to `nil', a file handler could optimize
3428 its behavior with respect to remote file attribute caching.
3430 You should only ever change this variable with a let-binding;
3431 never with `setq'.")
3433 (defun start-file-process (name buffer program &rest program-args)
3434 "Start a program in a subprocess. Return the process object for it.
3436 Similar to `start-process', but may invoke a file handler based on
3437 `default-directory'. See Info node `(elisp)Magic File Names'.
3439 This handler ought to run PROGRAM, perhaps on the local host,
3440 perhaps on a remote host that corresponds to `default-directory'.
3441 In the latter case, the local part of `default-directory' becomes
3442 the working directory of the process.
3444 PROGRAM and PROGRAM-ARGS might be file names. They are not
3445 objects of file handler invocation. File handlers might not
3446 support pty association, if PROGRAM is nil."
3447 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3448 (if fh (apply fh 'start-file-process name buffer program program-args)
3449 (apply 'start-process name buffer program program-args))))
3451 ;;;; Process menu
3453 (defvar tabulated-list-format)
3454 (defvar tabulated-list-entries)
3455 (defvar tabulated-list-sort-key)
3456 (declare-function tabulated-list-init-header "tabulated-list" ())
3457 (declare-function tabulated-list-print "tabulated-list"
3458 (&optional remember-pos))
3460 (defvar process-menu-query-only nil)
3462 (defvar process-menu-mode-map
3463 (let ((map (make-sparse-keymap)))
3464 (define-key map [?d] 'process-menu-delete-process)
3465 map))
3467 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3468 "Major mode for listing the processes called by Emacs."
3469 (setq tabulated-list-format [("Process" 15 t)
3470 ("Status" 7 t)
3471 ("Buffer" 15 t)
3472 ("TTY" 12 t)
3473 ("Command" 0 t)])
3474 (make-local-variable 'process-menu-query-only)
3475 (setq tabulated-list-sort-key (cons "Process" nil))
3476 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3477 (tabulated-list-init-header))
3479 (defun process-menu-delete-process ()
3480 "Kill process at point in a `list-processes' buffer."
3481 (interactive)
3482 (delete-process (tabulated-list-get-id))
3483 (revert-buffer))
3485 (defun list-processes--refresh ()
3486 "Recompute the list of processes for the Process List buffer.
3487 Also, delete any process that is exited or signaled."
3488 (setq tabulated-list-entries nil)
3489 (dolist (p (process-list))
3490 (cond ((memq (process-status p) '(exit signal closed))
3491 (delete-process p))
3492 ((or (not process-menu-query-only)
3493 (process-query-on-exit-flag p))
3494 (let* ((buf (process-buffer p))
3495 (type (process-type p))
3496 (name (process-name p))
3497 (status (symbol-name (process-status p)))
3498 (buf-label (if (buffer-live-p buf)
3499 `(,(buffer-name buf)
3500 face link
3501 help-echo ,(concat "Visit buffer `"
3502 (buffer-name buf) "'")
3503 follow-link t
3504 process-buffer ,buf
3505 action process-menu-visit-buffer)
3506 "--"))
3507 (tty (or (process-tty-name p) "--"))
3508 (cmd
3509 (if (memq type '(network serial))
3510 (let ((contact (process-contact p t)))
3511 (if (eq type 'network)
3512 (format "(%s %s)"
3513 (if (plist-get contact :type)
3514 "datagram"
3515 "network")
3516 (if (plist-get contact :server)
3517 (format "server on %s"
3519 (plist-get contact :host)
3520 (plist-get contact :local)))
3521 (format "connection to %s"
3522 (plist-get contact :host))))
3523 (format "(serial port %s%s)"
3524 (or (plist-get contact :port) "?")
3525 (let ((speed (plist-get contact :speed)))
3526 (if speed
3527 (format " at %s b/s" speed)
3528 "")))))
3529 (mapconcat 'identity (process-command p) " "))))
3530 (push (list p (vector name status buf-label tty cmd))
3531 tabulated-list-entries))))))
3533 (defun process-menu-visit-buffer (button)
3534 (display-buffer (button-get button 'process-buffer)))
3536 (defun list-processes (&optional query-only buffer)
3537 "Display a list of all processes that are Emacs sub-processes.
3538 If optional argument QUERY-ONLY is non-nil, only processes with
3539 the query-on-exit flag set are listed.
3540 Any process listed as exited or signaled is actually eliminated
3541 after the listing is made.
3542 Optional argument BUFFER specifies a buffer to use, instead of
3543 \"*Process List*\".
3544 The return value is always nil.
3546 This function lists only processes that were launched by Emacs. To
3547 see other processes running on the system, use `list-system-processes'."
3548 (interactive)
3549 (or (fboundp 'process-list)
3550 (error "Asynchronous subprocesses are not supported on this system"))
3551 (unless (bufferp buffer)
3552 (setq buffer (get-buffer-create "*Process List*")))
3553 (with-current-buffer buffer
3554 (process-menu-mode)
3555 (setq process-menu-query-only query-only)
3556 (list-processes--refresh)
3557 (tabulated-list-print))
3558 (display-buffer buffer)
3559 nil)
3561 (defvar universal-argument-map
3562 (let ((map (make-sparse-keymap))
3563 (universal-argument-minus
3564 ;; For backward compatibility, minus with no modifiers is an ordinary
3565 ;; command if digits have already been entered.
3566 `(menu-item "" negative-argument
3567 :filter ,(lambda (cmd)
3568 (if (integerp prefix-arg) nil cmd)))))
3569 (define-key map [switch-frame]
3570 (lambda (e) (interactive "e")
3571 (handle-switch-frame e) (universal-argument--mode)))
3572 (define-key map [?\C-u] 'universal-argument-more)
3573 (define-key map [?-] universal-argument-minus)
3574 (define-key map [?0] 'digit-argument)
3575 (define-key map [?1] 'digit-argument)
3576 (define-key map [?2] 'digit-argument)
3577 (define-key map [?3] 'digit-argument)
3578 (define-key map [?4] 'digit-argument)
3579 (define-key map [?5] 'digit-argument)
3580 (define-key map [?6] 'digit-argument)
3581 (define-key map [?7] 'digit-argument)
3582 (define-key map [?8] 'digit-argument)
3583 (define-key map [?9] 'digit-argument)
3584 (define-key map [kp-0] 'digit-argument)
3585 (define-key map [kp-1] 'digit-argument)
3586 (define-key map [kp-2] 'digit-argument)
3587 (define-key map [kp-3] 'digit-argument)
3588 (define-key map [kp-4] 'digit-argument)
3589 (define-key map [kp-5] 'digit-argument)
3590 (define-key map [kp-6] 'digit-argument)
3591 (define-key map [kp-7] 'digit-argument)
3592 (define-key map [kp-8] 'digit-argument)
3593 (define-key map [kp-9] 'digit-argument)
3594 (define-key map [kp-subtract] universal-argument-minus)
3595 map)
3596 "Keymap used while processing \\[universal-argument].")
3598 (defun universal-argument--mode ()
3599 (set-transient-map universal-argument-map))
3601 (defun universal-argument ()
3602 "Begin a numeric argument for the following command.
3603 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3604 \\[universal-argument] following the digits or minus sign ends the argument.
3605 \\[universal-argument] without digits or minus sign provides 4 as argument.
3606 Repeating \\[universal-argument] without digits or minus sign
3607 multiplies the argument by 4 each time.
3608 For some commands, just \\[universal-argument] by itself serves as a flag
3609 which is different in effect from any particular numeric argument.
3610 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3611 (interactive)
3612 (setq prefix-arg (list 4))
3613 (universal-argument--mode))
3615 (defun universal-argument-more (arg)
3616 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3617 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3618 (interactive "P")
3619 (setq prefix-arg (if (consp arg)
3620 (list (* 4 (car arg)))
3621 (if (eq arg '-)
3622 (list -4)
3623 arg)))
3624 (when (consp prefix-arg) (universal-argument--mode)))
3626 (defun negative-argument (arg)
3627 "Begin a negative numeric argument for the next command.
3628 \\[universal-argument] following digits or minus sign ends the argument."
3629 (interactive "P")
3630 (setq prefix-arg (cond ((integerp arg) (- arg))
3631 ((eq arg '-) nil)
3632 (t '-)))
3633 (universal-argument--mode))
3635 (defun digit-argument (arg)
3636 "Part of the numeric argument for the next command.
3637 \\[universal-argument] following digits or minus sign ends the argument."
3638 (interactive "P")
3639 (let* ((char (if (integerp last-command-event)
3640 last-command-event
3641 (get last-command-event 'ascii-character)))
3642 (digit (- (logand char ?\177) ?0)))
3643 (setq prefix-arg (cond ((integerp arg)
3644 (+ (* arg 10)
3645 (if (< arg 0) (- digit) digit)))
3646 ((eq arg '-)
3647 ;; Treat -0 as just -, so that -01 will work.
3648 (if (zerop digit) '- (- digit)))
3650 digit))))
3651 (universal-argument--mode))
3654 (defvar filter-buffer-substring-functions nil
3655 "This variable is a wrapper hook around `buffer-substring--filter'.")
3656 (make-obsolete-variable 'filter-buffer-substring-functions
3657 'filter-buffer-substring-function "24.4")
3659 (defvar filter-buffer-substring-function #'buffer-substring--filter
3660 "Function to perform the filtering in `filter-buffer-substring'.
3661 The function is called with the same 3 arguments (BEG END DELETE)
3662 that `filter-buffer-substring' received. It should return the
3663 buffer substring between BEG and END, after filtering. If DELETE is
3664 non-nil, it should delete the text between BEG and END from the buffer.")
3666 (defvar buffer-substring-filters nil
3667 "List of filter functions for `buffer-substring--filter'.
3668 Each function must accept a single argument, a string, and return a string.
3669 The buffer substring is passed to the first function in the list,
3670 and the return value of each function is passed to the next.
3671 As a special convention, point is set to the start of the buffer text
3672 being operated on (i.e., the first argument of `buffer-substring--filter')
3673 before these functions are called.")
3674 (make-obsolete-variable 'buffer-substring-filters
3675 'filter-buffer-substring-function "24.1")
3677 (defun filter-buffer-substring (beg end &optional delete)
3678 "Return the buffer substring between BEG and END, after filtering.
3679 If DELETE is non-nil, delete the text between BEG and END from the buffer.
3681 This calls the function that `filter-buffer-substring-function' specifies
3682 \(passing the same three arguments that it received) to do the work,
3683 and returns whatever it does. The default function does no filtering,
3684 unless a hook has been set.
3686 Use `filter-buffer-substring' instead of `buffer-substring',
3687 `buffer-substring-no-properties', or `delete-and-extract-region' when
3688 you want to allow filtering to take place. For example, major or minor
3689 modes can use `filter-buffer-substring-function' to extract characters
3690 that are special to a buffer, and should not be copied into other buffers."
3691 (funcall filter-buffer-substring-function beg end delete))
3693 (defun buffer-substring--filter (beg end &optional delete)
3694 "Default function to use for `filter-buffer-substring-function'.
3695 Its arguments and return value are as specified for `filter-buffer-substring'.
3696 This respects the wrapper hook `filter-buffer-substring-functions',
3697 and the abnormal hook `buffer-substring-filters'.
3698 No filtering is done unless a hook says to."
3699 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
3700 (cond
3701 ((or delete buffer-substring-filters)
3702 (save-excursion
3703 (goto-char beg)
3704 (let ((string (if delete (delete-and-extract-region beg end)
3705 (buffer-substring beg end))))
3706 (dolist (filter buffer-substring-filters)
3707 (setq string (funcall filter string)))
3708 string)))
3710 (buffer-substring beg end)))))
3713 ;;;; Window system cut and paste hooks.
3715 (defvar interprogram-cut-function #'gui-select-text
3716 "Function to call to make a killed region available to other programs.
3717 Most window systems provide a facility for cutting and pasting
3718 text between different programs, such as the clipboard on X and
3719 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3721 This variable holds a function that Emacs calls whenever text is
3722 put in the kill ring, to make the new kill available to other
3723 programs. The function takes one argument, TEXT, which is a
3724 string containing the text which should be made available.")
3726 (defvar interprogram-paste-function #'gui-selection-value
3727 "Function to call to get text cut from other programs.
3728 Most window systems provide a facility for cutting and pasting
3729 text between different programs, such as the clipboard on X and
3730 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3732 This variable holds a function that Emacs calls to obtain text
3733 that other programs have provided for pasting. The function is
3734 called with no arguments. If no other program has provided text
3735 to paste, the function should return nil (in which case the
3736 caller, usually `current-kill', should use the top of the Emacs
3737 kill ring). If another program has provided text to paste, the
3738 function should return that text as a string (in which case the
3739 caller should put this string in the kill ring as the latest
3740 kill).
3742 The function may also return a list of strings if the window
3743 system supports multiple selections. The first string will be
3744 used as the pasted text, but the other will be placed in the kill
3745 ring for easy access via `yank-pop'.
3747 Note that the function should return a string only if a program
3748 other than Emacs has provided a string for pasting; if Emacs
3749 provided the most recent string, the function should return nil.
3750 If it is difficult to tell whether Emacs or some other program
3751 provided the current string, it is probably good enough to return
3752 nil if the string is equal (according to `string=') to the last
3753 text Emacs provided.")
3757 ;;;; The kill ring data structure.
3759 (defvar kill-ring nil
3760 "List of killed text sequences.
3761 Since the kill ring is supposed to interact nicely with cut-and-paste
3762 facilities offered by window systems, use of this variable should
3763 interact nicely with `interprogram-cut-function' and
3764 `interprogram-paste-function'. The functions `kill-new',
3765 `kill-append', and `current-kill' are supposed to implement this
3766 interaction; you may want to use them instead of manipulating the kill
3767 ring directly.")
3769 (defcustom kill-ring-max 60
3770 "Maximum length of kill ring before oldest elements are thrown away."
3771 :type 'integer
3772 :group 'killing)
3774 (defvar kill-ring-yank-pointer nil
3775 "The tail of the kill ring whose car is the last thing yanked.")
3777 (defcustom save-interprogram-paste-before-kill nil
3778 "Save clipboard strings into kill ring before replacing them.
3779 When one selects something in another program to paste it into Emacs,
3780 but kills something in Emacs before actually pasting it,
3781 this selection is gone unless this variable is non-nil,
3782 in which case the other program's selection is saved in the `kill-ring'
3783 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
3784 :type 'boolean
3785 :group 'killing
3786 :version "23.2")
3788 (defcustom kill-do-not-save-duplicates nil
3789 "Do not add a new string to `kill-ring' if it duplicates the last one.
3790 The comparison is done using `equal-including-properties'."
3791 :type 'boolean
3792 :group 'killing
3793 :version "23.2")
3795 (defun kill-new (string &optional replace)
3796 "Make STRING the latest kill in the kill ring.
3797 Set `kill-ring-yank-pointer' to point to it.
3798 If `interprogram-cut-function' is non-nil, apply it to STRING.
3799 Optional second argument REPLACE non-nil means that STRING will replace
3800 the front of the kill ring, rather than being added to the list.
3802 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
3803 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3804 STRING.
3806 When the yank handler has a non-nil PARAM element, the original STRING
3807 argument is not used by `insert-for-yank'. However, since Lisp code
3808 may access and use elements from the kill ring directly, the STRING
3809 argument should still be a \"useful\" string for such uses."
3810 (unless (and kill-do-not-save-duplicates
3811 ;; Due to text properties such as 'yank-handler that
3812 ;; can alter the contents to yank, comparison using
3813 ;; `equal' is unsafe.
3814 (equal-including-properties string (car kill-ring)))
3815 (if (fboundp 'menu-bar-update-yank-menu)
3816 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
3817 (when save-interprogram-paste-before-kill
3818 (let ((interprogram-paste (and interprogram-paste-function
3819 (funcall interprogram-paste-function))))
3820 (when interprogram-paste
3821 (dolist (s (if (listp interprogram-paste)
3822 (nreverse interprogram-paste)
3823 (list interprogram-paste)))
3824 (unless (and kill-do-not-save-duplicates
3825 (equal-including-properties s (car kill-ring)))
3826 (push s kill-ring))))))
3827 (unless (and kill-do-not-save-duplicates
3828 (equal-including-properties string (car kill-ring)))
3829 (if (and replace kill-ring)
3830 (setcar kill-ring string)
3831 (push string kill-ring)
3832 (if (> (length kill-ring) kill-ring-max)
3833 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
3834 (setq kill-ring-yank-pointer kill-ring)
3835 (if interprogram-cut-function
3836 (funcall interprogram-cut-function string)))
3838 ;; It has been argued that this should work similar to `self-insert-command'
3839 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
3840 (defcustom kill-append-merge-undo nil
3841 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
3842 :type 'boolean
3843 :group 'killing
3844 :version "25.1")
3846 (defun kill-append (string before-p)
3847 "Append STRING to the end of the latest kill in the kill ring.
3848 If BEFORE-P is non-nil, prepend STRING to the kill.
3849 Also removes the last undo boundary in the current buffer,
3850 depending on `kill-append-merge-undo'.
3851 If `interprogram-cut-function' is set, pass the resulting kill to it."
3852 (let* ((cur (car kill-ring)))
3853 (kill-new (if before-p (concat string cur) (concat cur string))
3854 (or (= (length cur) 0)
3855 (equal nil (get-text-property 0 'yank-handler cur))))
3856 (when (and kill-append-merge-undo (not buffer-read-only))
3857 (let ((prev buffer-undo-list)
3858 (next (cdr buffer-undo-list)))
3859 ;; find the next undo boundary
3860 (while (car next)
3861 (pop next)
3862 (pop prev))
3863 ;; remove this undo boundary
3864 (when prev
3865 (setcdr prev (cdr next)))))))
3867 (defcustom yank-pop-change-selection nil
3868 "Whether rotating the kill ring changes the window system selection.
3869 If non-nil, whenever the kill ring is rotated (usually via the
3870 `yank-pop' command), Emacs also calls `interprogram-cut-function'
3871 to copy the new kill to the window system selection."
3872 :type 'boolean
3873 :group 'killing
3874 :version "23.1")
3876 (defun current-kill (n &optional do-not-move)
3877 "Rotate the yanking point by N places, and then return that kill.
3878 If N is zero and `interprogram-paste-function' is set to a
3879 function that returns a string or a list of strings, and if that
3880 function doesn't return nil, then that string (or list) is added
3881 to the front of the kill ring and the string (or first string in
3882 the list) is returned as the latest kill.
3884 If N is not zero, and if `yank-pop-change-selection' is
3885 non-nil, use `interprogram-cut-function' to transfer the
3886 kill at the new yank point into the window system selection.
3888 If optional arg DO-NOT-MOVE is non-nil, then don't actually
3889 move the yanking point; just return the Nth kill forward."
3891 (let ((interprogram-paste (and (= n 0)
3892 interprogram-paste-function
3893 (funcall interprogram-paste-function))))
3894 (if interprogram-paste
3895 (progn
3896 ;; Disable the interprogram cut function when we add the new
3897 ;; text to the kill ring, so Emacs doesn't try to own the
3898 ;; selection, with identical text.
3899 (let ((interprogram-cut-function nil))
3900 (if (listp interprogram-paste)
3901 (mapc 'kill-new (nreverse interprogram-paste))
3902 (kill-new interprogram-paste)))
3903 (car kill-ring))
3904 (or kill-ring (error "Kill ring is empty"))
3905 (let ((ARGth-kill-element
3906 (nthcdr (mod (- n (length kill-ring-yank-pointer))
3907 (length kill-ring))
3908 kill-ring)))
3909 (unless do-not-move
3910 (setq kill-ring-yank-pointer ARGth-kill-element)
3911 (when (and yank-pop-change-selection
3912 (> n 0)
3913 interprogram-cut-function)
3914 (funcall interprogram-cut-function (car ARGth-kill-element))))
3915 (car ARGth-kill-element)))))
3919 ;;;; Commands for manipulating the kill ring.
3921 (defcustom kill-read-only-ok nil
3922 "Non-nil means don't signal an error for killing read-only text."
3923 :type 'boolean
3924 :group 'killing)
3926 (defun kill-region (beg end &optional region)
3927 "Kill (\"cut\") text between point and mark.
3928 This deletes the text from the buffer and saves it in the kill ring.
3929 The command \\[yank] can retrieve it from there.
3930 \(If you want to save the region without killing it, use \\[kill-ring-save].)
3932 If you want to append the killed region to the last killed text,
3933 use \\[append-next-kill] before \\[kill-region].
3935 If the buffer is read-only, Emacs will beep and refrain from deleting
3936 the text, but put the text in the kill ring anyway. This means that
3937 you can use the killing commands to copy text from a read-only buffer.
3939 Lisp programs should use this function for killing text.
3940 (To delete text, use `delete-region'.)
3941 Supply two arguments, character positions indicating the stretch of text
3942 to be killed.
3943 Any command that calls this function is a \"kill command\".
3944 If the previous command was also a kill command,
3945 the text killed this time appends to the text killed last time
3946 to make one entry in the kill ring.
3948 The optional argument REGION if non-nil, indicates that we're not just killing
3949 some text between BEG and END, but we're killing the region."
3950 ;; Pass mark first, then point, because the order matters when
3951 ;; calling `kill-append'.
3952 (interactive (list (mark) (point) 'region))
3953 (unless (and beg end)
3954 (error "The mark is not set now, so there is no region"))
3955 (condition-case nil
3956 (let ((string (if region
3957 (funcall region-extract-function 'delete)
3958 (filter-buffer-substring beg end 'delete))))
3959 (when string ;STRING is nil if BEG = END
3960 ;; Add that string to the kill ring, one way or another.
3961 (if (eq last-command 'kill-region)
3962 (kill-append string (< end beg))
3963 (kill-new string)))
3964 (when (or string (eq last-command 'kill-region))
3965 (setq this-command 'kill-region))
3966 (setq deactivate-mark t)
3967 nil)
3968 ((buffer-read-only text-read-only)
3969 ;; The code above failed because the buffer, or some of the characters
3970 ;; in the region, are read-only.
3971 ;; We should beep, in case the user just isn't aware of this.
3972 ;; However, there's no harm in putting
3973 ;; the region's text in the kill ring, anyway.
3974 (copy-region-as-kill beg end region)
3975 ;; Set this-command now, so it will be set even if we get an error.
3976 (setq this-command 'kill-region)
3977 ;; This should barf, if appropriate, and give us the correct error.
3978 (if kill-read-only-ok
3979 (progn (message "Read only text copied to kill ring") nil)
3980 ;; Signal an error if the buffer is read-only.
3981 (barf-if-buffer-read-only)
3982 ;; If the buffer isn't read-only, the text is.
3983 (signal 'text-read-only (list (current-buffer)))))))
3985 ;; copy-region-as-kill no longer sets this-command, because it's confusing
3986 ;; to get two copies of the text when the user accidentally types M-w and
3987 ;; then corrects it with the intended C-w.
3988 (defun copy-region-as-kill (beg end &optional region)
3989 "Save the region as if killed, but don't kill it.
3990 In Transient Mark mode, deactivate the mark.
3991 If `interprogram-cut-function' is non-nil, also save the text for a window
3992 system cut and paste.
3994 The optional argument REGION if non-nil, indicates that we're not just copying
3995 some text between BEG and END, but we're copying the region.
3997 This command's old key binding has been given to `kill-ring-save'."
3998 ;; Pass mark first, then point, because the order matters when
3999 ;; calling `kill-append'.
4000 (interactive (list (mark) (point)
4001 (prefix-numeric-value current-prefix-arg)))
4002 (let ((str (if region
4003 (funcall region-extract-function nil)
4004 (filter-buffer-substring beg end))))
4005 (if (eq last-command 'kill-region)
4006 (kill-append str (< end beg))
4007 (kill-new str)))
4008 (setq deactivate-mark t)
4009 nil)
4011 (defun kill-ring-save (beg end &optional region)
4012 "Save the region as if killed, but don't kill it.
4013 In Transient Mark mode, deactivate the mark.
4014 If `interprogram-cut-function' is non-nil, also save the text for a window
4015 system cut and paste.
4017 If you want to append the killed line to the last killed text,
4018 use \\[append-next-kill] before \\[kill-ring-save].
4020 The optional argument REGION if non-nil, indicates that we're not just copying
4021 some text between BEG and END, but we're copying the region.
4023 This command is similar to `copy-region-as-kill', except that it gives
4024 visual feedback indicating the extent of the region being copied."
4025 ;; Pass mark first, then point, because the order matters when
4026 ;; calling `kill-append'.
4027 (interactive (list (mark) (point)
4028 (prefix-numeric-value current-prefix-arg)))
4029 (copy-region-as-kill beg end region)
4030 ;; This use of called-interactively-p is correct because the code it
4031 ;; controls just gives the user visual feedback.
4032 (if (called-interactively-p 'interactive)
4033 (indicate-copied-region)))
4035 (defun indicate-copied-region (&optional message-len)
4036 "Indicate that the region text has been copied interactively.
4037 If the mark is visible in the selected window, blink the cursor
4038 between point and mark if there is currently no active region
4039 highlighting.
4041 If the mark lies outside the selected window, display an
4042 informative message containing a sample of the copied text. The
4043 optional argument MESSAGE-LEN, if non-nil, specifies the length
4044 of this sample text; it defaults to 40."
4045 (let ((mark (mark t))
4046 (point (point))
4047 ;; Inhibit quitting so we can make a quit here
4048 ;; look like a C-g typed as a command.
4049 (inhibit-quit t))
4050 (if (pos-visible-in-window-p mark (selected-window))
4051 ;; Swap point-and-mark quickly so as to show the region that
4052 ;; was selected. Don't do it if the region is highlighted.
4053 (unless (and (region-active-p)
4054 (face-background 'region))
4055 ;; Swap point and mark.
4056 (set-marker (mark-marker) (point) (current-buffer))
4057 (goto-char mark)
4058 (sit-for blink-matching-delay)
4059 ;; Swap back.
4060 (set-marker (mark-marker) mark (current-buffer))
4061 (goto-char point)
4062 ;; If user quit, deactivate the mark
4063 ;; as C-g would as a command.
4064 (and quit-flag (region-active-p)
4065 (deactivate-mark)))
4066 (let ((len (min (abs (- mark point))
4067 (or message-len 40))))
4068 (if (< point mark)
4069 ;; Don't say "killed"; that is misleading.
4070 (message "Saved text until \"%s\""
4071 (buffer-substring-no-properties (- mark len) mark))
4072 (message "Saved text from \"%s\""
4073 (buffer-substring-no-properties mark (+ mark len))))))))
4075 (defun append-next-kill (&optional interactive)
4076 "Cause following command, if it kills, to add to previous kill.
4077 If the next command kills forward from point, the kill is
4078 appended to the previous killed text. If the command kills
4079 backward, the kill is prepended. Kill commands that act on the
4080 region, such as `kill-region', are regarded as killing forward if
4081 point is after mark, and killing backward if point is before
4082 mark.
4084 If the next command is not a kill command, `append-next-kill' has
4085 no effect.
4087 The argument is used for internal purposes; do not supply one."
4088 (interactive "p")
4089 ;; We don't use (interactive-p), since that breaks kbd macros.
4090 (if interactive
4091 (progn
4092 (setq this-command 'kill-region)
4093 (message "If the next command is a kill, it will append"))
4094 (setq last-command 'kill-region)))
4096 ;; Yanking.
4098 (defcustom yank-handled-properties
4099 '((font-lock-face . yank-handle-font-lock-face-property)
4100 (category . yank-handle-category-property))
4101 "List of special text property handling conditions for yanking.
4102 Each element should have the form (PROP . FUN), where PROP is a
4103 property symbol and FUN is a function. When the `yank' command
4104 inserts text into the buffer, it scans the inserted text for
4105 stretches of text that have `eq' values of the text property
4106 PROP; for each such stretch of text, FUN is called with three
4107 arguments: the property's value in that text, and the start and
4108 end positions of the text.
4110 This is done prior to removing the properties specified by
4111 `yank-excluded-properties'."
4112 :group 'killing
4113 :type '(repeat (cons (symbol :tag "property symbol")
4114 function))
4115 :version "24.3")
4117 ;; This is actually used in subr.el but defcustom does not work there.
4118 (defcustom yank-excluded-properties
4119 '(category field follow-link fontified font-lock-face help-echo
4120 intangible invisible keymap local-map mouse-face read-only
4121 yank-handler)
4122 "Text properties to discard when yanking.
4123 The value should be a list of text properties to discard or t,
4124 which means to discard all text properties.
4126 See also `yank-handled-properties'."
4127 :type '(choice (const :tag "All" t) (repeat symbol))
4128 :group 'killing
4129 :version "24.3")
4131 (defvar yank-window-start nil)
4132 (defvar yank-undo-function nil
4133 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4134 Function is called with two parameters, START and END corresponding to
4135 the value of the mark and point; it is guaranteed that START <= END.
4136 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4138 (defun yank-pop (&optional arg)
4139 "Replace just-yanked stretch of killed text with a different stretch.
4140 This command is allowed only immediately after a `yank' or a `yank-pop'.
4141 At such a time, the region contains a stretch of reinserted
4142 previously-killed text. `yank-pop' deletes that text and inserts in its
4143 place a different stretch of killed text.
4145 With no argument, the previous kill is inserted.
4146 With argument N, insert the Nth previous kill.
4147 If N is negative, this is a more recent kill.
4149 The sequence of kills wraps around, so that after the oldest one
4150 comes the newest one.
4152 When this command inserts killed text into the buffer, it honors
4153 `yank-excluded-properties' and `yank-handler' as described in the
4154 doc string for `insert-for-yank-1', which see."
4155 (interactive "*p")
4156 (if (not (eq last-command 'yank))
4157 (error "Previous command was not a yank"))
4158 (setq this-command 'yank)
4159 (unless arg (setq arg 1))
4160 (let ((inhibit-read-only t)
4161 (before (< (point) (mark t))))
4162 (if before
4163 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4164 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4165 (setq yank-undo-function nil)
4166 (set-marker (mark-marker) (point) (current-buffer))
4167 (insert-for-yank (current-kill arg))
4168 ;; Set the window start back where it was in the yank command,
4169 ;; if possible.
4170 (set-window-start (selected-window) yank-window-start t)
4171 (if before
4172 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4173 ;; It is cleaner to avoid activation, even though the command
4174 ;; loop would deactivate the mark because we inserted text.
4175 (goto-char (prog1 (mark t)
4176 (set-marker (mark-marker) (point) (current-buffer))))))
4177 nil)
4179 (defun yank (&optional arg)
4180 "Reinsert (\"paste\") the last stretch of killed text.
4181 More precisely, reinsert the most recent kill, which is the
4182 stretch of killed text most recently killed OR yanked. Put point
4183 at the end, and set mark at the beginning without activating it.
4184 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4185 With argument N, reinsert the Nth most recent kill.
4187 When this command inserts text into the buffer, it honors the
4188 `yank-handled-properties' and `yank-excluded-properties'
4189 variables, and the `yank-handler' text property. See
4190 `insert-for-yank-1' for details.
4192 See also the command `yank-pop' (\\[yank-pop])."
4193 (interactive "*P")
4194 (setq yank-window-start (window-start))
4195 ;; If we don't get all the way thru, make last-command indicate that
4196 ;; for the following command.
4197 (setq this-command t)
4198 (push-mark (point))
4199 (insert-for-yank (current-kill (cond
4200 ((listp arg) 0)
4201 ((eq arg '-) -2)
4202 (t (1- arg)))))
4203 (if (consp arg)
4204 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4205 ;; It is cleaner to avoid activation, even though the command
4206 ;; loop would deactivate the mark because we inserted text.
4207 (goto-char (prog1 (mark t)
4208 (set-marker (mark-marker) (point) (current-buffer)))))
4209 ;; If we do get all the way thru, make this-command indicate that.
4210 (if (eq this-command t)
4211 (setq this-command 'yank))
4212 nil)
4214 (defun rotate-yank-pointer (arg)
4215 "Rotate the yanking point in the kill ring.
4216 With ARG, rotate that many kills forward (or backward, if negative)."
4217 (interactive "p")
4218 (current-kill arg))
4220 ;; Some kill commands.
4222 ;; Internal subroutine of delete-char
4223 (defun kill-forward-chars (arg)
4224 (if (listp arg) (setq arg (car arg)))
4225 (if (eq arg '-) (setq arg -1))
4226 (kill-region (point) (+ (point) arg)))
4228 ;; Internal subroutine of backward-delete-char
4229 (defun kill-backward-chars (arg)
4230 (if (listp arg) (setq arg (car arg)))
4231 (if (eq arg '-) (setq arg -1))
4232 (kill-region (point) (- (point) arg)))
4234 (defcustom backward-delete-char-untabify-method 'untabify
4235 "The method for untabifying when deleting backward.
4236 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4237 `hungry' -- delete all whitespace, both tabs and spaces;
4238 `all' -- delete all whitespace, including tabs, spaces and newlines;
4239 nil -- just delete one character."
4240 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4241 :version "20.3"
4242 :group 'killing)
4244 (defun backward-delete-char-untabify (arg &optional killp)
4245 "Delete characters backward, changing tabs into spaces.
4246 The exact behavior depends on `backward-delete-char-untabify-method'.
4247 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4248 Interactively, ARG is the prefix arg (default 1)
4249 and KILLP is t if a prefix arg was specified."
4250 (interactive "*p\nP")
4251 (when (eq backward-delete-char-untabify-method 'untabify)
4252 (let ((count arg))
4253 (save-excursion
4254 (while (and (> count 0) (not (bobp)))
4255 (if (= (preceding-char) ?\t)
4256 (let ((col (current-column)))
4257 (forward-char -1)
4258 (setq col (- col (current-column)))
4259 (insert-char ?\s col)
4260 (delete-char 1)))
4261 (forward-char -1)
4262 (setq count (1- count))))))
4263 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4264 ((eq backward-delete-char-untabify-method 'all)
4265 " \t\n\r")))
4266 (n (if skip
4267 (let* ((oldpt (point))
4268 (wh (- oldpt (save-excursion
4269 (skip-chars-backward skip)
4270 (constrain-to-field nil oldpt)))))
4271 (+ arg (if (zerop wh) 0 (1- wh))))
4272 arg)))
4273 ;; Avoid warning about delete-backward-char
4274 (with-no-warnings (delete-backward-char n killp))))
4276 (defun zap-to-char (arg char)
4277 "Kill up to and including ARGth occurrence of CHAR.
4278 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4279 Goes backward if ARG is negative; error if CHAR not found."
4280 (interactive (list (prefix-numeric-value current-prefix-arg)
4281 (read-char "Zap to char: " t)))
4282 ;; Avoid "obsolete" warnings for translation-table-for-input.
4283 (with-no-warnings
4284 (if (char-table-p translation-table-for-input)
4285 (setq char (or (aref translation-table-for-input char) char))))
4286 (kill-region (point) (progn
4287 (search-forward (char-to-string char) nil nil arg)
4288 (point))))
4290 ;; kill-line and its subroutines.
4292 (defcustom kill-whole-line nil
4293 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4294 :type 'boolean
4295 :group 'killing)
4297 (defun kill-line (&optional arg)
4298 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4299 With prefix argument ARG, kill that many lines from point.
4300 Negative arguments kill lines backward.
4301 With zero argument, kills the text before point on the current line.
4303 When calling from a program, nil means \"no arg\",
4304 a number counts as a prefix arg.
4306 To kill a whole line, when point is not at the beginning, type \
4307 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4309 If `show-trailing-whitespace' is non-nil, this command will just
4310 kill the rest of the current line, even if there are only
4311 nonblanks there.
4313 If option `kill-whole-line' is non-nil, then this command kills the whole line
4314 including its terminating newline, when used at the beginning of a line
4315 with no argument. As a consequence, you can always kill a whole line
4316 by typing \\[move-beginning-of-line] \\[kill-line].
4318 If you want to append the killed line to the last killed text,
4319 use \\[append-next-kill] before \\[kill-line].
4321 If the buffer is read-only, Emacs will beep and refrain from deleting
4322 the line, but put the line in the kill ring anyway. This means that
4323 you can use this command to copy text from a read-only buffer.
4324 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4325 even beep.)"
4326 (interactive "P")
4327 (kill-region (point)
4328 ;; It is better to move point to the other end of the kill
4329 ;; before killing. That way, in a read-only buffer, point
4330 ;; moves across the text that is copied to the kill ring.
4331 ;; The choice has no effect on undo now that undo records
4332 ;; the value of point from before the command was run.
4333 (progn
4334 (if arg
4335 (forward-visible-line (prefix-numeric-value arg))
4336 (if (eobp)
4337 (signal 'end-of-buffer nil))
4338 (let ((end
4339 (save-excursion
4340 (end-of-visible-line) (point))))
4341 (if (or (save-excursion
4342 ;; If trailing whitespace is visible,
4343 ;; don't treat it as nothing.
4344 (unless show-trailing-whitespace
4345 (skip-chars-forward " \t" end))
4346 (= (point) end))
4347 (and kill-whole-line (bolp)))
4348 (forward-visible-line 1)
4349 (goto-char end))))
4350 (point))))
4352 (defun kill-whole-line (&optional arg)
4353 "Kill current line.
4354 With prefix ARG, kill that many lines starting from the current line.
4355 If ARG is negative, kill backward. Also kill the preceding newline.
4356 \(This is meant to make \\[repeat] work well with negative arguments.)
4357 If ARG is zero, kill current line but exclude the trailing newline."
4358 (interactive "p")
4359 (or arg (setq arg 1))
4360 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4361 (signal 'end-of-buffer nil))
4362 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4363 (signal 'beginning-of-buffer nil))
4364 (unless (eq last-command 'kill-region)
4365 (kill-new "")
4366 (setq last-command 'kill-region))
4367 (cond ((zerop arg)
4368 ;; We need to kill in two steps, because the previous command
4369 ;; could have been a kill command, in which case the text
4370 ;; before point needs to be prepended to the current kill
4371 ;; ring entry and the text after point appended. Also, we
4372 ;; need to use save-excursion to avoid copying the same text
4373 ;; twice to the kill ring in read-only buffers.
4374 (save-excursion
4375 (kill-region (point) (progn (forward-visible-line 0) (point))))
4376 (kill-region (point) (progn (end-of-visible-line) (point))))
4377 ((< arg 0)
4378 (save-excursion
4379 (kill-region (point) (progn (end-of-visible-line) (point))))
4380 (kill-region (point)
4381 (progn (forward-visible-line (1+ arg))
4382 (unless (bobp) (backward-char))
4383 (point))))
4385 (save-excursion
4386 (kill-region (point) (progn (forward-visible-line 0) (point))))
4387 (kill-region (point)
4388 (progn (forward-visible-line arg) (point))))))
4390 (defun forward-visible-line (arg)
4391 "Move forward by ARG lines, ignoring currently invisible newlines only.
4392 If ARG is negative, move backward -ARG lines.
4393 If ARG is zero, move to the beginning of the current line."
4394 (condition-case nil
4395 (if (> arg 0)
4396 (progn
4397 (while (> arg 0)
4398 (or (zerop (forward-line 1))
4399 (signal 'end-of-buffer nil))
4400 ;; If the newline we just skipped is invisible,
4401 ;; don't count it.
4402 (let ((prop
4403 (get-char-property (1- (point)) 'invisible)))
4404 (if (if (eq buffer-invisibility-spec t)
4405 prop
4406 (or (memq prop buffer-invisibility-spec)
4407 (assq prop buffer-invisibility-spec)))
4408 (setq arg (1+ arg))))
4409 (setq arg (1- arg)))
4410 ;; If invisible text follows, and it is a number of complete lines,
4411 ;; skip it.
4412 (let ((opoint (point)))
4413 (while (and (not (eobp))
4414 (let ((prop
4415 (get-char-property (point) 'invisible)))
4416 (if (eq buffer-invisibility-spec t)
4417 prop
4418 (or (memq prop buffer-invisibility-spec)
4419 (assq prop buffer-invisibility-spec)))))
4420 (goto-char
4421 (if (get-text-property (point) 'invisible)
4422 (or (next-single-property-change (point) 'invisible)
4423 (point-max))
4424 (next-overlay-change (point)))))
4425 (unless (bolp)
4426 (goto-char opoint))))
4427 (let ((first t))
4428 (while (or first (<= arg 0))
4429 (if first
4430 (beginning-of-line)
4431 (or (zerop (forward-line -1))
4432 (signal 'beginning-of-buffer nil)))
4433 ;; If the newline we just moved to is invisible,
4434 ;; don't count it.
4435 (unless (bobp)
4436 (let ((prop
4437 (get-char-property (1- (point)) 'invisible)))
4438 (unless (if (eq buffer-invisibility-spec t)
4439 prop
4440 (or (memq prop buffer-invisibility-spec)
4441 (assq prop buffer-invisibility-spec)))
4442 (setq arg (1+ arg)))))
4443 (setq first nil))
4444 ;; If invisible text follows, and it is a number of complete lines,
4445 ;; skip it.
4446 (let ((opoint (point)))
4447 (while (and (not (bobp))
4448 (let ((prop
4449 (get-char-property (1- (point)) 'invisible)))
4450 (if (eq buffer-invisibility-spec t)
4451 prop
4452 (or (memq prop buffer-invisibility-spec)
4453 (assq prop buffer-invisibility-spec)))))
4454 (goto-char
4455 (if (get-text-property (1- (point)) 'invisible)
4456 (or (previous-single-property-change (point) 'invisible)
4457 (point-min))
4458 (previous-overlay-change (point)))))
4459 (unless (bolp)
4460 (goto-char opoint)))))
4461 ((beginning-of-buffer end-of-buffer)
4462 nil)))
4464 (defun end-of-visible-line ()
4465 "Move to end of current visible line."
4466 (end-of-line)
4467 ;; If the following character is currently invisible,
4468 ;; skip all characters with that same `invisible' property value,
4469 ;; then find the next newline.
4470 (while (and (not (eobp))
4471 (save-excursion
4472 (skip-chars-forward "^\n")
4473 (let ((prop
4474 (get-char-property (point) 'invisible)))
4475 (if (eq buffer-invisibility-spec t)
4476 prop
4477 (or (memq prop buffer-invisibility-spec)
4478 (assq prop buffer-invisibility-spec))))))
4479 (skip-chars-forward "^\n")
4480 (if (get-text-property (point) 'invisible)
4481 (goto-char (or (next-single-property-change (point) 'invisible)
4482 (point-max)))
4483 (goto-char (next-overlay-change (point))))
4484 (end-of-line)))
4486 (defun insert-buffer (buffer)
4487 "Insert after point the contents of BUFFER.
4488 Puts mark after the inserted text.
4489 BUFFER may be a buffer or a buffer name."
4490 (declare (interactive-only insert-buffer-substring))
4491 (interactive
4492 (list
4493 (progn
4494 (barf-if-buffer-read-only)
4495 (read-buffer "Insert buffer: "
4496 (if (eq (selected-window) (next-window))
4497 (other-buffer (current-buffer))
4498 (window-buffer (next-window)))
4499 t))))
4500 (push-mark
4501 (save-excursion
4502 (insert-buffer-substring (get-buffer buffer))
4503 (point)))
4504 nil)
4506 (defun append-to-buffer (buffer start end)
4507 "Append to specified buffer the text of the region.
4508 It is inserted into that buffer before its point.
4510 When calling from a program, give three arguments:
4511 BUFFER (or buffer name), START and END.
4512 START and END specify the portion of the current buffer to be copied."
4513 (interactive
4514 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
4515 (region-beginning) (region-end)))
4516 (let* ((oldbuf (current-buffer))
4517 (append-to (get-buffer-create buffer))
4518 (windows (get-buffer-window-list append-to t t))
4519 point)
4520 (save-excursion
4521 (with-current-buffer append-to
4522 (setq point (point))
4523 (barf-if-buffer-read-only)
4524 (insert-buffer-substring oldbuf start end)
4525 (dolist (window windows)
4526 (when (= (window-point window) point)
4527 (set-window-point window (point))))))))
4529 (defun prepend-to-buffer (buffer start end)
4530 "Prepend to specified buffer the text of the region.
4531 It is inserted into that buffer after its point.
4533 When calling from a program, give three arguments:
4534 BUFFER (or buffer name), START and END.
4535 START and END specify the portion of the current buffer to be copied."
4536 (interactive "BPrepend to buffer: \nr")
4537 (let ((oldbuf (current-buffer)))
4538 (with-current-buffer (get-buffer-create buffer)
4539 (barf-if-buffer-read-only)
4540 (save-excursion
4541 (insert-buffer-substring oldbuf start end)))))
4543 (defun copy-to-buffer (buffer start end)
4544 "Copy to specified buffer the text of the region.
4545 It is inserted into that buffer, replacing existing text there.
4547 When calling from a program, give three arguments:
4548 BUFFER (or buffer name), START and END.
4549 START and END specify the portion of the current buffer to be copied."
4550 (interactive "BCopy to buffer: \nr")
4551 (let ((oldbuf (current-buffer)))
4552 (with-current-buffer (get-buffer-create buffer)
4553 (barf-if-buffer-read-only)
4554 (erase-buffer)
4555 (save-excursion
4556 (insert-buffer-substring oldbuf start end)))))
4558 (define-error 'mark-inactive (purecopy "The mark is not active now"))
4560 (defvar activate-mark-hook nil
4561 "Hook run when the mark becomes active.
4562 It is also run at the end of a command, if the mark is active and
4563 it is possible that the region may have changed.")
4565 (defvar deactivate-mark-hook nil
4566 "Hook run when the mark becomes inactive.")
4568 (defun mark (&optional force)
4569 "Return this buffer's mark value as integer, or nil if never set.
4571 In Transient Mark mode, this function signals an error if
4572 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
4573 or the argument FORCE is non-nil, it disregards whether the mark
4574 is active, and returns an integer or nil in the usual way.
4576 If you are using this in an editing command, you are most likely making
4577 a mistake; see the documentation of `set-mark'."
4578 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
4579 (marker-position (mark-marker))
4580 (signal 'mark-inactive nil)))
4582 ;; Behind display-selections-p.
4584 (defun deactivate-mark (&optional force)
4585 "Deactivate the mark.
4586 If Transient Mark mode is disabled, this function normally does
4587 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
4589 Deactivating the mark sets `mark-active' to nil, updates the
4590 primary selection according to `select-active-regions', and runs
4591 `deactivate-mark-hook'.
4593 If Transient Mark mode was temporarily enabled, reset the value
4594 of the variable `transient-mark-mode'; if this causes Transient
4595 Mark mode to be disabled, don't change `mark-active' to nil or
4596 run `deactivate-mark-hook'."
4597 (when (or (region-active-p) force)
4598 (when (and (if (eq select-active-regions 'only)
4599 (eq (car-safe transient-mark-mode) 'only)
4600 select-active-regions)
4601 (region-active-p)
4602 (display-selections-p))
4603 ;; The var `saved-region-selection', if non-nil, is the text in
4604 ;; the region prior to the last command modifying the buffer.
4605 ;; Set the selection to that, or to the current region.
4606 (cond (saved-region-selection
4607 (gui-set-selection 'PRIMARY saved-region-selection)
4608 (setq saved-region-selection nil))
4609 ;; If another program has acquired the selection, region
4610 ;; deactivation should not clobber it (Bug#11772).
4611 ((and (/= (region-beginning) (region-end))
4612 (or (gui-call gui-selection-owner-p 'PRIMARY)
4613 (null (gui-call gui-selection-exists-p 'PRIMARY))))
4614 (gui-set-selection 'PRIMARY
4615 (funcall region-extract-function nil)))))
4616 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
4617 (cond
4618 ((eq (car-safe transient-mark-mode) 'only)
4619 (setq transient-mark-mode (cdr transient-mark-mode))
4620 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
4621 (kill-local-variable 'transient-mark-mode)))
4622 ((eq transient-mark-mode 'lambda)
4623 (kill-local-variable 'transient-mark-mode)))
4624 (setq mark-active nil)
4625 (run-hooks 'deactivate-mark-hook)
4626 (redisplay--update-region-highlight (selected-window))))
4628 (defun activate-mark (&optional no-tmm)
4629 "Activate the mark.
4630 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
4631 (when (mark t)
4632 (unless (region-active-p)
4633 (force-mode-line-update) ;Refresh toolbar (bug#16382).
4634 (setq mark-active t)
4635 (unless (or transient-mark-mode no-tmm)
4636 (setq-local transient-mark-mode 'lambda))
4637 (run-hooks 'activate-mark-hook))))
4639 (defun set-mark (pos)
4640 "Set this buffer's mark to POS. Don't use this function!
4641 That is to say, don't use this function unless you want
4642 the user to see that the mark has moved, and you want the previous
4643 mark position to be lost.
4645 Normally, when a new mark is set, the old one should go on the stack.
4646 This is why most applications should use `push-mark', not `set-mark'.
4648 Novice Emacs Lisp programmers often try to use the mark for the wrong
4649 purposes. The mark saves a location for the user's convenience.
4650 Most editing commands should not alter the mark.
4651 To remember a location for internal use in the Lisp program,
4652 store it in a Lisp variable. Example:
4654 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
4655 (if pos
4656 (progn
4657 (set-marker (mark-marker) pos (current-buffer))
4658 (activate-mark 'no-tmm))
4659 ;; Normally we never clear mark-active except in Transient Mark mode.
4660 ;; But when we actually clear out the mark value too, we must
4661 ;; clear mark-active in any mode.
4662 (deactivate-mark t)
4663 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
4664 ;; it should never be nil if the mark is nil.
4665 (setq mark-active nil)
4666 (set-marker (mark-marker) nil)))
4668 (defcustom use-empty-active-region nil
4669 "Whether \"region-aware\" commands should act on empty regions.
4670 If nil, region-aware commands treat empty regions as inactive.
4671 If non-nil, region-aware commands treat the region as active as
4672 long as the mark is active, even if the region is empty.
4674 Region-aware commands are those that act on the region if it is
4675 active and Transient Mark mode is enabled, and on the text near
4676 point otherwise."
4677 :type 'boolean
4678 :version "23.1"
4679 :group 'editing-basics)
4681 (defun use-region-p ()
4682 "Return t if the region is active and it is appropriate to act on it.
4683 This is used by commands that act specially on the region under
4684 Transient Mark mode.
4686 The return value is t if Transient Mark mode is enabled and the
4687 mark is active; furthermore, if `use-empty-active-region' is nil,
4688 the region must not be empty. Otherwise, the return value is nil.
4690 For some commands, it may be appropriate to ignore the value of
4691 `use-empty-active-region'; in that case, use `region-active-p'."
4692 (and (region-active-p)
4693 (or use-empty-active-region (> (region-end) (region-beginning)))))
4695 (defun region-active-p ()
4696 "Return t if Transient Mark mode is enabled and the mark is active.
4698 Some commands act specially on the region when Transient Mark
4699 mode is enabled. Usually, such commands should use
4700 `use-region-p' instead of this function, because `use-region-p'
4701 also checks the value of `use-empty-active-region'."
4702 (and transient-mark-mode mark-active
4703 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
4704 ;; without the mark being set (e.g. bug#17324). We really should fix
4705 ;; that problem, but in the mean time, let's make sure we don't say the
4706 ;; region is active when there's no mark.
4707 (mark)))
4710 (defvar redisplay-unhighlight-region-function
4711 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
4713 (defvar redisplay-highlight-region-function
4714 (lambda (start end window rol)
4715 (if (not (overlayp rol))
4716 (let ((nrol (make-overlay start end)))
4717 (funcall redisplay-unhighlight-region-function rol)
4718 (overlay-put nrol 'window window)
4719 (overlay-put nrol 'face 'region)
4720 ;; Normal priority so that a large region doesn't hide all the
4721 ;; overlays within it, but high secondary priority so that if it
4722 ;; ends/starts in the middle of a small overlay, that small overlay
4723 ;; won't hide the region's boundaries.
4724 (overlay-put nrol 'priority '(nil . 100))
4725 nrol)
4726 (unless (and (eq (overlay-buffer rol) (current-buffer))
4727 (eq (overlay-start rol) start)
4728 (eq (overlay-end rol) end))
4729 (move-overlay rol start end (current-buffer)))
4730 rol)))
4732 (defun redisplay--update-region-highlight (window)
4733 (with-current-buffer (window-buffer window)
4734 (let ((rol (window-parameter window 'internal-region-overlay)))
4735 (if (not (region-active-p))
4736 (funcall redisplay-unhighlight-region-function rol)
4737 (let* ((pt (window-point window))
4738 (mark (mark))
4739 (start (min pt mark))
4740 (end (max pt mark))
4741 (new
4742 (funcall redisplay-highlight-region-function
4743 start end window rol)))
4744 (unless (equal new rol)
4745 (set-window-parameter window 'internal-region-overlay
4746 new)))))))
4748 (defun redisplay--update-region-highlights (windows)
4749 (with-demoted-errors "redisplay--update-region-highlights: %S"
4750 (if (null windows)
4751 (redisplay--update-region-highlight (selected-window))
4752 (unless (listp windows) (setq windows (window-list-1 nil nil t)))
4753 (if highlight-nonselected-windows
4754 (mapc #'redisplay--update-region-highlight windows)
4755 (let ((msw (and (window-minibuffer-p) (minibuffer-selected-window))))
4756 (dolist (w windows)
4757 (if (or (eq w (selected-window)) (eq w msw))
4758 (redisplay--update-region-highlight w)
4759 (funcall redisplay-unhighlight-region-function
4760 (window-parameter w 'internal-region-overlay)))))))))
4762 (add-function :before pre-redisplay-function
4763 #'redisplay--update-region-highlights)
4766 (defvar-local mark-ring nil
4767 "The list of former marks of the current buffer, most recent first.")
4768 (put 'mark-ring 'permanent-local t)
4770 (defcustom mark-ring-max 16
4771 "Maximum size of mark ring. Start discarding off end if gets this big."
4772 :type 'integer
4773 :group 'editing-basics)
4775 (defvar global-mark-ring nil
4776 "The list of saved global marks, most recent first.")
4778 (defcustom global-mark-ring-max 16
4779 "Maximum size of global mark ring. \
4780 Start discarding off end if gets this big."
4781 :type 'integer
4782 :group 'editing-basics)
4784 (defun pop-to-mark-command ()
4785 "Jump to mark, and pop a new position for mark off the ring.
4786 \(Does not affect global mark ring)."
4787 (interactive)
4788 (if (null (mark t))
4789 (error "No mark set in this buffer")
4790 (if (= (point) (mark t))
4791 (message "Mark popped"))
4792 (goto-char (mark t))
4793 (pop-mark)))
4795 (defun push-mark-command (arg &optional nomsg)
4796 "Set mark at where point is.
4797 If no prefix ARG and mark is already set there, just activate it.
4798 Display `Mark set' unless the optional second arg NOMSG is non-nil."
4799 (interactive "P")
4800 (let ((mark (mark t)))
4801 (if (or arg (null mark) (/= mark (point)))
4802 (push-mark nil nomsg t)
4803 (activate-mark 'no-tmm)
4804 (unless nomsg
4805 (message "Mark activated")))))
4807 (defcustom set-mark-command-repeat-pop nil
4808 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
4809 That means that C-u \\[set-mark-command] \\[set-mark-command]
4810 will pop the mark twice, and
4811 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
4812 will pop the mark three times.
4814 A value of nil means \\[set-mark-command]'s behavior does not change
4815 after C-u \\[set-mark-command]."
4816 :type 'boolean
4817 :group 'editing-basics)
4819 (defun set-mark-command (arg)
4820 "Set the mark where point is, or jump to the mark.
4821 Setting the mark also alters the region, which is the text
4822 between point and mark; this is the closest equivalent in
4823 Emacs to what some editors call the \"selection\".
4825 With no prefix argument, set the mark at point, and push the
4826 old mark position on local mark ring. Also push the old mark on
4827 global mark ring, if the previous mark was set in another buffer.
4829 When Transient Mark Mode is off, immediately repeating this
4830 command activates `transient-mark-mode' temporarily.
4832 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
4833 jump to the mark, and set the mark from
4834 position popped off the local mark ring (this does not affect the global
4835 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
4836 mark ring (see `pop-global-mark').
4838 If `set-mark-command-repeat-pop' is non-nil, repeating
4839 the \\[set-mark-command] command with no prefix argument pops the next position
4840 off the local (or global) mark ring and jumps there.
4842 With \\[universal-argument] \\[universal-argument] as prefix
4843 argument, unconditionally set mark where point is, even if
4844 `set-mark-command-repeat-pop' is non-nil.
4846 Novice Emacs Lisp programmers often try to use the mark for the wrong
4847 purposes. See the documentation of `set-mark' for more information."
4848 (interactive "P")
4849 (cond ((eq transient-mark-mode 'lambda)
4850 (kill-local-variable 'transient-mark-mode))
4851 ((eq (car-safe transient-mark-mode) 'only)
4852 (deactivate-mark)))
4853 (cond
4854 ((and (consp arg) (> (prefix-numeric-value arg) 4))
4855 (push-mark-command nil))
4856 ((not (eq this-command 'set-mark-command))
4857 (if arg
4858 (pop-to-mark-command)
4859 (push-mark-command t)))
4860 ((and set-mark-command-repeat-pop
4861 (eq last-command 'pop-global-mark)
4862 (not arg))
4863 (setq this-command 'pop-global-mark)
4864 (pop-global-mark))
4865 ((or (and set-mark-command-repeat-pop
4866 (eq last-command 'pop-to-mark-command))
4867 arg)
4868 (setq this-command 'pop-to-mark-command)
4869 (pop-to-mark-command))
4870 ((eq last-command 'set-mark-command)
4871 (if (region-active-p)
4872 (progn
4873 (deactivate-mark)
4874 (message "Mark deactivated"))
4875 (activate-mark)
4876 (message "Mark activated")))
4878 (push-mark-command nil))))
4880 (defun push-mark (&optional location nomsg activate)
4881 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
4882 If the last global mark pushed was not in the current buffer,
4883 also push LOCATION on the global mark ring.
4884 Display `Mark set' unless the optional second arg NOMSG is non-nil.
4886 Novice Emacs Lisp programmers often try to use the mark for the wrong
4887 purposes. See the documentation of `set-mark' for more information.
4889 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
4890 (unless (null (mark t))
4891 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
4892 (when (> (length mark-ring) mark-ring-max)
4893 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
4894 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
4895 (set-marker (mark-marker) (or location (point)) (current-buffer))
4896 ;; Now push the mark on the global mark ring.
4897 (if (and global-mark-ring
4898 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
4899 ;; The last global mark pushed was in this same buffer.
4900 ;; Don't push another one.
4902 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
4903 (when (> (length global-mark-ring) global-mark-ring-max)
4904 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
4905 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
4906 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
4907 (message "Mark set"))
4908 (if (or activate (not transient-mark-mode))
4909 (set-mark (mark t)))
4910 nil)
4912 (defun pop-mark ()
4913 "Pop off mark ring into the buffer's actual mark.
4914 Does not set point. Does nothing if mark ring is empty."
4915 (when mark-ring
4916 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
4917 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
4918 (move-marker (car mark-ring) nil)
4919 (if (null (mark t)) (ding))
4920 (setq mark-ring (cdr mark-ring)))
4921 (deactivate-mark))
4923 (define-obsolete-function-alias
4924 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
4925 (defun exchange-point-and-mark (&optional arg)
4926 "Put the mark where point is now, and point where the mark is now.
4927 This command works even when the mark is not active,
4928 and it reactivates the mark.
4930 If Transient Mark mode is on, a prefix ARG deactivates the mark
4931 if it is active, and otherwise avoids reactivating it. If
4932 Transient Mark mode is off, a prefix ARG enables Transient Mark
4933 mode temporarily."
4934 (interactive "P")
4935 (let ((omark (mark t))
4936 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
4937 (if (null omark)
4938 (error "No mark set in this buffer"))
4939 (set-mark (point))
4940 (goto-char omark)
4941 (cond (temp-highlight
4942 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
4943 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
4944 (not (or arg (region-active-p))))
4945 (deactivate-mark))
4946 (t (activate-mark)))
4947 nil))
4949 (defcustom shift-select-mode t
4950 "When non-nil, shifted motion keys activate the mark momentarily.
4952 While the mark is activated in this way, any shift-translated point
4953 motion key extends the region, and if Transient Mark mode was off, it
4954 is temporarily turned on. Furthermore, the mark will be deactivated
4955 by any subsequent point motion key that was not shift-translated, or
4956 by any action that normally deactivates the mark in Transient Mark mode.
4958 See `this-command-keys-shift-translated' for the meaning of
4959 shift-translation."
4960 :type 'boolean
4961 :group 'editing-basics)
4963 (defun handle-shift-selection ()
4964 "Activate/deactivate mark depending on invocation thru shift translation.
4965 This function is called by `call-interactively' when a command
4966 with a `^' character in its `interactive' spec is invoked, before
4967 running the command itself.
4969 If `shift-select-mode' is enabled and the command was invoked
4970 through shift translation, set the mark and activate the region
4971 temporarily, unless it was already set in this way. See
4972 `this-command-keys-shift-translated' for the meaning of shift
4973 translation.
4975 Otherwise, if the region has been activated temporarily,
4976 deactivate it, and restore the variable `transient-mark-mode' to
4977 its earlier value."
4978 (cond ((and shift-select-mode this-command-keys-shift-translated)
4979 (unless (and mark-active
4980 (eq (car-safe transient-mark-mode) 'only))
4981 (setq-local transient-mark-mode
4982 (cons 'only
4983 (unless (eq transient-mark-mode 'lambda)
4984 transient-mark-mode)))
4985 (push-mark nil nil t)))
4986 ((eq (car-safe transient-mark-mode) 'only)
4987 (setq transient-mark-mode (cdr transient-mark-mode))
4988 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
4989 (kill-local-variable 'transient-mark-mode))
4990 (deactivate-mark))))
4992 (define-minor-mode transient-mark-mode
4993 "Toggle Transient Mark mode.
4994 With a prefix argument ARG, enable Transient Mark mode if ARG is
4995 positive, and disable it otherwise. If called from Lisp, enable
4996 Transient Mark mode if ARG is omitted or nil.
4998 Transient Mark mode is a global minor mode. When enabled, the
4999 region is highlighted whenever the mark is active. The mark is
5000 \"deactivated\" by changing the buffer, and after certain other
5001 operations that set the mark but whose main purpose is something
5002 else--for example, incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
5004 You can also deactivate the mark by typing \\[keyboard-quit] or
5005 \\[keyboard-escape-quit].
5007 Many commands change their behavior when Transient Mark mode is
5008 in effect and the mark is active, by acting on the region instead
5009 of their usual default part of the buffer's text. Examples of
5010 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5011 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5012 To see the documentation of commands which are sensitive to the
5013 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5014 or \"mark.*active\" at the prompt."
5015 :global t
5016 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5017 :variable (default-value 'transient-mark-mode))
5019 (defvar widen-automatically t
5020 "Non-nil means it is ok for commands to call `widen' when they want to.
5021 Some commands will do this in order to go to positions outside
5022 the current accessible part of the buffer.
5024 If `widen-automatically' is nil, these commands will do something else
5025 as a fallback, and won't change the buffer bounds.")
5027 (defvar non-essential nil
5028 "Whether the currently executing code is performing an essential task.
5029 This variable should be non-nil only when running code which should not
5030 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5031 user for a password when we are simply scanning a set of files in the
5032 background or displaying possible completions before the user even asked
5033 for it.")
5035 (defun pop-global-mark ()
5036 "Pop off global mark ring and jump to the top location."
5037 (interactive)
5038 ;; Pop entries which refer to non-existent buffers.
5039 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5040 (setq global-mark-ring (cdr global-mark-ring)))
5041 (or global-mark-ring
5042 (error "No global mark set"))
5043 (let* ((marker (car global-mark-ring))
5044 (buffer (marker-buffer marker))
5045 (position (marker-position marker)))
5046 (setq global-mark-ring (nconc (cdr global-mark-ring)
5047 (list (car global-mark-ring))))
5048 (set-buffer buffer)
5049 (or (and (>= position (point-min))
5050 (<= position (point-max)))
5051 (if widen-automatically
5052 (widen)
5053 (error "Global mark position is outside accessible part of buffer")))
5054 (goto-char position)
5055 (switch-to-buffer buffer)))
5057 (defcustom next-line-add-newlines nil
5058 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5059 :type 'boolean
5060 :version "21.1"
5061 :group 'editing-basics)
5063 (defun next-line (&optional arg try-vscroll)
5064 "Move cursor vertically down ARG lines.
5065 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5066 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5067 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5068 function will not vscroll.
5070 ARG defaults to 1.
5072 If there is no character in the target line exactly under the current column,
5073 the cursor is positioned after the character in that line which spans this
5074 column, or at the end of the line if it is not long enough.
5075 If there is no line in the buffer after this one, behavior depends on the
5076 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5077 to create a line, and moves the cursor to that line. Otherwise it moves the
5078 cursor to the end of the buffer.
5080 If the variable `line-move-visual' is non-nil, this command moves
5081 by display lines. Otherwise, it moves by buffer lines, without
5082 taking variable-width characters or continued lines into account.
5084 The command \\[set-goal-column] can be used to create
5085 a semipermanent goal column for this command.
5086 Then instead of trying to move exactly vertically (or as close as possible),
5087 this command moves to the specified goal column (or as close as possible).
5088 The goal column is stored in the variable `goal-column', which is nil
5089 when there is no goal column. Note that setting `goal-column'
5090 overrides `line-move-visual' and causes this command to move by buffer
5091 lines rather than by display lines."
5092 (declare (interactive-only forward-line))
5093 (interactive "^p\np")
5094 (or arg (setq arg 1))
5095 (if (and next-line-add-newlines (= arg 1))
5096 (if (save-excursion (end-of-line) (eobp))
5097 ;; When adding a newline, don't expand an abbrev.
5098 (let ((abbrev-mode nil))
5099 (end-of-line)
5100 (insert (if use-hard-newlines hard-newline "\n")))
5101 (line-move arg nil nil try-vscroll))
5102 (if (called-interactively-p 'interactive)
5103 (condition-case err
5104 (line-move arg nil nil try-vscroll)
5105 ((beginning-of-buffer end-of-buffer)
5106 (signal (car err) (cdr err))))
5107 (line-move arg nil nil try-vscroll)))
5108 nil)
5110 (defun previous-line (&optional arg try-vscroll)
5111 "Move cursor vertically up ARG lines.
5112 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5113 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5114 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5115 function will not vscroll.
5117 ARG defaults to 1.
5119 If there is no character in the target line exactly over the current column,
5120 the cursor is positioned after the character in that line which spans this
5121 column, or at the end of the line if it is not long enough.
5123 If the variable `line-move-visual' is non-nil, this command moves
5124 by display lines. Otherwise, it moves by buffer lines, without
5125 taking variable-width characters or continued lines into account.
5127 The command \\[set-goal-column] can be used to create
5128 a semipermanent goal column for this command.
5129 Then instead of trying to move exactly vertically (or as close as possible),
5130 this command moves to the specified goal column (or as close as possible).
5131 The goal column is stored in the variable `goal-column', which is nil
5132 when there is no goal column. Note that setting `goal-column'
5133 overrides `line-move-visual' and causes this command to move by buffer
5134 lines rather than by display lines."
5135 (declare (interactive-only
5136 "use `forward-line' with negative argument instead."))
5137 (interactive "^p\np")
5138 (or arg (setq arg 1))
5139 (if (called-interactively-p 'interactive)
5140 (condition-case err
5141 (line-move (- arg) nil nil try-vscroll)
5142 ((beginning-of-buffer end-of-buffer)
5143 (signal (car err) (cdr err))))
5144 (line-move (- arg) nil nil try-vscroll))
5145 nil)
5147 (defcustom track-eol nil
5148 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5149 This means moving to the end of each line moved onto.
5150 The beginning of a blank line does not count as the end of a line.
5151 This has no effect when the variable `line-move-visual' is non-nil."
5152 :type 'boolean
5153 :group 'editing-basics)
5155 (defcustom goal-column nil
5156 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5157 A non-nil setting overrides the variable `line-move-visual', which see."
5158 :type '(choice integer
5159 (const :tag "None" nil))
5160 :group 'editing-basics)
5161 (make-variable-buffer-local 'goal-column)
5163 (defvar temporary-goal-column 0
5164 "Current goal column for vertical motion.
5165 It is the column where point was at the start of the current run
5166 of vertical motion commands.
5168 When moving by visual lines via the function `line-move-visual', it is a cons
5169 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5170 divided by the default column width, and HSCROLL is the number of
5171 columns by which window is scrolled from left margin.
5173 When the `track-eol' feature is doing its job, the value is
5174 `most-positive-fixnum'.")
5176 (defcustom line-move-ignore-invisible t
5177 "Non-nil means commands that move by lines ignore invisible newlines.
5178 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5179 as if newlines that are invisible didn't exist, and count
5180 only visible newlines. Thus, moving across across 2 newlines
5181 one of which is invisible will be counted as a one-line move.
5182 Also, a non-nil value causes invisible text to be ignored when
5183 counting columns for the purposes of keeping point in the same
5184 column by \\[next-line] and \\[previous-line].
5186 Outline mode sets this."
5187 :type 'boolean
5188 :group 'editing-basics)
5190 (defcustom line-move-visual t
5191 "When non-nil, `line-move' moves point by visual lines.
5192 This movement is based on where the cursor is displayed on the
5193 screen, instead of relying on buffer contents alone. It takes
5194 into account variable-width characters and line continuation.
5195 If nil, `line-move' moves point by logical lines.
5196 A non-nil setting of `goal-column' overrides the value of this variable
5197 and forces movement by logical lines.
5198 A window that is horizontally scrolled also forces movement by logical
5199 lines."
5200 :type 'boolean
5201 :group 'editing-basics
5202 :version "23.1")
5204 ;; Only used if display-graphic-p.
5205 (declare-function font-info "font.c" (name &optional frame))
5207 (defun default-font-height ()
5208 "Return the height in pixels of the current buffer's default face font."
5209 (let ((default-font (face-font 'default)))
5210 (cond
5211 ((and (display-multi-font-p)
5212 ;; Avoid calling font-info if the frame's default font was
5213 ;; not changed since the frame was created. That's because
5214 ;; font-info is expensive for some fonts, see bug #14838.
5215 (not (string= (frame-parameter nil 'font) default-font)))
5216 (aref (font-info default-font) 3))
5217 (t (frame-char-height)))))
5219 (defun default-line-height ()
5220 "Return the pixel height of current buffer's default-face text line.
5222 The value includes `line-spacing', if any, defined for the buffer
5223 or the frame."
5224 (let ((dfh (default-font-height))
5225 (lsp (if (display-graphic-p)
5226 (or line-spacing
5227 (default-value 'line-spacing)
5228 (frame-parameter nil 'line-spacing)
5230 0)))
5231 (if (floatp lsp)
5232 (setq lsp (truncate (* (frame-char-height) lsp))))
5233 (+ dfh lsp)))
5235 (defun window-screen-lines ()
5236 "Return the number of screen lines in the text area of the selected window.
5238 This is different from `window-text-height' in that this function counts
5239 lines in units of the height of the font used by the default face displayed
5240 in the window, not in units of the frame's default font, and also accounts
5241 for `line-spacing', if any, defined for the window's buffer or frame.
5243 The value is a floating-point number."
5244 (let ((edges (window-inside-pixel-edges))
5245 (dlh (default-line-height)))
5246 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5248 ;; Returns non-nil if partial move was done.
5249 (defun line-move-partial (arg noerror to-end)
5250 (if (< arg 0)
5251 ;; Move backward (up).
5252 ;; If already vscrolled, reduce vscroll
5253 (let ((vs (window-vscroll nil t))
5254 (dlh (default-line-height)))
5255 (when (> vs dlh)
5256 (set-window-vscroll nil (- vs dlh) t)))
5258 ;; Move forward (down).
5259 (let* ((lh (window-line-height -1))
5260 (rowh (car lh))
5261 (vpos (nth 1 lh))
5262 (ypos (nth 2 lh))
5263 (rbot (nth 3 lh))
5264 (this-lh (window-line-height))
5265 (this-height (car this-lh))
5266 (this-ypos (nth 2 this-lh))
5267 (dlh (default-line-height))
5268 (wslines (window-screen-lines))
5269 (edges (window-inside-pixel-edges))
5270 (winh (- (nth 3 edges) (nth 1 edges) 1))
5271 py vs last-line)
5272 (if (> (mod wslines 1.0) 0.0)
5273 (setq wslines (round (+ wslines 0.5))))
5274 (when (or (null lh)
5275 (>= rbot dlh)
5276 (<= ypos (- dlh))
5277 (null this-lh)
5278 (<= this-ypos (- dlh)))
5279 (unless lh
5280 (let ((wend (pos-visible-in-window-p t nil t)))
5281 (setq rbot (nth 3 wend)
5282 rowh (nth 4 wend)
5283 vpos (nth 5 wend))))
5284 (unless this-lh
5285 (let ((wstart (pos-visible-in-window-p nil nil t)))
5286 (setq this-ypos (nth 2 wstart)
5287 this-height (nth 4 wstart))))
5288 (setq py
5289 (or (nth 1 this-lh)
5290 (let ((ppos (posn-at-point))
5291 col-row)
5292 (setq col-row (posn-actual-col-row ppos))
5293 (if col-row
5294 (- (cdr col-row) (window-vscroll))
5295 (cdr (posn-col-row ppos))))))
5296 ;; VPOS > 0 means the last line is only partially visible.
5297 ;; But if the part that is visible is at least as tall as the
5298 ;; default font, that means the line is actually fully
5299 ;; readable, and something like line-spacing is hidden. So in
5300 ;; that case we accept the last line in the window as still
5301 ;; visible, and consider the margin as starting one line
5302 ;; later.
5303 (if (and vpos (> vpos 0))
5304 (if (and rowh
5305 (>= rowh (default-font-height))
5306 (< rowh dlh))
5307 (setq last-line (min (- wslines scroll-margin) vpos))
5308 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
5309 (cond
5310 ;; If last line of window is fully visible, and vscrolling
5311 ;; more would make this line invisible, move forward.
5312 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
5313 (null this-height)
5314 (<= this-height dlh))
5315 (or (null rbot) (= rbot 0)))
5316 nil)
5317 ;; If cursor is not in the bottom scroll margin, and the
5318 ;; current line is is not too tall, move forward.
5319 ((and (or (null this-height) (<= this-height winh))
5320 vpos
5321 (> vpos 0)
5322 (< py last-line))
5323 nil)
5324 ;; When already vscrolled, we vscroll some more if we can,
5325 ;; or clear vscroll and move forward at end of tall image.
5326 ((> vs 0)
5327 (when (or (and rbot (> rbot 0))
5328 (and this-height (> this-height dlh)))
5329 (set-window-vscroll nil (+ vs dlh) t)))
5330 ;; If cursor just entered the bottom scroll margin, move forward,
5331 ;; but also optionally vscroll one line so redisplay won't recenter.
5332 ((and vpos
5333 (> vpos 0)
5334 (= py last-line))
5335 ;; Don't vscroll if the partially-visible line at window
5336 ;; bottom is not too tall (a.k.a. "just one more text
5337 ;; line"): in that case, we do want redisplay to behave
5338 ;; normally, i.e. recenter or whatever.
5340 ;; Note: ROWH + RBOT from the value returned by
5341 ;; pos-visible-in-window-p give the total height of the
5342 ;; partially-visible glyph row at the end of the window. As
5343 ;; we are dealing with floats, we disregard sub-pixel
5344 ;; discrepancies between that and DLH.
5345 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
5346 (set-window-vscroll nil dlh t))
5347 (line-move-1 arg noerror to-end)
5349 ;; If there are lines above the last line, scroll-up one line.
5350 ((and vpos (> vpos 0))
5351 (scroll-up 1)
5353 ;; Finally, start vscroll.
5355 (set-window-vscroll nil dlh t)))))))
5358 ;; This is like line-move-1 except that it also performs
5359 ;; vertical scrolling of tall images if appropriate.
5360 ;; That is not really a clean thing to do, since it mixes
5361 ;; scrolling with cursor motion. But so far we don't have
5362 ;; a cleaner solution to the problem of making C-n do something
5363 ;; useful given a tall image.
5364 (defun line-move (arg &optional noerror to-end try-vscroll)
5365 "Move forward ARG lines.
5366 If NOERROR, don't signal an error if we can't move ARG lines.
5367 TO-END is unused.
5368 TRY-VSCROLL controls whether to vscroll tall lines: if either
5369 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
5370 not vscroll."
5371 (if noninteractive
5372 (forward-line arg)
5373 (unless (and auto-window-vscroll try-vscroll
5374 ;; Only vscroll for single line moves
5375 (= (abs arg) 1)
5376 ;; Under scroll-conservatively, the display engine
5377 ;; does this better.
5378 (zerop scroll-conservatively)
5379 ;; But don't vscroll in a keyboard macro.
5380 (not defining-kbd-macro)
5381 (not executing-kbd-macro)
5382 (line-move-partial arg noerror to-end))
5383 (set-window-vscroll nil 0 t)
5384 (if (and line-move-visual
5385 ;; Display-based column are incompatible with goal-column.
5386 (not goal-column)
5387 ;; When the text in the window is scrolled to the left,
5388 ;; display-based motion doesn't make sense (because each
5389 ;; logical line occupies exactly one screen line).
5390 (not (> (window-hscroll) 0))
5391 ;; Likewise when the text _was_ scrolled to the left
5392 ;; when the current run of vertical motion commands
5393 ;; started.
5394 (not (and (memq last-command
5395 `(next-line previous-line ,this-command))
5396 auto-hscroll-mode
5397 (numberp temporary-goal-column)
5398 (>= temporary-goal-column
5399 (- (window-width) hscroll-margin)))))
5400 (prog1 (line-move-visual arg noerror)
5401 ;; If we moved into a tall line, set vscroll to make
5402 ;; scrolling through tall images more smooth.
5403 (let ((lh (line-pixel-height))
5404 (edges (window-inside-pixel-edges))
5405 (dlh (default-line-height))
5406 winh)
5407 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
5408 (if (and (< arg 0)
5409 (< (point) (window-start))
5410 (> lh winh))
5411 (set-window-vscroll
5413 (- lh dlh) t))))
5414 (line-move-1 arg noerror to-end)))))
5416 ;; Display-based alternative to line-move-1.
5417 ;; Arg says how many lines to move. The value is t if we can move the
5418 ;; specified number of lines.
5419 (defun line-move-visual (arg &optional noerror)
5420 "Move ARG lines forward.
5421 If NOERROR, don't signal an error if we can't move that many lines."
5422 (let ((opoint (point))
5423 (hscroll (window-hscroll))
5424 target-hscroll)
5425 ;; Check if the previous command was a line-motion command, or if
5426 ;; we were called from some other command.
5427 (if (and (consp temporary-goal-column)
5428 (memq last-command `(next-line previous-line ,this-command)))
5429 ;; If so, there's no need to reset `temporary-goal-column',
5430 ;; but we may need to hscroll.
5431 (if (or (/= (cdr temporary-goal-column) hscroll)
5432 (> (cdr temporary-goal-column) 0))
5433 (setq target-hscroll (cdr temporary-goal-column)))
5434 ;; Otherwise, we should reset `temporary-goal-column'.
5435 (let ((posn (posn-at-point)))
5436 (cond
5437 ;; Handle the `overflow-newline-into-fringe' case:
5438 ((eq (nth 1 posn) 'right-fringe)
5439 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
5440 ((car (posn-x-y posn))
5441 (setq temporary-goal-column
5442 (cons (/ (float (car (posn-x-y posn)))
5443 (frame-char-width))
5444 hscroll))))))
5445 (if target-hscroll
5446 (set-window-hscroll (selected-window) target-hscroll))
5447 ;; vertical-motion can move more than it was asked to if it moves
5448 ;; across display strings with newlines. We don't want to ring
5449 ;; the bell and announce beginning/end of buffer in that case.
5450 (or (and (or (and (>= arg 0)
5451 (>= (vertical-motion
5452 (cons (or goal-column
5453 (if (consp temporary-goal-column)
5454 (car temporary-goal-column)
5455 temporary-goal-column))
5456 arg))
5457 arg))
5458 (and (< arg 0)
5459 (<= (vertical-motion
5460 (cons (or goal-column
5461 (if (consp temporary-goal-column)
5462 (car temporary-goal-column)
5463 temporary-goal-column))
5464 arg))
5465 arg)))
5466 (or (>= arg 0)
5467 (/= (point) opoint)
5468 ;; If the goal column lies on a display string,
5469 ;; `vertical-motion' advances the cursor to the end
5470 ;; of the string. For arg < 0, this can cause the
5471 ;; cursor to get stuck. (Bug#3020).
5472 (= (vertical-motion arg) arg)))
5473 (unless noerror
5474 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
5475 nil)))))
5477 ;; This is the guts of next-line and previous-line.
5478 ;; Arg says how many lines to move.
5479 ;; The value is t if we can move the specified number of lines.
5480 (defun line-move-1 (arg &optional noerror _to-end)
5481 ;; Don't run any point-motion hooks, and disregard intangibility,
5482 ;; for intermediate positions.
5483 (let ((inhibit-point-motion-hooks t)
5484 (opoint (point))
5485 (orig-arg arg))
5486 (if (consp temporary-goal-column)
5487 (setq temporary-goal-column (+ (car temporary-goal-column)
5488 (cdr temporary-goal-column))))
5489 (unwind-protect
5490 (progn
5491 (if (not (memq last-command '(next-line previous-line)))
5492 (setq temporary-goal-column
5493 (if (and track-eol (eolp)
5494 ;; Don't count beg of empty line as end of line
5495 ;; unless we just did explicit end-of-line.
5496 (or (not (bolp)) (eq last-command 'move-end-of-line)))
5497 most-positive-fixnum
5498 (current-column))))
5500 (if (not (or (integerp selective-display)
5501 line-move-ignore-invisible))
5502 ;; Use just newline characters.
5503 ;; Set ARG to 0 if we move as many lines as requested.
5504 (or (if (> arg 0)
5505 (progn (if (> arg 1) (forward-line (1- arg)))
5506 ;; This way of moving forward ARG lines
5507 ;; verifies that we have a newline after the last one.
5508 ;; It doesn't get confused by intangible text.
5509 (end-of-line)
5510 (if (zerop (forward-line 1))
5511 (setq arg 0)))
5512 (and (zerop (forward-line arg))
5513 (bolp)
5514 (setq arg 0)))
5515 (unless noerror
5516 (signal (if (< arg 0)
5517 'beginning-of-buffer
5518 'end-of-buffer)
5519 nil)))
5520 ;; Move by arg lines, but ignore invisible ones.
5521 (let (done)
5522 (while (and (> arg 0) (not done))
5523 ;; If the following character is currently invisible,
5524 ;; skip all characters with that same `invisible' property value.
5525 (while (and (not (eobp)) (invisible-p (point)))
5526 (goto-char (next-char-property-change (point))))
5527 ;; Move a line.
5528 ;; We don't use `end-of-line', since we want to escape
5529 ;; from field boundaries occurring exactly at point.
5530 (goto-char (constrain-to-field
5531 (let ((inhibit-field-text-motion t))
5532 (line-end-position))
5533 (point) t t
5534 'inhibit-line-move-field-capture))
5535 ;; If there's no invisibility here, move over the newline.
5536 (cond
5537 ((eobp)
5538 (if (not noerror)
5539 (signal 'end-of-buffer nil)
5540 (setq done t)))
5541 ((and (> arg 1) ;; Use vertical-motion for last move
5542 (not (integerp selective-display))
5543 (not (invisible-p (point))))
5544 ;; We avoid vertical-motion when possible
5545 ;; because that has to fontify.
5546 (forward-line 1))
5547 ;; Otherwise move a more sophisticated way.
5548 ((zerop (vertical-motion 1))
5549 (if (not noerror)
5550 (signal 'end-of-buffer nil)
5551 (setq done t))))
5552 (unless done
5553 (setq arg (1- arg))))
5554 ;; The logic of this is the same as the loop above,
5555 ;; it just goes in the other direction.
5556 (while (and (< arg 0) (not done))
5557 ;; For completely consistency with the forward-motion
5558 ;; case, we should call beginning-of-line here.
5559 ;; However, if point is inside a field and on a
5560 ;; continued line, the call to (vertical-motion -1)
5561 ;; below won't move us back far enough; then we return
5562 ;; to the same column in line-move-finish, and point
5563 ;; gets stuck -- cyd
5564 (forward-line 0)
5565 (cond
5566 ((bobp)
5567 (if (not noerror)
5568 (signal 'beginning-of-buffer nil)
5569 (setq done t)))
5570 ((and (< arg -1) ;; Use vertical-motion for last move
5571 (not (integerp selective-display))
5572 (not (invisible-p (1- (point)))))
5573 (forward-line -1))
5574 ((zerop (vertical-motion -1))
5575 (if (not noerror)
5576 (signal 'beginning-of-buffer nil)
5577 (setq done t))))
5578 (unless done
5579 (setq arg (1+ arg))
5580 (while (and ;; Don't move over previous invis lines
5581 ;; if our target is the middle of this line.
5582 (or (zerop (or goal-column temporary-goal-column))
5583 (< arg 0))
5584 (not (bobp)) (invisible-p (1- (point))))
5585 (goto-char (previous-char-property-change (point))))))))
5586 ;; This is the value the function returns.
5587 (= arg 0))
5589 (cond ((> arg 0)
5590 ;; If we did not move down as far as desired, at least go
5591 ;; to end of line. Be sure to call point-entered and
5592 ;; point-left-hooks.
5593 (let* ((npoint (prog1 (line-end-position)
5594 (goto-char opoint)))
5595 (inhibit-point-motion-hooks nil))
5596 (goto-char npoint)))
5597 ((< arg 0)
5598 ;; If we did not move up as far as desired,
5599 ;; at least go to beginning of line.
5600 (let* ((npoint (prog1 (line-beginning-position)
5601 (goto-char opoint)))
5602 (inhibit-point-motion-hooks nil))
5603 (goto-char npoint)))
5605 (line-move-finish (or goal-column temporary-goal-column)
5606 opoint (> orig-arg 0)))))))
5608 (defun line-move-finish (column opoint forward)
5609 (let ((repeat t))
5610 (while repeat
5611 ;; Set REPEAT to t to repeat the whole thing.
5612 (setq repeat nil)
5614 (let (new
5615 (old (point))
5616 (line-beg (line-beginning-position))
5617 (line-end
5618 ;; Compute the end of the line
5619 ;; ignoring effectively invisible newlines.
5620 (save-excursion
5621 ;; Like end-of-line but ignores fields.
5622 (skip-chars-forward "^\n")
5623 (while (and (not (eobp)) (invisible-p (point)))
5624 (goto-char (next-char-property-change (point)))
5625 (skip-chars-forward "^\n"))
5626 (point))))
5628 ;; Move to the desired column.
5629 (line-move-to-column (truncate column))
5631 ;; Corner case: suppose we start out in a field boundary in
5632 ;; the middle of a continued line. When we get to
5633 ;; line-move-finish, point is at the start of a new *screen*
5634 ;; line but the same text line; then line-move-to-column would
5635 ;; move us backwards. Test using C-n with point on the "x" in
5636 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
5637 (and forward
5638 (< (point) old)
5639 (goto-char old))
5641 (setq new (point))
5643 ;; Process intangibility within a line.
5644 ;; With inhibit-point-motion-hooks bound to nil, a call to
5645 ;; goto-char moves point past intangible text.
5647 ;; However, inhibit-point-motion-hooks controls both the
5648 ;; intangibility and the point-entered/point-left hooks. The
5649 ;; following hack avoids calling the point-* hooks
5650 ;; unnecessarily. Note that we move *forward* past intangible
5651 ;; text when the initial and final points are the same.
5652 (goto-char new)
5653 (let ((inhibit-point-motion-hooks nil))
5654 (goto-char new)
5656 ;; If intangibility moves us to a different (later) place
5657 ;; in the same line, use that as the destination.
5658 (if (<= (point) line-end)
5659 (setq new (point))
5660 ;; If that position is "too late",
5661 ;; try the previous allowable position.
5662 ;; See if it is ok.
5663 (backward-char)
5664 (if (if forward
5665 ;; If going forward, don't accept the previous
5666 ;; allowable position if it is before the target line.
5667 (< line-beg (point))
5668 ;; If going backward, don't accept the previous
5669 ;; allowable position if it is still after the target line.
5670 (<= (point) line-end))
5671 (setq new (point))
5672 ;; As a last resort, use the end of the line.
5673 (setq new line-end))))
5675 ;; Now move to the updated destination, processing fields
5676 ;; as well as intangibility.
5677 (goto-char opoint)
5678 (let ((inhibit-point-motion-hooks nil))
5679 (goto-char
5680 ;; Ignore field boundaries if the initial and final
5681 ;; positions have the same `field' property, even if the
5682 ;; fields are non-contiguous. This seems to be "nicer"
5683 ;; behavior in many situations.
5684 (if (eq (get-char-property new 'field)
5685 (get-char-property opoint 'field))
5687 (constrain-to-field new opoint t t
5688 'inhibit-line-move-field-capture))))
5690 ;; If all this moved us to a different line,
5691 ;; retry everything within that new line.
5692 (when (or (< (point) line-beg) (> (point) line-end))
5693 ;; Repeat the intangibility and field processing.
5694 (setq repeat t))))))
5696 (defun line-move-to-column (col)
5697 "Try to find column COL, considering invisibility.
5698 This function works only in certain cases,
5699 because what we really need is for `move-to-column'
5700 and `current-column' to be able to ignore invisible text."
5701 (if (zerop col)
5702 (beginning-of-line)
5703 (move-to-column col))
5705 (when (and line-move-ignore-invisible
5706 (not (bolp)) (invisible-p (1- (point))))
5707 (let ((normal-location (point))
5708 (normal-column (current-column)))
5709 ;; If the following character is currently invisible,
5710 ;; skip all characters with that same `invisible' property value.
5711 (while (and (not (eobp))
5712 (invisible-p (point)))
5713 (goto-char (next-char-property-change (point))))
5714 ;; Have we advanced to a larger column position?
5715 (if (> (current-column) normal-column)
5716 ;; We have made some progress towards the desired column.
5717 ;; See if we can make any further progress.
5718 (line-move-to-column (+ (current-column) (- col normal-column)))
5719 ;; Otherwise, go to the place we originally found
5720 ;; and move back over invisible text.
5721 ;; that will get us to the same place on the screen
5722 ;; but with a more reasonable buffer position.
5723 (goto-char normal-location)
5724 (let ((line-beg (line-beginning-position)))
5725 (while (and (not (bolp)) (invisible-p (1- (point))))
5726 (goto-char (previous-char-property-change (point) line-beg))))))))
5728 (defun move-end-of-line (arg)
5729 "Move point to end of current line as displayed.
5730 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5731 If point reaches the beginning or end of buffer, it stops there.
5733 To ignore the effects of the `intangible' text or overlay
5734 property, bind `inhibit-point-motion-hooks' to t.
5735 If there is an image in the current line, this function
5736 disregards newlines that are part of the text on which the image
5737 rests."
5738 (interactive "^p")
5739 (or arg (setq arg 1))
5740 (let (done)
5741 (while (not done)
5742 (let ((newpos
5743 (save-excursion
5744 (let ((goal-column 0)
5745 (line-move-visual nil))
5746 (and (line-move arg t)
5747 ;; With bidi reordering, we may not be at bol,
5748 ;; so make sure we are.
5749 (skip-chars-backward "^\n")
5750 (not (bobp))
5751 (progn
5752 (while (and (not (bobp)) (invisible-p (1- (point))))
5753 (goto-char (previous-single-char-property-change
5754 (point) 'invisible)))
5755 (backward-char 1)))
5756 (point)))))
5757 (goto-char newpos)
5758 (if (and (> (point) newpos)
5759 (eq (preceding-char) ?\n))
5760 (backward-char 1)
5761 (if (and (> (point) newpos) (not (eobp))
5762 (not (eq (following-char) ?\n)))
5763 ;; If we skipped something intangible and now we're not
5764 ;; really at eol, keep going.
5765 (setq arg 1)
5766 (setq done t)))))))
5768 (defun move-beginning-of-line (arg)
5769 "Move point to beginning of current line as displayed.
5770 \(If there's an image in the line, this disregards newlines
5771 which are part of the text that the image rests on.)
5773 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5774 If point reaches the beginning or end of buffer, it stops there.
5775 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5776 (interactive "^p")
5777 (or arg (setq arg 1))
5779 (let ((orig (point))
5780 first-vis first-vis-field-value)
5782 ;; Move by lines, if ARG is not 1 (the default).
5783 (if (/= arg 1)
5784 (let ((line-move-visual nil))
5785 (line-move (1- arg) t)))
5787 ;; Move to beginning-of-line, ignoring fields and invisible text.
5788 (skip-chars-backward "^\n")
5789 (while (and (not (bobp)) (invisible-p (1- (point))))
5790 (goto-char (previous-char-property-change (point)))
5791 (skip-chars-backward "^\n"))
5793 ;; Now find first visible char in the line.
5794 (while (and (< (point) orig) (invisible-p (point)))
5795 (goto-char (next-char-property-change (point) orig)))
5796 (setq first-vis (point))
5798 ;; See if fields would stop us from reaching FIRST-VIS.
5799 (setq first-vis-field-value
5800 (constrain-to-field first-vis orig (/= arg 1) t nil))
5802 (goto-char (if (/= first-vis-field-value first-vis)
5803 ;; If yes, obey them.
5804 first-vis-field-value
5805 ;; Otherwise, move to START with attention to fields.
5806 ;; (It is possible that fields never matter in this case.)
5807 (constrain-to-field (point) orig
5808 (/= arg 1) t nil)))))
5811 ;; Many people have said they rarely use this feature, and often type
5812 ;; it by accident. Maybe it shouldn't even be on a key.
5813 (put 'set-goal-column 'disabled t)
5815 (defun set-goal-column (arg)
5816 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
5817 Those commands will move to this position in the line moved to
5818 rather than trying to keep the same horizontal position.
5819 With a non-nil argument ARG, clears out the goal column
5820 so that \\[next-line] and \\[previous-line] resume vertical motion.
5821 The goal column is stored in the variable `goal-column'."
5822 (interactive "P")
5823 (if arg
5824 (progn
5825 (setq goal-column nil)
5826 (message "No goal column"))
5827 (setq goal-column (current-column))
5828 ;; The older method below can be erroneous if `set-goal-column' is bound
5829 ;; to a sequence containing %
5830 ;;(message (substitute-command-keys
5831 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
5832 ;;goal-column)
5833 (message "%s"
5834 (concat
5835 (format "Goal column %d " goal-column)
5836 (substitute-command-keys
5837 "(use \\[set-goal-column] with an arg to unset it)")))
5840 nil)
5842 ;;; Editing based on visual lines, as opposed to logical lines.
5844 (defun end-of-visual-line (&optional n)
5845 "Move point to end of current visual line.
5846 With argument N not nil or 1, move forward N - 1 visual lines first.
5847 If point reaches the beginning or end of buffer, it stops there.
5848 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5849 (interactive "^p")
5850 (or n (setq n 1))
5851 (if (/= n 1)
5852 (let ((line-move-visual t))
5853 (line-move (1- n) t)))
5854 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
5855 ;; constrain to field boundaries, so we don't either.
5856 (vertical-motion (cons (window-width) 0)))
5858 (defun beginning-of-visual-line (&optional n)
5859 "Move point to beginning of current visual line.
5860 With argument N not nil or 1, move forward N - 1 visual lines first.
5861 If point reaches the beginning or end of buffer, it stops there.
5862 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5863 (interactive "^p")
5864 (or n (setq n 1))
5865 (let ((opoint (point)))
5866 (if (/= n 1)
5867 (let ((line-move-visual t))
5868 (line-move (1- n) t)))
5869 (vertical-motion 0)
5870 ;; Constrain to field boundaries, like `move-beginning-of-line'.
5871 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
5873 (defun kill-visual-line (&optional arg)
5874 "Kill the rest of the visual line.
5875 With prefix argument ARG, kill that many visual lines from point.
5876 If ARG is negative, kill visual lines backward.
5877 If ARG is zero, kill the text before point on the current visual
5878 line.
5880 If you want to append the killed line to the last killed text,
5881 use \\[append-next-kill] before \\[kill-line].
5883 If the buffer is read-only, Emacs will beep and refrain from deleting
5884 the line, but put the line in the kill ring anyway. This means that
5885 you can use this command to copy text from a read-only buffer.
5886 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5887 even beep.)"
5888 (interactive "P")
5889 ;; Like in `kill-line', it's better to move point to the other end
5890 ;; of the kill before killing.
5891 (let ((opoint (point))
5892 (kill-whole-line (and kill-whole-line (bolp))))
5893 (if arg
5894 (vertical-motion (prefix-numeric-value arg))
5895 (end-of-visual-line 1)
5896 (if (= (point) opoint)
5897 (vertical-motion 1)
5898 ;; Skip any trailing whitespace at the end of the visual line.
5899 ;; We used to do this only if `show-trailing-whitespace' is
5900 ;; nil, but that's wrong; the correct thing would be to check
5901 ;; whether the trailing whitespace is highlighted. But, it's
5902 ;; OK to just do this unconditionally.
5903 (skip-chars-forward " \t")))
5904 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
5905 (1+ (point))
5906 (point)))))
5908 (defun next-logical-line (&optional arg try-vscroll)
5909 "Move cursor vertically down ARG lines.
5910 This is identical to `next-line', except that it always moves
5911 by logical lines instead of visual lines, ignoring the value of
5912 the variable `line-move-visual'."
5913 (interactive "^p\np")
5914 (let ((line-move-visual nil))
5915 (with-no-warnings
5916 (next-line arg try-vscroll))))
5918 (defun previous-logical-line (&optional arg try-vscroll)
5919 "Move cursor vertically up ARG lines.
5920 This is identical to `previous-line', except that it always moves
5921 by logical lines instead of visual lines, ignoring the value of
5922 the variable `line-move-visual'."
5923 (interactive "^p\np")
5924 (let ((line-move-visual nil))
5925 (with-no-warnings
5926 (previous-line arg try-vscroll))))
5928 (defgroup visual-line nil
5929 "Editing based on visual lines."
5930 :group 'convenience
5931 :version "23.1")
5933 (defvar visual-line-mode-map
5934 (let ((map (make-sparse-keymap)))
5935 (define-key map [remap kill-line] 'kill-visual-line)
5936 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
5937 (define-key map [remap move-end-of-line] 'end-of-visual-line)
5938 ;; These keybindings interfere with xterm function keys. Are
5939 ;; there any other suitable bindings?
5940 ;; (define-key map "\M-[" 'previous-logical-line)
5941 ;; (define-key map "\M-]" 'next-logical-line)
5942 map))
5944 (defcustom visual-line-fringe-indicators '(nil nil)
5945 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
5946 The value should be a list of the form (LEFT RIGHT), where LEFT
5947 and RIGHT are symbols representing the bitmaps to display, to
5948 indicate wrapped lines, in the left and right fringes respectively.
5949 See also `fringe-indicator-alist'.
5950 The default is not to display fringe indicators for wrapped lines.
5951 This variable does not affect fringe indicators displayed for
5952 other purposes."
5953 :type '(list (choice (const :tag "Hide left indicator" nil)
5954 (const :tag "Left curly arrow" left-curly-arrow)
5955 (symbol :tag "Other bitmap"))
5956 (choice (const :tag "Hide right indicator" nil)
5957 (const :tag "Right curly arrow" right-curly-arrow)
5958 (symbol :tag "Other bitmap")))
5959 :set (lambda (symbol value)
5960 (dolist (buf (buffer-list))
5961 (with-current-buffer buf
5962 (when (and (boundp 'visual-line-mode)
5963 (symbol-value 'visual-line-mode))
5964 (setq fringe-indicator-alist
5965 (cons (cons 'continuation value)
5966 (assq-delete-all
5967 'continuation
5968 (copy-tree fringe-indicator-alist)))))))
5969 (set-default symbol value)))
5971 (defvar visual-line--saved-state nil)
5973 (define-minor-mode visual-line-mode
5974 "Toggle visual line based editing (Visual Line mode).
5975 With a prefix argument ARG, enable Visual Line mode if ARG is
5976 positive, and disable it otherwise. If called from Lisp, enable
5977 the mode if ARG is omitted or nil.
5979 When Visual Line mode is enabled, `word-wrap' is turned on in
5980 this buffer, and simple editing commands are redefined to act on
5981 visual lines, not logical lines. See Info node `Visual Line
5982 Mode' for details."
5983 :keymap visual-line-mode-map
5984 :group 'visual-line
5985 :lighter " Wrap"
5986 (if visual-line-mode
5987 (progn
5988 (set (make-local-variable 'visual-line--saved-state) nil)
5989 ;; Save the local values of some variables, to be restored if
5990 ;; visual-line-mode is turned off.
5991 (dolist (var '(line-move-visual truncate-lines
5992 truncate-partial-width-windows
5993 word-wrap fringe-indicator-alist))
5994 (if (local-variable-p var)
5995 (push (cons var (symbol-value var))
5996 visual-line--saved-state)))
5997 (set (make-local-variable 'line-move-visual) t)
5998 (set (make-local-variable 'truncate-partial-width-windows) nil)
5999 (setq truncate-lines nil
6000 word-wrap t
6001 fringe-indicator-alist
6002 (cons (cons 'continuation visual-line-fringe-indicators)
6003 fringe-indicator-alist)))
6004 (kill-local-variable 'line-move-visual)
6005 (kill-local-variable 'word-wrap)
6006 (kill-local-variable 'truncate-lines)
6007 (kill-local-variable 'truncate-partial-width-windows)
6008 (kill-local-variable 'fringe-indicator-alist)
6009 (dolist (saved visual-line--saved-state)
6010 (set (make-local-variable (car saved)) (cdr saved)))
6011 (kill-local-variable 'visual-line--saved-state)))
6013 (defun turn-on-visual-line-mode ()
6014 (visual-line-mode 1))
6016 (define-globalized-minor-mode global-visual-line-mode
6017 visual-line-mode turn-on-visual-line-mode)
6020 (defun transpose-chars (arg)
6021 "Interchange characters around point, moving forward one character.
6022 With prefix arg ARG, effect is to take character before point
6023 and drag it forward past ARG other characters (backward if ARG negative).
6024 If no argument and at end of line, the previous two chars are exchanged."
6025 (interactive "*P")
6026 (when (and (null arg) (eolp) (not (bobp))
6027 (not (get-text-property (1- (point)) 'read-only)))
6028 (forward-char -1))
6029 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6031 (defun transpose-words (arg)
6032 "Interchange words around point, leaving point at end of them.
6033 With prefix arg ARG, effect is to take word before or around point
6034 and drag it forward past ARG other words (backward if ARG negative).
6035 If ARG is zero, the words around or after point and around or after mark
6036 are interchanged."
6037 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6038 (interactive "*p")
6039 (transpose-subr 'forward-word arg))
6041 (defun transpose-sexps (arg)
6042 "Like \\[transpose-words] but applies to sexps.
6043 Does not work on a sexp that point is in the middle of
6044 if it is a list or string."
6045 (interactive "*p")
6046 (transpose-subr
6047 (lambda (arg)
6048 ;; Here we should try to simulate the behavior of
6049 ;; (cons (progn (forward-sexp x) (point))
6050 ;; (progn (forward-sexp (- x)) (point)))
6051 ;; Except that we don't want to rely on the second forward-sexp
6052 ;; putting us back to where we want to be, since forward-sexp-function
6053 ;; might do funny things like infix-precedence.
6054 (if (if (> arg 0)
6055 (looking-at "\\sw\\|\\s_")
6056 (and (not (bobp))
6057 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6058 ;; Jumping over a symbol. We might be inside it, mind you.
6059 (progn (funcall (if (> arg 0)
6060 'skip-syntax-backward 'skip-syntax-forward)
6061 "w_")
6062 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6063 ;; Otherwise, we're between sexps. Take a step back before jumping
6064 ;; to make sure we'll obey the same precedence no matter which direction
6065 ;; we're going.
6066 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6067 (cons (save-excursion (forward-sexp arg) (point))
6068 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6069 (not (zerop (funcall (if (> arg 0)
6070 'skip-syntax-forward
6071 'skip-syntax-backward)
6072 ".")))))
6073 (point)))))
6074 arg 'special))
6076 (defun transpose-lines (arg)
6077 "Exchange current line and previous line, leaving point after both.
6078 With argument ARG, takes previous line and moves it past ARG lines.
6079 With argument 0, interchanges line point is in with line mark is in."
6080 (interactive "*p")
6081 (transpose-subr (function
6082 (lambda (arg)
6083 (if (> arg 0)
6084 (progn
6085 ;; Move forward over ARG lines,
6086 ;; but create newlines if necessary.
6087 (setq arg (forward-line arg))
6088 (if (/= (preceding-char) ?\n)
6089 (setq arg (1+ arg)))
6090 (if (> arg 0)
6091 (newline arg)))
6092 (forward-line arg))))
6093 arg))
6095 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6096 ;; which seems inconsistent with the ARG /= 0 case.
6097 ;; FIXME document SPECIAL.
6098 (defun transpose-subr (mover arg &optional special)
6099 "Subroutine to do the work of transposing objects.
6100 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6101 moves forward by units of the given object (e.g. forward-sentence,
6102 forward-paragraph). If ARG is zero, exchanges the current object
6103 with the one containing mark. If ARG is an integer, moves the
6104 current object past ARG following (if ARG is positive) or
6105 preceding (if ARG is negative) objects, leaving point after the
6106 current object."
6107 (let ((aux (if special mover
6108 (lambda (x)
6109 (cons (progn (funcall mover x) (point))
6110 (progn (funcall mover (- x)) (point))))))
6111 pos1 pos2)
6112 (cond
6113 ((= arg 0)
6114 (save-excursion
6115 (setq pos1 (funcall aux 1))
6116 (goto-char (or (mark) (error "No mark set in this buffer")))
6117 (setq pos2 (funcall aux 1))
6118 (transpose-subr-1 pos1 pos2))
6119 (exchange-point-and-mark))
6120 ((> arg 0)
6121 (setq pos1 (funcall aux -1))
6122 (setq pos2 (funcall aux arg))
6123 (transpose-subr-1 pos1 pos2)
6124 (goto-char (car pos2)))
6126 (setq pos1 (funcall aux -1))
6127 (goto-char (car pos1))
6128 (setq pos2 (funcall aux arg))
6129 (transpose-subr-1 pos1 pos2)))))
6131 (defun transpose-subr-1 (pos1 pos2)
6132 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6133 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6134 (when (> (car pos1) (car pos2))
6135 (let ((swap pos1))
6136 (setq pos1 pos2 pos2 swap)))
6137 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6138 (atomic-change-group
6139 ;; This sequence of insertions attempts to preserve marker
6140 ;; positions at the start and end of the transposed objects.
6141 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6142 (len1 (- (cdr pos1) (car pos1)))
6143 (len2 (length word))
6144 (boundary (make-marker)))
6145 (set-marker boundary (car pos2))
6146 (goto-char (cdr pos1))
6147 (insert-before-markers word)
6148 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6149 (goto-char boundary)
6150 (insert word)
6151 (goto-char (+ boundary len1))
6152 (delete-region (point) (+ (point) len2))
6153 (set-marker boundary nil))))
6155 (defun backward-word (&optional arg)
6156 "Move backward until encountering the beginning of a word.
6157 With argument ARG, do this that many times.
6158 If ARG is omitted or nil, move point backward one word."
6159 (interactive "^p")
6160 (forward-word (- (or arg 1))))
6162 (defun mark-word (&optional arg allow-extend)
6163 "Set mark ARG words away from point.
6164 The place mark goes is the same place \\[forward-word] would
6165 move to with the same argument.
6166 Interactively, if this command is repeated
6167 or (in Transient Mark mode) if the mark is active,
6168 it marks the next ARG words after the ones already marked."
6169 (interactive "P\np")
6170 (cond ((and allow-extend
6171 (or (and (eq last-command this-command) (mark t))
6172 (region-active-p)))
6173 (setq arg (if arg (prefix-numeric-value arg)
6174 (if (< (mark) (point)) -1 1)))
6175 (set-mark
6176 (save-excursion
6177 (goto-char (mark))
6178 (forward-word arg)
6179 (point))))
6181 (push-mark
6182 (save-excursion
6183 (forward-word (prefix-numeric-value arg))
6184 (point))
6185 nil t))))
6187 (defun kill-word (arg)
6188 "Kill characters forward until encountering the end of a word.
6189 With argument ARG, do this that many times."
6190 (interactive "p")
6191 (kill-region (point) (progn (forward-word arg) (point))))
6193 (defun backward-kill-word (arg)
6194 "Kill characters backward until encountering the beginning of a word.
6195 With argument ARG, do this that many times."
6196 (interactive "p")
6197 (kill-word (- arg)))
6199 (defun current-word (&optional strict really-word)
6200 "Return the symbol or word that point is on (or a nearby one) as a string.
6201 The return value includes no text properties.
6202 If optional arg STRICT is non-nil, return nil unless point is within
6203 or adjacent to a symbol or word. In all cases the value can be nil
6204 if there is no word nearby.
6205 The function, belying its name, normally finds a symbol.
6206 If optional arg REALLY-WORD is non-nil, it finds just a word."
6207 (save-excursion
6208 (let* ((oldpoint (point)) (start (point)) (end (point))
6209 (syntaxes (if really-word "w" "w_"))
6210 (not-syntaxes (concat "^" syntaxes)))
6211 (skip-syntax-backward syntaxes) (setq start (point))
6212 (goto-char oldpoint)
6213 (skip-syntax-forward syntaxes) (setq end (point))
6214 (when (and (eq start oldpoint) (eq end oldpoint)
6215 ;; Point is neither within nor adjacent to a word.
6216 (not strict))
6217 ;; Look for preceding word in same line.
6218 (skip-syntax-backward not-syntaxes (line-beginning-position))
6219 (if (bolp)
6220 ;; No preceding word in same line.
6221 ;; Look for following word in same line.
6222 (progn
6223 (skip-syntax-forward not-syntaxes (line-end-position))
6224 (setq start (point))
6225 (skip-syntax-forward syntaxes)
6226 (setq end (point)))
6227 (setq end (point))
6228 (skip-syntax-backward syntaxes)
6229 (setq start (point))))
6230 ;; If we found something nonempty, return it as a string.
6231 (unless (= start end)
6232 (buffer-substring-no-properties start end)))))
6234 (defcustom fill-prefix nil
6235 "String for filling to insert at front of new line, or nil for none."
6236 :type '(choice (const :tag "None" nil)
6237 string)
6238 :group 'fill)
6239 (make-variable-buffer-local 'fill-prefix)
6240 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
6242 (defcustom auto-fill-inhibit-regexp nil
6243 "Regexp to match lines which should not be auto-filled."
6244 :type '(choice (const :tag "None" nil)
6245 regexp)
6246 :group 'fill)
6248 (defun do-auto-fill ()
6249 "The default value for `normal-auto-fill-function'.
6250 This is the default auto-fill function, some major modes use a different one.
6251 Returns t if it really did any work."
6252 (let (fc justify give-up
6253 (fill-prefix fill-prefix))
6254 (if (or (not (setq justify (current-justification)))
6255 (null (setq fc (current-fill-column)))
6256 (and (eq justify 'left)
6257 (<= (current-column) fc))
6258 (and auto-fill-inhibit-regexp
6259 (save-excursion (beginning-of-line)
6260 (looking-at auto-fill-inhibit-regexp))))
6261 nil ;; Auto-filling not required
6262 (if (memq justify '(full center right))
6263 (save-excursion (unjustify-current-line)))
6265 ;; Choose a fill-prefix automatically.
6266 (when (and adaptive-fill-mode
6267 (or (null fill-prefix) (string= fill-prefix "")))
6268 (let ((prefix
6269 (fill-context-prefix
6270 (save-excursion (fill-forward-paragraph -1) (point))
6271 (save-excursion (fill-forward-paragraph 1) (point)))))
6272 (and prefix (not (equal prefix ""))
6273 ;; Use auto-indentation rather than a guessed empty prefix.
6274 (not (and fill-indent-according-to-mode
6275 (string-match "\\`[ \t]*\\'" prefix)))
6276 (setq fill-prefix prefix))))
6278 (while (and (not give-up) (> (current-column) fc))
6279 ;; Determine where to split the line.
6280 (let* (after-prefix
6281 (fill-point
6282 (save-excursion
6283 (beginning-of-line)
6284 (setq after-prefix (point))
6285 (and fill-prefix
6286 (looking-at (regexp-quote fill-prefix))
6287 (setq after-prefix (match-end 0)))
6288 (move-to-column (1+ fc))
6289 (fill-move-to-break-point after-prefix)
6290 (point))))
6292 ;; See whether the place we found is any good.
6293 (if (save-excursion
6294 (goto-char fill-point)
6295 (or (bolp)
6296 ;; There is no use breaking at end of line.
6297 (save-excursion (skip-chars-forward " ") (eolp))
6298 ;; It is futile to split at the end of the prefix
6299 ;; since we would just insert the prefix again.
6300 (and after-prefix (<= (point) after-prefix))
6301 ;; Don't split right after a comment starter
6302 ;; since we would just make another comment starter.
6303 (and comment-start-skip
6304 (let ((limit (point)))
6305 (beginning-of-line)
6306 (and (re-search-forward comment-start-skip
6307 limit t)
6308 (eq (point) limit))))))
6309 ;; No good place to break => stop trying.
6310 (setq give-up t)
6311 ;; Ok, we have a useful place to break the line. Do it.
6312 (let ((prev-column (current-column)))
6313 ;; If point is at the fill-point, do not `save-excursion'.
6314 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6315 ;; point will end up before it rather than after it.
6316 (if (save-excursion
6317 (skip-chars-backward " \t")
6318 (= (point) fill-point))
6319 (default-indent-new-line t)
6320 (save-excursion
6321 (goto-char fill-point)
6322 (default-indent-new-line t)))
6323 ;; Now do justification, if required
6324 (if (not (eq justify 'left))
6325 (save-excursion
6326 (end-of-line 0)
6327 (justify-current-line justify nil t)))
6328 ;; If making the new line didn't reduce the hpos of
6329 ;; the end of the line, then give up now;
6330 ;; trying again will not help.
6331 (if (>= (current-column) prev-column)
6332 (setq give-up t))))))
6333 ;; Justify last line.
6334 (justify-current-line justify t t)
6335 t)))
6337 (defvar comment-line-break-function 'comment-indent-new-line
6338 "Mode-specific function which line breaks and continues a comment.
6339 This function is called during auto-filling when a comment syntax
6340 is defined.
6341 The function should take a single optional argument, which is a flag
6342 indicating whether it should use soft newlines.")
6344 (defun default-indent-new-line (&optional soft)
6345 "Break line at point and indent.
6346 If a comment syntax is defined, call `comment-indent-new-line'.
6348 The inserted newline is marked hard if variable `use-hard-newlines' is true,
6349 unless optional argument SOFT is non-nil."
6350 (interactive)
6351 (if comment-start
6352 (funcall comment-line-break-function soft)
6353 ;; Insert the newline before removing empty space so that markers
6354 ;; get preserved better.
6355 (if soft (insert-and-inherit ?\n) (newline 1))
6356 (save-excursion (forward-char -1) (delete-horizontal-space))
6357 (delete-horizontal-space)
6359 (if (and fill-prefix (not adaptive-fill-mode))
6360 ;; Blindly trust a non-adaptive fill-prefix.
6361 (progn
6362 (indent-to-left-margin)
6363 (insert-before-markers-and-inherit fill-prefix))
6365 (cond
6366 ;; If there's an adaptive prefix, use it unless we're inside
6367 ;; a comment and the prefix is not a comment starter.
6368 (fill-prefix
6369 (indent-to-left-margin)
6370 (insert-and-inherit fill-prefix))
6371 ;; If we're not inside a comment, just try to indent.
6372 (t (indent-according-to-mode))))))
6374 (defvar normal-auto-fill-function 'do-auto-fill
6375 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6376 Some major modes set this.")
6378 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
6379 ;; `functions' and `hooks' are usually unsafe to set, but setting
6380 ;; auto-fill-function to nil in a file-local setting is safe and
6381 ;; can be useful to prevent auto-filling.
6382 (put 'auto-fill-function 'safe-local-variable 'null)
6384 (define-minor-mode auto-fill-mode
6385 "Toggle automatic line breaking (Auto Fill mode).
6386 With a prefix argument ARG, enable Auto Fill mode if ARG is
6387 positive, and disable it otherwise. If called from Lisp, enable
6388 the mode if ARG is omitted or nil.
6390 When Auto Fill mode is enabled, inserting a space at a column
6391 beyond `current-fill-column' automatically breaks the line at a
6392 previous space.
6394 When `auto-fill-mode' is on, the `auto-fill-function' variable is
6395 non-`nil'.
6397 The value of `normal-auto-fill-function' specifies the function to use
6398 for `auto-fill-function' when turning Auto Fill mode on."
6399 :variable (auto-fill-function
6400 . (lambda (v) (setq auto-fill-function
6401 (if v normal-auto-fill-function)))))
6403 ;; This holds a document string used to document auto-fill-mode.
6404 (defun auto-fill-function ()
6405 "Automatically break line at a previous space, in insertion of text."
6406 nil)
6408 (defun turn-on-auto-fill ()
6409 "Unconditionally turn on Auto Fill mode."
6410 (auto-fill-mode 1))
6412 (defun turn-off-auto-fill ()
6413 "Unconditionally turn off Auto Fill mode."
6414 (auto-fill-mode -1))
6416 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
6418 (defun set-fill-column (arg)
6419 "Set `fill-column' to specified argument.
6420 Use \\[universal-argument] followed by a number to specify a column.
6421 Just \\[universal-argument] as argument means to use the current column."
6422 (interactive
6423 (list (or current-prefix-arg
6424 ;; We used to use current-column silently, but C-x f is too easily
6425 ;; typed as a typo for C-x C-f, so we turned it into an error and
6426 ;; now an interactive prompt.
6427 (read-number "Set fill-column to: " (current-column)))))
6428 (if (consp arg)
6429 (setq arg (current-column)))
6430 (if (not (integerp arg))
6431 ;; Disallow missing argument; it's probably a typo for C-x C-f.
6432 (error "set-fill-column requires an explicit argument")
6433 (message "Fill column set to %d (was %d)" arg fill-column)
6434 (setq fill-column arg)))
6436 (defun set-selective-display (arg)
6437 "Set `selective-display' to ARG; clear it if no arg.
6438 When the value of `selective-display' is a number > 0,
6439 lines whose indentation is >= that value are not displayed.
6440 The variable `selective-display' has a separate value for each buffer."
6441 (interactive "P")
6442 (if (eq selective-display t)
6443 (error "selective-display already in use for marked lines"))
6444 (let ((current-vpos
6445 (save-restriction
6446 (narrow-to-region (point-min) (point))
6447 (goto-char (window-start))
6448 (vertical-motion (window-height)))))
6449 (setq selective-display
6450 (and arg (prefix-numeric-value arg)))
6451 (recenter current-vpos))
6452 (set-window-start (selected-window) (window-start))
6453 (princ "selective-display set to " t)
6454 (prin1 selective-display t)
6455 (princ "." t))
6457 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
6459 (defun toggle-truncate-lines (&optional arg)
6460 "Toggle truncating of long lines for the current buffer.
6461 When truncating is off, long lines are folded.
6462 With prefix argument ARG, truncate long lines if ARG is positive,
6463 otherwise fold them. Note that in side-by-side windows, this
6464 command has no effect if `truncate-partial-width-windows' is
6465 non-nil."
6466 (interactive "P")
6467 (setq truncate-lines
6468 (if (null arg)
6469 (not truncate-lines)
6470 (> (prefix-numeric-value arg) 0)))
6471 (force-mode-line-update)
6472 (unless truncate-lines
6473 (let ((buffer (current-buffer)))
6474 (walk-windows (lambda (window)
6475 (if (eq buffer (window-buffer window))
6476 (set-window-hscroll window 0)))
6477 nil t)))
6478 (message "Truncate long lines %s"
6479 (if truncate-lines "enabled" "disabled")))
6481 (defun toggle-word-wrap (&optional arg)
6482 "Toggle whether to use word-wrapping for continuation lines.
6483 With prefix argument ARG, wrap continuation lines at word boundaries
6484 if ARG is positive, otherwise wrap them at the right screen edge.
6485 This command toggles the value of `word-wrap'. It has no effect
6486 if long lines are truncated."
6487 (interactive "P")
6488 (setq word-wrap
6489 (if (null arg)
6490 (not word-wrap)
6491 (> (prefix-numeric-value arg) 0)))
6492 (force-mode-line-update)
6493 (message "Word wrapping %s"
6494 (if word-wrap "enabled" "disabled")))
6496 (defvar overwrite-mode-textual (purecopy " Ovwrt")
6497 "The string displayed in the mode line when in overwrite mode.")
6498 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
6499 "The string displayed in the mode line when in binary overwrite mode.")
6501 (define-minor-mode overwrite-mode
6502 "Toggle Overwrite mode.
6503 With a prefix argument ARG, enable Overwrite mode if ARG is
6504 positive, and disable it otherwise. If called from Lisp, enable
6505 the mode if ARG is omitted or nil.
6507 When Overwrite mode is enabled, printing characters typed in
6508 replace existing text on a one-for-one basis, rather than pushing
6509 it to the right. At the end of a line, such characters extend
6510 the line. Before a tab, such characters insert until the tab is
6511 filled in. \\[quoted-insert] still inserts characters in
6512 overwrite mode; this is supposed to make it easier to insert
6513 characters when necessary."
6514 :variable (overwrite-mode
6515 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
6517 (define-minor-mode binary-overwrite-mode
6518 "Toggle Binary Overwrite mode.
6519 With a prefix argument ARG, enable Binary Overwrite mode if ARG
6520 is positive, and disable it otherwise. If called from Lisp,
6521 enable the mode if ARG is omitted or nil.
6523 When Binary Overwrite mode is enabled, printing characters typed
6524 in replace existing text. Newlines are not treated specially, so
6525 typing at the end of a line joins the line to the next, with the
6526 typed character between them. Typing before a tab character
6527 simply replaces the tab with the character typed.
6528 \\[quoted-insert] replaces the text at the cursor, just as
6529 ordinary typing characters do.
6531 Note that Binary Overwrite mode is not its own minor mode; it is
6532 a specialization of overwrite mode, entered by setting the
6533 `overwrite-mode' variable to `overwrite-mode-binary'."
6534 :variable (overwrite-mode
6535 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
6537 (define-minor-mode line-number-mode
6538 "Toggle line number display in the mode line (Line Number mode).
6539 With a prefix argument ARG, enable Line Number mode if ARG is
6540 positive, and disable it otherwise. If called from Lisp, enable
6541 the mode if ARG is omitted or nil.
6543 Line numbers do not appear for very large buffers and buffers
6544 with very long lines; see variables `line-number-display-limit'
6545 and `line-number-display-limit-width'."
6546 :init-value t :global t :group 'mode-line)
6548 (define-minor-mode column-number-mode
6549 "Toggle column number display in the mode line (Column Number mode).
6550 With a prefix argument ARG, enable Column Number mode if ARG is
6551 positive, and disable it otherwise.
6553 If called from Lisp, enable the mode if ARG is omitted or nil."
6554 :global t :group 'mode-line)
6556 (define-minor-mode size-indication-mode
6557 "Toggle buffer size display in the mode line (Size Indication mode).
6558 With a prefix argument ARG, enable Size Indication mode if ARG is
6559 positive, and disable it otherwise.
6561 If called from Lisp, enable the mode if ARG is omitted or nil."
6562 :global t :group 'mode-line)
6564 (define-minor-mode auto-save-mode
6565 "Toggle auto-saving in the current buffer (Auto Save mode).
6566 With a prefix argument ARG, enable Auto Save mode if ARG is
6567 positive, and disable it otherwise.
6569 If called from Lisp, enable the mode if ARG is omitted or nil."
6570 :variable ((and buffer-auto-save-file-name
6571 ;; If auto-save is off because buffer has shrunk,
6572 ;; then toggling should turn it on.
6573 (>= buffer-saved-size 0))
6574 . (lambda (val)
6575 (setq buffer-auto-save-file-name
6576 (cond
6577 ((null val) nil)
6578 ((and buffer-file-name auto-save-visited-file-name
6579 (not buffer-read-only))
6580 buffer-file-name)
6581 (t (make-auto-save-file-name))))))
6582 ;; If -1 was stored here, to temporarily turn off saving,
6583 ;; turn it back on.
6584 (and (< buffer-saved-size 0)
6585 (setq buffer-saved-size 0)))
6587 (defgroup paren-blinking nil
6588 "Blinking matching of parens and expressions."
6589 :prefix "blink-matching-"
6590 :group 'paren-matching)
6592 (defcustom blink-matching-paren t
6593 "Non-nil means show matching open-paren when close-paren is inserted.
6594 If t, highlight the paren. If `jump', move cursor to its position."
6595 :type '(choice
6596 (const :tag "Disable" nil)
6597 (const :tag "Highlight" t)
6598 (const :tag "Move cursor" jump))
6599 :group 'paren-blinking)
6601 (defcustom blink-matching-paren-on-screen t
6602 "Non-nil means show matching open-paren when it is on screen.
6603 If nil, don't show it (but the open-paren can still be shown
6604 when it is off screen).
6606 This variable has no effect if `blink-matching-paren' is nil.
6607 \(In that case, the open-paren is never shown.)
6608 It is also ignored if `show-paren-mode' is enabled."
6609 :type 'boolean
6610 :group 'paren-blinking)
6612 (defcustom blink-matching-paren-distance (* 100 1024)
6613 "If non-nil, maximum distance to search backwards for matching open-paren.
6614 If nil, search stops at the beginning of the accessible portion of the buffer."
6615 :version "23.2" ; 25->100k
6616 :type '(choice (const nil) integer)
6617 :group 'paren-blinking)
6619 (defcustom blink-matching-delay 1
6620 "Time in seconds to delay after showing a matching paren."
6621 :type 'number
6622 :group 'paren-blinking)
6624 (defcustom blink-matching-paren-dont-ignore-comments nil
6625 "If nil, `blink-matching-paren' ignores comments.
6626 More precisely, when looking for the matching parenthesis,
6627 it skips the contents of comments that end before point."
6628 :type 'boolean
6629 :group 'paren-blinking)
6631 (defun blink-matching-check-mismatch (start end)
6632 "Return whether or not START...END are matching parens.
6633 END is the current point and START is the blink position.
6634 START might be nil if no matching starter was found.
6635 Returns non-nil if we find there is a mismatch."
6636 (let* ((end-syntax (syntax-after (1- end)))
6637 (matching-paren (and (consp end-syntax)
6638 (eq (syntax-class end-syntax) 5)
6639 (cdr end-syntax))))
6640 ;; For self-matched chars like " and $, we can't know when they're
6641 ;; mismatched or unmatched, so we can only do it for parens.
6642 (when matching-paren
6643 (not (and start
6645 (eq (char-after start) matching-paren)
6646 ;; The cdr might hold a new paren-class info rather than
6647 ;; a matching-char info, in which case the two CDRs
6648 ;; should match.
6649 (eq matching-paren (cdr-safe (syntax-after start)))))))))
6651 (defvar blink-matching-check-function #'blink-matching-check-mismatch
6652 "Function to check parentheses mismatches.
6653 The function takes two arguments (START and END) where START is the
6654 position just before the opening token and END is the position right after.
6655 START can be nil, if it was not found.
6656 The function should return non-nil if the two tokens do not match.")
6658 (defvar blink-matching--overlay
6659 (let ((ol (make-overlay (point) (point) nil t)))
6660 (overlay-put ol 'face 'show-paren-match)
6661 (delete-overlay ol)
6663 "Overlay used to highlight the matching paren.")
6665 (defun blink-matching-open ()
6666 "Momentarily highlight the beginning of the sexp before point."
6667 (interactive)
6668 (when (and (not (bobp))
6669 blink-matching-paren)
6670 (let* ((oldpos (point))
6671 (message-log-max nil) ; Don't log messages about paren matching.
6672 (blinkpos
6673 (save-excursion
6674 (save-restriction
6675 (if blink-matching-paren-distance
6676 (narrow-to-region
6677 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
6678 (- (point) blink-matching-paren-distance))
6679 oldpos))
6680 (let ((parse-sexp-ignore-comments
6681 (and parse-sexp-ignore-comments
6682 (not blink-matching-paren-dont-ignore-comments))))
6683 (condition-case ()
6684 (progn
6685 (syntax-propertize (point))
6686 (forward-sexp -1)
6687 ;; backward-sexp skips backward over prefix chars,
6688 ;; so move back to the matching paren.
6689 (while (and (< (point) (1- oldpos))
6690 (let ((code (syntax-after (point))))
6691 (or (eq (syntax-class code) 6)
6692 (eq (logand 1048576 (car code))
6693 1048576))))
6694 (forward-char 1))
6695 (point))
6696 (error nil))))))
6697 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
6698 (cond
6699 (mismatch
6700 (if blinkpos
6701 (if (minibufferp)
6702 (minibuffer-message "Mismatched parentheses")
6703 (message "Mismatched parentheses"))
6704 (if (minibufferp)
6705 (minibuffer-message "No matching parenthesis found")
6706 (message "No matching parenthesis found"))))
6707 ((not blinkpos) nil)
6708 ((pos-visible-in-window-p blinkpos)
6709 ;; Matching open within window, temporarily move to or highlight
6710 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
6711 ;; is non-nil.
6712 (and blink-matching-paren-on-screen
6713 (not show-paren-mode)
6714 (if (eq blink-matching-paren 'jump)
6715 (save-excursion
6716 (goto-char blinkpos)
6717 (sit-for blink-matching-delay))
6718 (unwind-protect
6719 (progn
6720 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
6721 (current-buffer))
6722 (sit-for blink-matching-delay))
6723 (delete-overlay blink-matching--overlay)))))
6725 (save-excursion
6726 (goto-char blinkpos)
6727 (let ((open-paren-line-string
6728 ;; Show what precedes the open in its line, if anything.
6729 (cond
6730 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
6731 (buffer-substring (line-beginning-position)
6732 (1+ blinkpos)))
6733 ;; Show what follows the open in its line, if anything.
6734 ((save-excursion
6735 (forward-char 1)
6736 (skip-chars-forward " \t")
6737 (not (eolp)))
6738 (buffer-substring blinkpos
6739 (line-end-position)))
6740 ;; Otherwise show the previous nonblank line,
6741 ;; if there is one.
6742 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
6743 (concat
6744 (buffer-substring (progn
6745 (skip-chars-backward "\n \t")
6746 (line-beginning-position))
6747 (progn (end-of-line)
6748 (skip-chars-backward " \t")
6749 (point)))
6750 ;; Replace the newline and other whitespace with `...'.
6751 "..."
6752 (buffer-substring blinkpos (1+ blinkpos))))
6753 ;; There is nothing to show except the char itself.
6754 (t (buffer-substring blinkpos (1+ blinkpos))))))
6755 (message "Matches %s"
6756 (substring-no-properties open-paren-line-string)))))))))
6758 (defvar blink-paren-function 'blink-matching-open
6759 "Function called, if non-nil, whenever a close parenthesis is inserted.
6760 More precisely, a char with closeparen syntax is self-inserted.")
6762 (defun blink-paren-post-self-insert-function ()
6763 (when (and (eq (char-before) last-command-event) ; Sanity check.
6764 (memq (char-syntax last-command-event) '(?\) ?\$))
6765 blink-paren-function
6766 (not executing-kbd-macro)
6767 (not noninteractive)
6768 ;; Verify an even number of quoting characters precede the close.
6769 (= 1 (logand 1 (- (point)
6770 (save-excursion
6771 (forward-char -1)
6772 (skip-syntax-backward "/\\")
6773 (point))))))
6774 (funcall blink-paren-function)))
6776 (put 'blink-paren-post-self-insert-function 'priority 100)
6778 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
6779 ;; Most likely, this hook is nil, so this arg doesn't matter,
6780 ;; but I use it as a reminder that this function usually
6781 ;; likes to be run after others since it does
6782 ;; `sit-for'. That's also the reason it get a `priority' prop
6783 ;; of 100.
6784 'append)
6786 ;; This executes C-g typed while Emacs is waiting for a command.
6787 ;; Quitting out of a program does not go through here;
6788 ;; that happens in the QUIT macro at the C code level.
6789 (defun keyboard-quit ()
6790 "Signal a `quit' condition.
6791 During execution of Lisp code, this character causes a quit directly.
6792 At top-level, as an editor command, this simply beeps."
6793 (interactive)
6794 ;; Avoid adding the region to the window selection.
6795 (setq saved-region-selection nil)
6796 (let (select-active-regions)
6797 (deactivate-mark))
6798 (if (fboundp 'kmacro-keyboard-quit)
6799 (kmacro-keyboard-quit))
6800 (when completion-in-region-mode
6801 (completion-in-region-mode -1))
6802 ;; Force the next redisplay cycle to remove the "Def" indicator from
6803 ;; all the mode lines.
6804 (if defining-kbd-macro
6805 (force-mode-line-update t))
6806 (setq defining-kbd-macro nil)
6807 (let ((debug-on-quit nil))
6808 (signal 'quit nil)))
6810 (defvar buffer-quit-function nil
6811 "Function to call to \"quit\" the current buffer, or nil if none.
6812 \\[keyboard-escape-quit] calls this function when its more local actions
6813 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
6815 (defun keyboard-escape-quit ()
6816 "Exit the current \"mode\" (in a generalized sense of the word).
6817 This command can exit an interactive command such as `query-replace',
6818 can clear out a prefix argument or a region,
6819 can get out of the minibuffer or other recursive edit,
6820 cancel the use of the current buffer (for special-purpose buffers),
6821 or go back to just one window (by deleting all but the selected window)."
6822 (interactive)
6823 (cond ((eq last-command 'mode-exited) nil)
6824 ((region-active-p)
6825 (deactivate-mark))
6826 ((> (minibuffer-depth) 0)
6827 (abort-recursive-edit))
6828 (current-prefix-arg
6829 nil)
6830 ((> (recursion-depth) 0)
6831 (exit-recursive-edit))
6832 (buffer-quit-function
6833 (funcall buffer-quit-function))
6834 ((not (one-window-p t))
6835 (delete-other-windows))
6836 ((string-match "^ \\*" (buffer-name (current-buffer)))
6837 (bury-buffer))))
6839 (defun play-sound-file (file &optional volume device)
6840 "Play sound stored in FILE.
6841 VOLUME and DEVICE correspond to the keywords of the sound
6842 specification for `play-sound'."
6843 (interactive "fPlay sound file: ")
6844 (let ((sound (list :file file)))
6845 (if volume
6846 (plist-put sound :volume volume))
6847 (if device
6848 (plist-put sound :device device))
6849 (push 'sound sound)
6850 (play-sound sound)))
6853 (defcustom read-mail-command 'rmail
6854 "Your preference for a mail reading package.
6855 This is used by some keybindings which support reading mail.
6856 See also `mail-user-agent' concerning sending mail."
6857 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
6858 (function-item :tag "Gnus" :format "%t\n" gnus)
6859 (function-item :tag "Emacs interface to MH"
6860 :format "%t\n" mh-rmail)
6861 (function :tag "Other"))
6862 :version "21.1"
6863 :group 'mail)
6865 (defcustom mail-user-agent 'message-user-agent
6866 "Your preference for a mail composition package.
6867 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
6868 outgoing email message. This variable lets you specify which
6869 mail-sending package you prefer.
6871 Valid values include:
6873 `message-user-agent' -- use the Message package.
6874 See Info node `(message)'.
6875 `sendmail-user-agent' -- use the Mail package.
6876 See Info node `(emacs)Sending Mail'.
6877 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
6878 See Info node `(mh-e)'.
6879 `gnus-user-agent' -- like `message-user-agent', but with Gnus
6880 paraphernalia if Gnus is running, particularly
6881 the Gcc: header for archiving.
6883 Additional valid symbols may be available; check with the author of
6884 your package for details. The function should return non-nil if it
6885 succeeds.
6887 See also `read-mail-command' concerning reading mail."
6888 :type '(radio (function-item :tag "Message package"
6889 :format "%t\n"
6890 message-user-agent)
6891 (function-item :tag "Mail package"
6892 :format "%t\n"
6893 sendmail-user-agent)
6894 (function-item :tag "Emacs interface to MH"
6895 :format "%t\n"
6896 mh-e-user-agent)
6897 (function-item :tag "Message with full Gnus features"
6898 :format "%t\n"
6899 gnus-user-agent)
6900 (function :tag "Other"))
6901 :version "23.2" ; sendmail->message
6902 :group 'mail)
6904 (defcustom compose-mail-user-agent-warnings t
6905 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
6906 If the value of `mail-user-agent' is the default, and the user
6907 appears to have customizations applying to the old default,
6908 `compose-mail' issues a warning."
6909 :type 'boolean
6910 :version "23.2"
6911 :group 'mail)
6913 (defun rfc822-goto-eoh ()
6914 "If the buffer starts with a mail header, move point to the header's end.
6915 Otherwise, moves to `point-min'.
6916 The end of the header is the start of the next line, if there is one,
6917 else the end of the last line. This function obeys RFC822."
6918 (goto-char (point-min))
6919 (when (re-search-forward
6920 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
6921 (goto-char (match-beginning 0))))
6923 ;; Used by Rmail (e.g., rmail-forward).
6924 (defvar mail-encode-mml nil
6925 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
6926 the outgoing message before sending it.")
6928 (defun compose-mail (&optional to subject other-headers continue
6929 switch-function yank-action send-actions
6930 return-action)
6931 "Start composing a mail message to send.
6932 This uses the user's chosen mail composition package
6933 as selected with the variable `mail-user-agent'.
6934 The optional arguments TO and SUBJECT specify recipients
6935 and the initial Subject field, respectively.
6937 OTHER-HEADERS is an alist specifying additional
6938 header fields. Elements look like (HEADER . VALUE) where both
6939 HEADER and VALUE are strings.
6941 CONTINUE, if non-nil, says to continue editing a message already
6942 being composed. Interactively, CONTINUE is the prefix argument.
6944 SWITCH-FUNCTION, if non-nil, is a function to use to
6945 switch to and display the buffer used for mail composition.
6947 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
6948 to insert the raw text of the message being replied to.
6949 It has the form (FUNCTION . ARGS). The user agent will apply
6950 FUNCTION to ARGS, to insert the raw text of the original message.
6951 \(The user agent will also run `mail-citation-hook', *after* the
6952 original text has been inserted in this way.)
6954 SEND-ACTIONS is a list of actions to call when the message is sent.
6955 Each action has the form (FUNCTION . ARGS).
6957 RETURN-ACTION, if non-nil, is an action for returning to the
6958 caller. It has the form (FUNCTION . ARGS). The function is
6959 called after the mail has been sent or put aside, and the mail
6960 buffer buried."
6961 (interactive
6962 (list nil nil nil current-prefix-arg))
6964 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
6965 ;; from sendmail-user-agent to message-user-agent. Some users may
6966 ;; encounter incompatibilities. This hack tries to detect problems
6967 ;; and warn about them.
6968 (and compose-mail-user-agent-warnings
6969 (eq mail-user-agent 'message-user-agent)
6970 (let (warn-vars)
6971 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
6972 mail-yank-hooks mail-archive-file-name
6973 mail-default-reply-to mail-mailing-lists
6974 mail-self-blind))
6975 (and (boundp var)
6976 (symbol-value var)
6977 (push var warn-vars)))
6978 (when warn-vars
6979 (display-warning 'mail
6980 (format "\
6981 The default mail mode is now Message mode.
6982 You have the following Mail mode variable%s customized:
6983 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
6984 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
6985 (if (> (length warn-vars) 1) "s" "")
6986 (mapconcat 'symbol-name
6987 warn-vars " "))))))
6989 (let ((function (get mail-user-agent 'composefunc)))
6990 (funcall function to subject other-headers continue switch-function
6991 yank-action send-actions return-action)))
6993 (defun compose-mail-other-window (&optional to subject other-headers continue
6994 yank-action send-actions
6995 return-action)
6996 "Like \\[compose-mail], but edit the outgoing message in another window."
6997 (interactive (list nil nil nil current-prefix-arg))
6998 (compose-mail to subject other-headers continue
6999 'switch-to-buffer-other-window yank-action send-actions
7000 return-action))
7002 (defun compose-mail-other-frame (&optional to subject other-headers continue
7003 yank-action send-actions
7004 return-action)
7005 "Like \\[compose-mail], but edit the outgoing message in another frame."
7006 (interactive (list nil nil nil current-prefix-arg))
7007 (compose-mail to subject other-headers continue
7008 'switch-to-buffer-other-frame yank-action send-actions
7009 return-action))
7012 (defvar set-variable-value-history nil
7013 "History of values entered with `set-variable'.
7015 Maximum length of the history list is determined by the value
7016 of `history-length', which see.")
7018 (defun set-variable (variable value &optional make-local)
7019 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7020 VARIABLE should be a user option variable name, a Lisp variable
7021 meant to be customized by users. You should enter VALUE in Lisp syntax,
7022 so if you want VALUE to be a string, you must surround it with doublequotes.
7023 VALUE is used literally, not evaluated.
7025 If VARIABLE has a `variable-interactive' property, that is used as if
7026 it were the arg to `interactive' (which see) to interactively read VALUE.
7028 If VARIABLE has been defined with `defcustom', then the type information
7029 in the definition is used to check that VALUE is valid.
7031 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7032 (interactive
7033 (let* ((default-var (variable-at-point))
7034 (var (if (custom-variable-p default-var)
7035 (read-variable (format "Set variable (default %s): " default-var)
7036 default-var)
7037 (read-variable "Set variable: ")))
7038 (minibuffer-help-form '(describe-variable var))
7039 (prop (get var 'variable-interactive))
7040 (obsolete (car (get var 'byte-obsolete-variable)))
7041 (prompt (format "Set %s %s to value: " var
7042 (cond ((local-variable-p var)
7043 "(buffer-local)")
7044 ((or current-prefix-arg
7045 (local-variable-if-set-p var))
7046 "buffer-locally")
7047 (t "globally"))))
7048 (val (progn
7049 (when obsolete
7050 (message (concat "`%S' is obsolete; "
7051 (if (symbolp obsolete) "use `%S' instead" "%s"))
7052 var obsolete)
7053 (sit-for 3))
7054 (if prop
7055 ;; Use VAR's `variable-interactive' property
7056 ;; as an interactive spec for prompting.
7057 (call-interactively `(lambda (arg)
7058 (interactive ,prop)
7059 arg))
7060 (read-from-minibuffer prompt nil
7061 read-expression-map t
7062 'set-variable-value-history
7063 (format "%S" (symbol-value var)))))))
7064 (list var val current-prefix-arg)))
7066 (and (custom-variable-p variable)
7067 (not (get variable 'custom-type))
7068 (custom-load-symbol variable))
7069 (let ((type (get variable 'custom-type)))
7070 (when type
7071 ;; Match with custom type.
7072 (require 'cus-edit)
7073 (setq type (widget-convert type))
7074 (unless (widget-apply type :match value)
7075 (error "Value `%S' does not match type %S of %S"
7076 value (car type) variable))))
7078 (if make-local
7079 (make-local-variable variable))
7081 (set variable value)
7083 ;; Force a thorough redisplay for the case that the variable
7084 ;; has an effect on the display, like `tab-width' has.
7085 (force-mode-line-update))
7087 ;; Define the major mode for lists of completions.
7089 (defvar completion-list-mode-map
7090 (let ((map (make-sparse-keymap)))
7091 (define-key map [mouse-2] 'choose-completion)
7092 (define-key map [follow-link] 'mouse-face)
7093 (define-key map [down-mouse-2] nil)
7094 (define-key map "\C-m" 'choose-completion)
7095 (define-key map "\e\e\e" 'delete-completion-window)
7096 (define-key map [left] 'previous-completion)
7097 (define-key map [right] 'next-completion)
7098 (define-key map [?\t] 'next-completion)
7099 (define-key map [backtab] 'previous-completion)
7100 (define-key map "q" 'quit-window)
7101 (define-key map "z" 'kill-this-buffer)
7102 map)
7103 "Local map for completion list buffers.")
7105 ;; Completion mode is suitable only for specially formatted data.
7106 (put 'completion-list-mode 'mode-class 'special)
7108 (defvar completion-reference-buffer nil
7109 "Record the buffer that was current when the completion list was requested.
7110 This is a local variable in the completion list buffer.
7111 Initial value is nil to avoid some compiler warnings.")
7113 (defvar completion-no-auto-exit nil
7114 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7115 This also applies to other functions such as `choose-completion'.")
7117 (defvar completion-base-position nil
7118 "Position of the base of the text corresponding to the shown completions.
7119 This variable is used in the *Completions* buffers.
7120 Its value is a list of the form (START END) where START is the place
7121 where the completion should be inserted and END (if non-nil) is the end
7122 of the text to replace. If END is nil, point is used instead.")
7124 (defvar completion-list-insert-choice-function #'completion--replace
7125 "Function to use to insert the text chosen in *Completions*.
7126 Called with three arguments (BEG END TEXT), it should replace the text
7127 between BEG and END with TEXT. Expected to be set buffer-locally
7128 in the *Completions* buffer.")
7130 (defvar completion-base-size nil
7131 "Number of chars before point not involved in completion.
7132 This is a local variable in the completion list buffer.
7133 It refers to the chars in the minibuffer if completing in the
7134 minibuffer, or in `completion-reference-buffer' otherwise.
7135 Only characters in the field at point are included.
7137 If nil, Emacs determines which part of the tail end of the
7138 buffer's text is involved in completion by comparing the text
7139 directly.")
7140 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7142 (defun delete-completion-window ()
7143 "Delete the completion list window.
7144 Go to the window from which completion was requested."
7145 (interactive)
7146 (let ((buf completion-reference-buffer))
7147 (if (one-window-p t)
7148 (if (window-dedicated-p) (delete-frame))
7149 (delete-window (selected-window))
7150 (if (get-buffer-window buf)
7151 (select-window (get-buffer-window buf))))))
7153 (defun previous-completion (n)
7154 "Move to the previous item in the completion list."
7155 (interactive "p")
7156 (next-completion (- n)))
7158 (defun next-completion (n)
7159 "Move to the next item in the completion list.
7160 With prefix argument N, move N items (negative N means move backward)."
7161 (interactive "p")
7162 (let ((beg (point-min)) (end (point-max)))
7163 (while (and (> n 0) (not (eobp)))
7164 ;; If in a completion, move to the end of it.
7165 (when (get-text-property (point) 'mouse-face)
7166 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7167 ;; Move to start of next one.
7168 (unless (get-text-property (point) 'mouse-face)
7169 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7170 (setq n (1- n)))
7171 (while (and (< n 0) (not (bobp)))
7172 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7173 ;; If in a completion, move to the start of it.
7174 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7175 (goto-char (previous-single-property-change
7176 (point) 'mouse-face nil beg)))
7177 ;; Move to end of the previous completion.
7178 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7179 (goto-char (previous-single-property-change
7180 (point) 'mouse-face nil beg)))
7181 ;; Move to the start of that one.
7182 (goto-char (previous-single-property-change
7183 (point) 'mouse-face nil beg))
7184 (setq n (1+ n))))))
7186 (defun choose-completion (&optional event)
7187 "Choose the completion at point.
7188 If EVENT, use EVENT's position to determine the starting position."
7189 (interactive (list last-nonmenu-event))
7190 ;; In case this is run via the mouse, give temporary modes such as
7191 ;; isearch a chance to turn off.
7192 (run-hooks 'mouse-leave-buffer-hook)
7193 (with-current-buffer (window-buffer (posn-window (event-start event)))
7194 (let ((buffer completion-reference-buffer)
7195 (base-size completion-base-size)
7196 (base-position completion-base-position)
7197 (insert-function completion-list-insert-choice-function)
7198 (choice
7199 (save-excursion
7200 (goto-char (posn-point (event-start event)))
7201 (let (beg end)
7202 (cond
7203 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7204 (setq end (point) beg (1+ (point))))
7205 ((and (not (bobp))
7206 (get-text-property (1- (point)) 'mouse-face))
7207 (setq end (1- (point)) beg (point)))
7208 (t (error "No completion here")))
7209 (setq beg (previous-single-property-change beg 'mouse-face))
7210 (setq end (or (next-single-property-change end 'mouse-face)
7211 (point-max)))
7212 (buffer-substring-no-properties beg end)))))
7214 (unless (buffer-live-p buffer)
7215 (error "Destination buffer is dead"))
7216 (quit-window nil (posn-window (event-start event)))
7218 (with-current-buffer buffer
7219 (choose-completion-string
7220 choice buffer
7221 (or base-position
7222 (when base-size
7223 ;; Someone's using old completion code that doesn't know
7224 ;; about base-position yet.
7225 (list (+ base-size (field-beginning))))
7226 ;; If all else fails, just guess.
7227 (list (choose-completion-guess-base-position choice)))
7228 insert-function)))))
7230 ;; Delete the longest partial match for STRING
7231 ;; that can be found before POINT.
7232 (defun choose-completion-guess-base-position (string)
7233 (save-excursion
7234 (let ((opoint (point))
7235 len)
7236 ;; Try moving back by the length of the string.
7237 (goto-char (max (- (point) (length string))
7238 (minibuffer-prompt-end)))
7239 ;; See how far back we were actually able to move. That is the
7240 ;; upper bound on how much we can match and delete.
7241 (setq len (- opoint (point)))
7242 (if completion-ignore-case
7243 (setq string (downcase string)))
7244 (while (and (> len 0)
7245 (let ((tail (buffer-substring (point) opoint)))
7246 (if completion-ignore-case
7247 (setq tail (downcase tail)))
7248 (not (string= tail (substring string 0 len)))))
7249 (setq len (1- len))
7250 (forward-char 1))
7251 (point))))
7253 (defun choose-completion-delete-max-match (string)
7254 (declare (obsolete choose-completion-guess-base-position "23.2"))
7255 (delete-region (choose-completion-guess-base-position string) (point)))
7257 (defvar choose-completion-string-functions nil
7258 "Functions that may override the normal insertion of a completion choice.
7259 These functions are called in order with three arguments:
7260 CHOICE - the string to insert in the buffer,
7261 BUFFER - the buffer in which the choice should be inserted,
7262 BASE-POSITION - where to insert the completion.
7264 If a function in the list returns non-nil, that function is supposed
7265 to have inserted the CHOICE in the BUFFER, and possibly exited
7266 the minibuffer; no further functions will be called.
7268 If all functions in the list return nil, that means to use
7269 the default method of inserting the completion in BUFFER.")
7271 (defun choose-completion-string (choice &optional
7272 buffer base-position insert-function)
7273 "Switch to BUFFER and insert the completion choice CHOICE.
7274 BASE-POSITION says where to insert the completion.
7275 INSERT-FUNCTION says how to insert the completion and falls
7276 back on `completion-list-insert-choice-function' when nil."
7278 ;; If BUFFER is the minibuffer, exit the minibuffer
7279 ;; unless it is reading a file name and CHOICE is a directory,
7280 ;; or completion-no-auto-exit is non-nil.
7282 ;; Some older code may call us passing `base-size' instead of
7283 ;; `base-position'. It's difficult to make any use of `base-size',
7284 ;; so we just ignore it.
7285 (unless (consp base-position)
7286 (message "Obsolete `base-size' passed to choose-completion-string")
7287 (setq base-position nil))
7289 (let* ((buffer (or buffer completion-reference-buffer))
7290 (mini-p (minibufferp buffer)))
7291 ;; If BUFFER is a minibuffer, barf unless it's the currently
7292 ;; active minibuffer.
7293 (if (and mini-p
7294 (not (and (active-minibuffer-window)
7295 (equal buffer
7296 (window-buffer (active-minibuffer-window))))))
7297 (error "Minibuffer is not active for completion")
7298 ;; Set buffer so buffer-local choose-completion-string-functions works.
7299 (set-buffer buffer)
7300 (unless (run-hook-with-args-until-success
7301 'choose-completion-string-functions
7302 ;; The fourth arg used to be `mini-p' but was useless
7303 ;; (since minibufferp can be used on the `buffer' arg)
7304 ;; and indeed unused. The last used to be `base-size', so we
7305 ;; keep it to try and avoid breaking old code.
7306 choice buffer base-position nil)
7307 ;; This remove-text-properties should be unnecessary since `choice'
7308 ;; comes from buffer-substring-no-properties.
7309 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7310 ;; Insert the completion into the buffer where it was requested.
7311 (funcall (or insert-function completion-list-insert-choice-function)
7312 (or (car base-position) (point))
7313 (or (cadr base-position) (point))
7314 choice)
7315 ;; Update point in the window that BUFFER is showing in.
7316 (let ((window (get-buffer-window buffer t)))
7317 (set-window-point window (point)))
7318 ;; If completing for the minibuffer, exit it with this choice.
7319 (and (not completion-no-auto-exit)
7320 (minibufferp buffer)
7321 minibuffer-completion-table
7322 ;; If this is reading a file name, and the file name chosen
7323 ;; is a directory, don't exit the minibuffer.
7324 (let* ((result (buffer-substring (field-beginning) (point)))
7325 (bounds
7326 (completion-boundaries result minibuffer-completion-table
7327 minibuffer-completion-predicate
7328 "")))
7329 (if (eq (car bounds) (length result))
7330 ;; The completion chosen leads to a new set of completions
7331 ;; (e.g. it's a directory): don't exit the minibuffer yet.
7332 (let ((mini (active-minibuffer-window)))
7333 (select-window mini)
7334 (when minibuffer-auto-raise
7335 (raise-frame (window-frame mini))))
7336 (exit-minibuffer))))))))
7338 (define-derived-mode completion-list-mode nil "Completion List"
7339 "Major mode for buffers showing lists of possible completions.
7340 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
7341 to select the completion near point.
7342 Or click to select one with the mouse.
7344 \\{completion-list-mode-map}"
7345 (set (make-local-variable 'completion-base-size) nil))
7347 (defun completion-list-mode-finish ()
7348 "Finish setup of the completions buffer.
7349 Called from `temp-buffer-show-hook'."
7350 (when (eq major-mode 'completion-list-mode)
7351 (setq buffer-read-only t)))
7353 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
7356 ;; Variables and faces used in `completion-setup-function'.
7358 (defcustom completion-show-help t
7359 "Non-nil means show help message in *Completions* buffer."
7360 :type 'boolean
7361 :version "22.1"
7362 :group 'completion)
7364 ;; This function goes in completion-setup-hook, so that it is called
7365 ;; after the text of the completion list buffer is written.
7366 (defun completion-setup-function ()
7367 (let* ((mainbuf (current-buffer))
7368 (base-dir
7369 ;; FIXME: This is a bad hack. We try to set the default-directory
7370 ;; in the *Completions* buffer so that the relative file names
7371 ;; displayed there can be treated as valid file names, independently
7372 ;; from the completion context. But this suffers from many problems:
7373 ;; - It's not clear when the completions are file names. With some
7374 ;; completion tables (e.g. bzr revision specs), the listed
7375 ;; completions can mix file names and other things.
7376 ;; - It doesn't pay attention to possible quoting.
7377 ;; - With fancy completion styles, the code below will not always
7378 ;; find the right base directory.
7379 (if minibuffer-completing-file-name
7380 (file-name-as-directory
7381 (expand-file-name
7382 (buffer-substring (minibuffer-prompt-end)
7383 (- (point) (or completion-base-size 0))))))))
7384 (with-current-buffer standard-output
7385 (let ((base-size completion-base-size) ;Read before killing localvars.
7386 (base-position completion-base-position)
7387 (insert-fun completion-list-insert-choice-function))
7388 (completion-list-mode)
7389 (set (make-local-variable 'completion-base-size) base-size)
7390 (set (make-local-variable 'completion-base-position) base-position)
7391 (set (make-local-variable 'completion-list-insert-choice-function)
7392 insert-fun))
7393 (set (make-local-variable 'completion-reference-buffer) mainbuf)
7394 (if base-dir (setq default-directory base-dir))
7395 ;; Maybe insert help string.
7396 (when completion-show-help
7397 (goto-char (point-min))
7398 (if (display-mouse-p)
7399 (insert (substitute-command-keys
7400 "Click on a completion to select it.\n")))
7401 (insert (substitute-command-keys
7402 "In this buffer, type \\[choose-completion] to \
7403 select the completion near point.\n\n"))))))
7405 (add-hook 'completion-setup-hook 'completion-setup-function)
7407 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
7408 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
7410 (defun switch-to-completions ()
7411 "Select the completion list window."
7412 (interactive)
7413 (let ((window (or (get-buffer-window "*Completions*" 0)
7414 ;; Make sure we have a completions window.
7415 (progn (minibuffer-completion-help)
7416 (get-buffer-window "*Completions*" 0)))))
7417 (when window
7418 (select-window window)
7419 ;; In the new buffer, go to the first completion.
7420 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
7421 (when (bobp)
7422 (next-completion 1)))))
7424 ;;; Support keyboard commands to turn on various modifiers.
7426 ;; These functions -- which are not commands -- each add one modifier
7427 ;; to the following event.
7429 (defun event-apply-alt-modifier (_ignore-prompt)
7430 "\\<function-key-map>Add the Alt modifier to the following event.
7431 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
7432 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
7433 (defun event-apply-super-modifier (_ignore-prompt)
7434 "\\<function-key-map>Add the Super modifier to the following event.
7435 For example, type \\[event-apply-super-modifier] & to enter Super-&."
7436 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
7437 (defun event-apply-hyper-modifier (_ignore-prompt)
7438 "\\<function-key-map>Add the Hyper modifier to the following event.
7439 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
7440 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
7441 (defun event-apply-shift-modifier (_ignore-prompt)
7442 "\\<function-key-map>Add the Shift modifier to the following event.
7443 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
7444 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
7445 (defun event-apply-control-modifier (_ignore-prompt)
7446 "\\<function-key-map>Add the Ctrl modifier to the following event.
7447 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
7448 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
7449 (defun event-apply-meta-modifier (_ignore-prompt)
7450 "\\<function-key-map>Add the Meta modifier to the following event.
7451 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
7452 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
7454 (defun event-apply-modifier (event symbol lshiftby prefix)
7455 "Apply a modifier flag to event EVENT.
7456 SYMBOL is the name of this modifier, as a symbol.
7457 LSHIFTBY is the numeric value of this modifier, in keyboard events.
7458 PREFIX is the string that represents this modifier in an event type symbol."
7459 (if (numberp event)
7460 (cond ((eq symbol 'control)
7461 (if (and (<= (downcase event) ?z)
7462 (>= (downcase event) ?a))
7463 (- (downcase event) ?a -1)
7464 (if (and (<= (downcase event) ?Z)
7465 (>= (downcase event) ?A))
7466 (- (downcase event) ?A -1)
7467 (logior (lsh 1 lshiftby) event))))
7468 ((eq symbol 'shift)
7469 (if (and (<= (downcase event) ?z)
7470 (>= (downcase event) ?a))
7471 (upcase event)
7472 (logior (lsh 1 lshiftby) event)))
7474 (logior (lsh 1 lshiftby) event)))
7475 (if (memq symbol (event-modifiers event))
7476 event
7477 (let ((event-type (if (symbolp event) event (car event))))
7478 (setq event-type (intern (concat prefix (symbol-name event-type))))
7479 (if (symbolp event)
7480 event-type
7481 (cons event-type (cdr event)))))))
7483 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
7484 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
7485 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
7486 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
7487 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
7488 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
7490 ;;;; Keypad support.
7492 ;; Make the keypad keys act like ordinary typing keys. If people add
7493 ;; bindings for the function key symbols, then those bindings will
7494 ;; override these, so this shouldn't interfere with any existing
7495 ;; bindings.
7497 ;; Also tell read-char how to handle these keys.
7498 (mapc
7499 (lambda (keypad-normal)
7500 (let ((keypad (nth 0 keypad-normal))
7501 (normal (nth 1 keypad-normal)))
7502 (put keypad 'ascii-character normal)
7503 (define-key function-key-map (vector keypad) (vector normal))))
7504 ;; See also kp-keys bound in bindings.el.
7505 '((kp-space ?\s)
7506 (kp-tab ?\t)
7507 (kp-enter ?\r)
7508 (kp-separator ?,)
7509 (kp-equal ?=)
7510 ;; Do the same for various keys that are represented as symbols under
7511 ;; GUIs but naturally correspond to characters.
7512 (backspace 127)
7513 (delete 127)
7514 (tab ?\t)
7515 (linefeed ?\n)
7516 (clear ?\C-l)
7517 (return ?\C-m)
7518 (escape ?\e)
7521 ;;;;
7522 ;;;; forking a twin copy of a buffer.
7523 ;;;;
7525 (defvar clone-buffer-hook nil
7526 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
7528 (defvar clone-indirect-buffer-hook nil
7529 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
7531 (defun clone-process (process &optional newname)
7532 "Create a twin copy of PROCESS.
7533 If NEWNAME is nil, it defaults to PROCESS' name;
7534 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
7535 If PROCESS is associated with a buffer, the new process will be associated
7536 with the current buffer instead.
7537 Returns nil if PROCESS has already terminated."
7538 (setq newname (or newname (process-name process)))
7539 (if (string-match "<[0-9]+>\\'" newname)
7540 (setq newname (substring newname 0 (match-beginning 0))))
7541 (when (memq (process-status process) '(run stop open))
7542 (let* ((process-connection-type (process-tty-name process))
7543 (new-process
7544 (if (memq (process-status process) '(open))
7545 (let ((args (process-contact process t)))
7546 (setq args (plist-put args :name newname))
7547 (setq args (plist-put args :buffer
7548 (if (process-buffer process)
7549 (current-buffer))))
7550 (apply 'make-network-process args))
7551 (apply 'start-process newname
7552 (if (process-buffer process) (current-buffer))
7553 (process-command process)))))
7554 (set-process-query-on-exit-flag
7555 new-process (process-query-on-exit-flag process))
7556 (set-process-inherit-coding-system-flag
7557 new-process (process-inherit-coding-system-flag process))
7558 (set-process-filter new-process (process-filter process))
7559 (set-process-sentinel new-process (process-sentinel process))
7560 (set-process-plist new-process (copy-sequence (process-plist process)))
7561 new-process)))
7563 ;; things to maybe add (currently partly covered by `funcall mode'):
7564 ;; - syntax-table
7565 ;; - overlays
7566 (defun clone-buffer (&optional newname display-flag)
7567 "Create and return a twin copy of the current buffer.
7568 Unlike an indirect buffer, the new buffer can be edited
7569 independently of the old one (if it is not read-only).
7570 NEWNAME is the name of the new buffer. It may be modified by
7571 adding or incrementing <N> at the end as necessary to create a
7572 unique buffer name. If nil, it defaults to the name of the
7573 current buffer, with the proper suffix. If DISPLAY-FLAG is
7574 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
7575 clone a file-visiting buffer, or a buffer whose major mode symbol
7576 has a non-nil `no-clone' property, results in an error.
7578 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
7579 current buffer with appropriate suffix. However, if a prefix
7580 argument is given, then the command prompts for NEWNAME in the
7581 minibuffer.
7583 This runs the normal hook `clone-buffer-hook' in the new buffer
7584 after it has been set up properly in other respects."
7585 (interactive
7586 (progn
7587 (if buffer-file-name
7588 (error "Cannot clone a file-visiting buffer"))
7589 (if (get major-mode 'no-clone)
7590 (error "Cannot clone a buffer in %s mode" mode-name))
7591 (list (if current-prefix-arg
7592 (read-buffer "Name of new cloned buffer: " (current-buffer)))
7593 t)))
7594 (if buffer-file-name
7595 (error "Cannot clone a file-visiting buffer"))
7596 (if (get major-mode 'no-clone)
7597 (error "Cannot clone a buffer in %s mode" mode-name))
7598 (setq newname (or newname (buffer-name)))
7599 (if (string-match "<[0-9]+>\\'" newname)
7600 (setq newname (substring newname 0 (match-beginning 0))))
7601 (let ((buf (current-buffer))
7602 (ptmin (point-min))
7603 (ptmax (point-max))
7604 (pt (point))
7605 (mk (if mark-active (mark t)))
7606 (modified (buffer-modified-p))
7607 (mode major-mode)
7608 (lvars (buffer-local-variables))
7609 (process (get-buffer-process (current-buffer)))
7610 (new (generate-new-buffer (or newname (buffer-name)))))
7611 (save-restriction
7612 (widen)
7613 (with-current-buffer new
7614 (insert-buffer-substring buf)))
7615 (with-current-buffer new
7616 (narrow-to-region ptmin ptmax)
7617 (goto-char pt)
7618 (if mk (set-mark mk))
7619 (set-buffer-modified-p modified)
7621 ;; Clone the old buffer's process, if any.
7622 (when process (clone-process process))
7624 ;; Now set up the major mode.
7625 (funcall mode)
7627 ;; Set up other local variables.
7628 (mapc (lambda (v)
7629 (condition-case () ;in case var is read-only
7630 (if (symbolp v)
7631 (makunbound v)
7632 (set (make-local-variable (car v)) (cdr v)))
7633 (error nil)))
7634 lvars)
7636 ;; Run any hooks (typically set up by the major mode
7637 ;; for cloning to work properly).
7638 (run-hooks 'clone-buffer-hook))
7639 (if display-flag
7640 ;; Presumably the current buffer is shown in the selected frame, so
7641 ;; we want to display the clone elsewhere.
7642 (let ((same-window-regexps nil)
7643 (same-window-buffer-names))
7644 (pop-to-buffer new)))
7645 new))
7648 (defun clone-indirect-buffer (newname display-flag &optional norecord)
7649 "Create an indirect buffer that is a twin copy of the current buffer.
7651 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
7652 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
7653 or if not called with a prefix arg, NEWNAME defaults to the current
7654 buffer's name. The name is modified by adding a `<N>' suffix to it
7655 or by incrementing the N in an existing suffix. Trying to clone a
7656 buffer whose major mode symbol has a non-nil `no-clone-indirect'
7657 property results in an error.
7659 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7660 This is always done when called interactively.
7662 Optional third arg NORECORD non-nil means do not put this buffer at the
7663 front of the list of recently selected ones.
7665 Returns the newly created indirect buffer."
7666 (interactive
7667 (progn
7668 (if (get major-mode 'no-clone-indirect)
7669 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7670 (list (if current-prefix-arg
7671 (read-buffer "Name of indirect buffer: " (current-buffer)))
7672 t)))
7673 (if (get major-mode 'no-clone-indirect)
7674 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7675 (setq newname (or newname (buffer-name)))
7676 (if (string-match "<[0-9]+>\\'" newname)
7677 (setq newname (substring newname 0 (match-beginning 0))))
7678 (let* ((name (generate-new-buffer-name newname))
7679 (buffer (make-indirect-buffer (current-buffer) name t)))
7680 (with-current-buffer buffer
7681 (run-hooks 'clone-indirect-buffer-hook))
7682 (when display-flag
7683 (pop-to-buffer buffer norecord))
7684 buffer))
7687 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
7688 "Like `clone-indirect-buffer' but display in another window."
7689 (interactive
7690 (progn
7691 (if (get major-mode 'no-clone-indirect)
7692 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7693 (list (if current-prefix-arg
7694 (read-buffer "Name of indirect buffer: " (current-buffer)))
7695 t)))
7696 (let ((pop-up-windows t))
7697 (clone-indirect-buffer newname display-flag norecord)))
7700 ;;; Handling of Backspace and Delete keys.
7702 (defcustom normal-erase-is-backspace 'maybe
7703 "Set the default behavior of the Delete and Backspace keys.
7705 If set to t, Delete key deletes forward and Backspace key deletes
7706 backward.
7708 If set to nil, both Delete and Backspace keys delete backward.
7710 If set to 'maybe (which is the default), Emacs automatically
7711 selects a behavior. On window systems, the behavior depends on
7712 the keyboard used. If the keyboard has both a Backspace key and
7713 a Delete key, and both are mapped to their usual meanings, the
7714 option's default value is set to t, so that Backspace can be used
7715 to delete backward, and Delete can be used to delete forward.
7717 If not running under a window system, customizing this option
7718 accomplishes a similar effect by mapping C-h, which is usually
7719 generated by the Backspace key, to DEL, and by mapping DEL to C-d
7720 via `keyboard-translate'. The former functionality of C-h is
7721 available on the F1 key. You should probably not use this
7722 setting if you don't have both Backspace, Delete and F1 keys.
7724 Setting this variable with setq doesn't take effect. Programmatically,
7725 call `normal-erase-is-backspace-mode' (which see) instead."
7726 :type '(choice (const :tag "Off" nil)
7727 (const :tag "Maybe" maybe)
7728 (other :tag "On" t))
7729 :group 'editing-basics
7730 :version "21.1"
7731 :set (lambda (symbol value)
7732 ;; The fboundp is because of a problem with :set when
7733 ;; dumping Emacs. It doesn't really matter.
7734 (if (fboundp 'normal-erase-is-backspace-mode)
7735 (normal-erase-is-backspace-mode (or value 0))
7736 (set-default symbol value))))
7738 (defun normal-erase-is-backspace-setup-frame (&optional frame)
7739 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
7740 (unless frame (setq frame (selected-frame)))
7741 (with-selected-frame frame
7742 (unless (terminal-parameter nil 'normal-erase-is-backspace)
7743 (normal-erase-is-backspace-mode
7744 (if (if (eq normal-erase-is-backspace 'maybe)
7745 (and (not noninteractive)
7746 (or (memq system-type '(ms-dos windows-nt))
7747 (memq window-system '(w32 ns))
7748 (and (memq window-system '(x))
7749 (fboundp 'x-backspace-delete-keys-p)
7750 (x-backspace-delete-keys-p))
7751 ;; If the terminal Emacs is running on has erase char
7752 ;; set to ^H, use the Backspace key for deleting
7753 ;; backward, and the Delete key for deleting forward.
7754 (and (null window-system)
7755 (eq tty-erase-char ?\^H))))
7756 normal-erase-is-backspace)
7757 1 0)))))
7759 (define-minor-mode normal-erase-is-backspace-mode
7760 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
7761 With a prefix argument ARG, enable this feature if ARG is
7762 positive, and disable it otherwise. If called from Lisp, enable
7763 the mode if ARG is omitted or nil.
7765 On window systems, when this mode is on, Delete is mapped to C-d
7766 and Backspace is mapped to DEL; when this mode is off, both
7767 Delete and Backspace are mapped to DEL. (The remapping goes via
7768 `local-function-key-map', so binding Delete or Backspace in the
7769 global or local keymap will override that.)
7771 In addition, on window systems, the bindings of C-Delete, M-Delete,
7772 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
7773 the global keymap in accordance with the functionality of Delete and
7774 Backspace. For example, if Delete is remapped to C-d, which deletes
7775 forward, C-Delete is bound to `kill-word', but if Delete is remapped
7776 to DEL, which deletes backward, C-Delete is bound to
7777 `backward-kill-word'.
7779 If not running on a window system, a similar effect is accomplished by
7780 remapping C-h (normally produced by the Backspace key) and DEL via
7781 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
7782 to C-d; if it's off, the keys are not remapped.
7784 When not running on a window system, and this mode is turned on, the
7785 former functionality of C-h is available on the F1 key. You should
7786 probably not turn on this mode on a text-only terminal if you don't
7787 have both Backspace, Delete and F1 keys.
7789 See also `normal-erase-is-backspace'."
7790 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
7791 . (lambda (v)
7792 (setf (terminal-parameter nil 'normal-erase-is-backspace)
7793 (if v 1 0))))
7794 (let ((enabled (eq 1 (terminal-parameter
7795 nil 'normal-erase-is-backspace))))
7797 (cond ((or (memq window-system '(x w32 ns pc))
7798 (memq system-type '(ms-dos windows-nt)))
7799 (let ((bindings
7800 `(([M-delete] [M-backspace])
7801 ([C-M-delete] [C-M-backspace])
7802 ([?\e C-delete] [?\e C-backspace]))))
7804 (if enabled
7805 (progn
7806 (define-key local-function-key-map [delete] [deletechar])
7807 (define-key local-function-key-map [kp-delete] [deletechar])
7808 (define-key local-function-key-map [backspace] [?\C-?])
7809 (dolist (b bindings)
7810 ;; Not sure if input-decode-map is really right, but
7811 ;; keyboard-translate-table (used below) only works
7812 ;; for integer events, and key-translation-table is
7813 ;; global (like the global-map, used earlier).
7814 (define-key input-decode-map (car b) nil)
7815 (define-key input-decode-map (cadr b) nil)))
7816 (define-key local-function-key-map [delete] [?\C-?])
7817 (define-key local-function-key-map [kp-delete] [?\C-?])
7818 (define-key local-function-key-map [backspace] [?\C-?])
7819 (dolist (b bindings)
7820 (define-key input-decode-map (car b) (cadr b))
7821 (define-key input-decode-map (cadr b) (car b))))))
7823 (if enabled
7824 (progn
7825 (keyboard-translate ?\C-h ?\C-?)
7826 (keyboard-translate ?\C-? ?\C-d))
7827 (keyboard-translate ?\C-h ?\C-h)
7828 (keyboard-translate ?\C-? ?\C-?))))
7830 (if (called-interactively-p 'interactive)
7831 (message "Delete key deletes %s"
7832 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
7833 "forward" "backward")))))
7835 (defvar vis-mode-saved-buffer-invisibility-spec nil
7836 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
7838 (define-minor-mode read-only-mode
7839 "Change whether the current buffer is read-only.
7840 With prefix argument ARG, make the buffer read-only if ARG is
7841 positive, otherwise make it writable. If buffer is read-only
7842 and `view-read-only' is non-nil, enter view mode.
7844 Do not call this from a Lisp program unless you really intend to
7845 do the same thing as the \\[read-only-mode] command, including
7846 possibly enabling or disabling View mode. Also, note that this
7847 command works by setting the variable `buffer-read-only', which
7848 does not affect read-only regions caused by text properties. To
7849 ignore read-only status in a Lisp program (whether due to text
7850 properties or buffer state), bind `inhibit-read-only' temporarily
7851 to a non-nil value."
7852 :variable buffer-read-only
7853 (cond
7854 ((and (not buffer-read-only) view-mode)
7855 (View-exit-and-edit)
7856 (make-local-variable 'view-read-only)
7857 (setq view-read-only t)) ; Must leave view mode.
7858 ((and buffer-read-only view-read-only
7859 ;; If view-mode is already active, `view-mode-enter' is a nop.
7860 (not view-mode)
7861 (not (eq (get major-mode 'mode-class) 'special)))
7862 (view-mode-enter))))
7864 (define-minor-mode visible-mode
7865 "Toggle making all invisible text temporarily visible (Visible mode).
7866 With a prefix argument ARG, enable Visible mode if ARG is
7867 positive, and disable it otherwise. If called from Lisp, enable
7868 the mode if ARG is omitted or nil.
7870 This mode works by saving the value of `buffer-invisibility-spec'
7871 and setting it to nil."
7872 :lighter " Vis"
7873 :group 'editing-basics
7874 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
7875 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
7876 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
7877 (when visible-mode
7878 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
7879 buffer-invisibility-spec)
7880 (setq buffer-invisibility-spec nil)))
7882 (defvar messages-buffer-mode-map
7883 (let ((map (make-sparse-keymap)))
7884 (set-keymap-parent map special-mode-map)
7885 (define-key map "g" nil) ; nothing to revert
7886 map))
7888 (define-derived-mode messages-buffer-mode special-mode "Messages"
7889 "Major mode used in the \"*Messages*\" buffer.")
7891 (defun messages-buffer ()
7892 "Return the \"*Messages*\" buffer.
7893 If it does not exist, create and it switch it to `messages-buffer-mode'."
7894 (or (get-buffer "*Messages*")
7895 (with-current-buffer (get-buffer-create "*Messages*")
7896 (messages-buffer-mode)
7897 (current-buffer))))
7900 ;; Minibuffer prompt stuff.
7902 ;;(defun minibuffer-prompt-modification (start end)
7903 ;; (error "You cannot modify the prompt"))
7906 ;;(defun minibuffer-prompt-insertion (start end)
7907 ;; (let ((inhibit-modification-hooks t))
7908 ;; (delete-region start end)
7909 ;; ;; Discard undo information for the text insertion itself
7910 ;; ;; and for the text deletion.above.
7911 ;; (when (consp buffer-undo-list)
7912 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
7913 ;; (message "You cannot modify the prompt")))
7916 ;;(setq minibuffer-prompt-properties
7917 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
7918 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
7921 ;;;; Problematic external packages.
7923 ;; rms says this should be done by specifying symbols that define
7924 ;; versions together with bad values. This is therefore not as
7925 ;; flexible as it could be. See the thread:
7926 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
7927 (defconst bad-packages-alist
7928 ;; Not sure exactly which semantic versions have problems.
7929 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
7930 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
7931 "The version of `semantic' loaded does not work in Emacs 22.
7932 It can cause constant high CPU load.
7933 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
7934 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
7935 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
7936 ;; provided the `CUA-mode' feature. Since this is no longer true,
7937 ;; we can warn the user if the `CUA-mode' feature is ever provided.
7938 (CUA-mode t nil
7939 "CUA-mode is now part of the standard GNU Emacs distribution,
7940 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
7942 You have loaded an older version of CUA-mode which does not work
7943 correctly with this version of Emacs. You should remove the old
7944 version and use the one distributed with Emacs."))
7945 "Alist of packages known to cause problems in this version of Emacs.
7946 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
7947 PACKAGE is either a regular expression to match file names, or a
7948 symbol (a feature name), like for `with-eval-after-load'.
7949 SYMBOL is either the name of a string variable, or `t'. Upon
7950 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
7951 warning using STRING as the message.")
7953 (defun bad-package-check (package)
7954 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
7955 (condition-case nil
7956 (let* ((list (assoc package bad-packages-alist))
7957 (symbol (nth 1 list)))
7958 (and list
7959 (boundp symbol)
7960 (or (eq symbol t)
7961 (and (stringp (setq symbol (eval symbol)))
7962 (string-match-p (nth 2 list) symbol)))
7963 (display-warning package (nth 3 list) :warning)))
7964 (error nil)))
7966 (dolist (elem bad-packages-alist)
7967 (let ((pkg (car elem)))
7968 (with-eval-after-load pkg
7969 (bad-package-check pkg))))
7972 ;;; Generic dispatcher commands
7974 ;; Macro `define-alternatives' is used to create generic commands.
7975 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
7976 ;; that can have different alternative implementations where choosing
7977 ;; among them is exclusively a matter of user preference.
7979 ;; (define-alternatives COMMAND) creates a new interactive command
7980 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
7981 ;; Typically, the user will not need to customize this variable; packages
7982 ;; wanting to add alternative implementations should use
7984 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
7986 (defmacro define-alternatives (command &rest customizations)
7987 "Define the new command `COMMAND'.
7989 The argument `COMMAND' should be a symbol.
7991 Running `M-x COMMAND RET' for the first time prompts for which
7992 alternative to use and records the selected command as a custom
7993 variable.
7995 Running `C-u M-x COMMAND RET' prompts again for an alternative
7996 and overwrites the previous choice.
7998 The variable `COMMAND-alternatives' contains an alist with
7999 alternative implementations of COMMAND. `define-alternatives'
8000 does not have any effect until this variable is set.
8002 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8003 `defcustom' keywords and values to add to the declaration of
8004 `COMMAND-alternatives' (typically :group and :version)."
8005 (let* ((command-name (symbol-name command))
8006 (varalt-name (concat command-name "-alternatives"))
8007 (varalt-sym (intern varalt-name))
8008 (varimp-sym (intern (concat command-name "--implementation"))))
8009 `(progn
8011 (defcustom ,varalt-sym nil
8012 ,(format "Alist of alternative implementations for the `%s' command.
8014 Each entry must be a pair (ALTNAME . ALTFUN), where:
8015 ALTNAME - The name shown at user to describe the alternative implementation.
8016 ALTFUN - The function called to implement this alternative."
8017 command-name)
8018 :type '(alist :key-type string :value-type function)
8019 ,@customizations)
8021 (put ',varalt-sym 'definition-name ',command)
8022 (defvar ,varimp-sym nil "Internal use only.")
8024 (defun ,command (&optional arg)
8025 ,(format "Run generic command `%s'.
8026 If used for the first time, or with interactive ARG, ask the user which
8027 implementation to use for `%s'. The variable `%s'
8028 contains the list of implementations currently supported for this command."
8029 command-name command-name varalt-name)
8030 (interactive "P")
8031 (when (or arg (null ,varimp-sym))
8032 (let ((val (completing-read
8033 ,(format "Select implementation for command `%s': "
8034 command-name)
8035 ,varalt-sym nil t)))
8036 (unless (string-equal val "")
8037 (when (null ,varimp-sym)
8038 (message
8039 "Use `C-u M-x %s RET' to select another implementation"
8040 ,command-name)
8041 (sit-for 3))
8042 (customize-save-variable ',varimp-sym
8043 (cdr (assoc-string val ,varalt-sym))))))
8044 (if ,varimp-sym
8045 (call-interactively ,varimp-sym)
8046 (message ,(format "No implementation selected for command `%s'"
8047 command-name)))))))
8051 (provide 'simple)
8053 ;;; simple.el ends here