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