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