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