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