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