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