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