]> code.delx.au - gnu-emacs/blob - lisp/simple.el
Merge from origin/emacs-25
[gnu-emacs] / lisp / simple.el
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 1985-1987, 1993-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 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 If COMMAND ends in `&', execute it asynchronously.
3199 The output appears in the buffer `*Async Shell Command*'.
3200 That buffer is in shell mode. You can also use
3201 `async-shell-command' that automatically adds `&'.
3202
3203 Otherwise, COMMAND is executed synchronously. The output appears in
3204 the buffer `*Shell Command Output*'. If the output is short enough to
3205 display in the echo area (which is determined by the variables
3206 `resize-mini-windows' and `max-mini-window-height'), it is shown
3207 there, but it is nonetheless available in buffer `*Shell Command
3208 Output*' even though that buffer is not automatically displayed.
3209
3210 To specify a coding system for converting non-ASCII characters
3211 in the shell command output, use \\[universal-coding-system-argument] \
3212 before this command.
3213
3214 Noninteractive callers can specify coding systems by binding
3215 `coding-system-for-read' and `coding-system-for-write'.
3216
3217 The optional second argument OUTPUT-BUFFER, if non-nil,
3218 says to put the output in some other buffer.
3219 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
3220 If OUTPUT-BUFFER is not a buffer and not nil,
3221 insert output in current buffer. (This cannot be done asynchronously.)
3222 In either case, the buffer is first erased, and the output is
3223 inserted after point (leaving mark after it).
3224
3225 If the command terminates without error, but generates output,
3226 and you did not specify \"insert it in the current buffer\",
3227 the output can be displayed in the echo area or in its buffer.
3228 If the output is short enough to display in the echo area
3229 \(determined by the variable `max-mini-window-height' if
3230 `resize-mini-windows' is non-nil), it is shown there.
3231 Otherwise,the buffer containing the output is displayed.
3232
3233 If there is output and an error, and you did not specify \"insert it
3234 in the current buffer\", a message about the error goes at the end
3235 of the output.
3236
3237 If there is no output, or if output is inserted in the current buffer,
3238 then `*Shell Command Output*' is deleted.
3239
3240 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
3241 or buffer name to which to direct the command's standard error output.
3242 If it is nil, error output is mingled with regular output.
3243 In an interactive call, the variable `shell-command-default-error-buffer'
3244 specifies the value of ERROR-BUFFER.
3245
3246 In Elisp, you will often be better served by calling `call-process' or
3247 `start-process' directly, since it offers more control and does not impose
3248 the use of a shell (with its need to quote arguments)."
3249
3250 (interactive
3251 (list
3252 (read-shell-command "Shell command: " nil nil
3253 (let ((filename
3254 (cond
3255 (buffer-file-name)
3256 ((eq major-mode 'dired-mode)
3257 (dired-get-filename nil t)))))
3258 (and filename (file-relative-name filename))))
3259 current-prefix-arg
3260 shell-command-default-error-buffer))
3261 ;; Look for a handler in case default-directory is a remote file name.
3262 (let ((handler
3263 (find-file-name-handler (directory-file-name default-directory)
3264 'shell-command)))
3265 (if handler
3266 (funcall handler 'shell-command command output-buffer error-buffer)
3267 (if (and output-buffer
3268 (not (or (bufferp output-buffer) (stringp output-buffer))))
3269 ;; Output goes in current buffer.
3270 (let ((error-file
3271 (if error-buffer
3272 (make-temp-file
3273 (expand-file-name "scor"
3274 (or small-temporary-file-directory
3275 temporary-file-directory)))
3276 nil)))
3277 (barf-if-buffer-read-only)
3278 (push-mark nil t)
3279 ;; We do not use -f for csh; we will not support broken use of
3280 ;; .cshrcs. Even the BSD csh manual says to use
3281 ;; "if ($?prompt) exit" before things which are not useful
3282 ;; non-interactively. Besides, if someone wants their other
3283 ;; aliases for shell commands then they can still have them.
3284 (call-process shell-file-name nil
3285 (if error-file
3286 (list t error-file)
3287 t)
3288 nil shell-command-switch command)
3289 (when (and error-file (file-exists-p error-file))
3290 (if (< 0 (nth 7 (file-attributes error-file)))
3291 (with-current-buffer (get-buffer-create error-buffer)
3292 (let ((pos-from-end (- (point-max) (point))))
3293 (or (bobp)
3294 (insert "\f\n"))
3295 ;; Do no formatting while reading error file,
3296 ;; because that can run a shell command, and we
3297 ;; don't want that to cause an infinite recursion.
3298 (format-insert-file error-file nil)
3299 ;; Put point after the inserted errors.
3300 (goto-char (- (point-max) pos-from-end)))
3301 (display-buffer (current-buffer))))
3302 (delete-file error-file))
3303 ;; This is like exchange-point-and-mark, but doesn't
3304 ;; activate the mark. It is cleaner to avoid activation,
3305 ;; even though the command loop would deactivate the mark
3306 ;; because we inserted text.
3307 (goto-char (prog1 (mark t)
3308 (set-marker (mark-marker) (point)
3309 (current-buffer)))))
3310 ;; Output goes in a separate buffer.
3311 ;; Preserve the match data in case called from a program.
3312 (save-match-data
3313 (if (string-match "[ \t]*&[ \t]*\\'" command)
3314 ;; Command ending with ampersand means asynchronous.
3315 (let ((buffer (get-buffer-create
3316 (or output-buffer "*Async Shell Command*")))
3317 (directory default-directory)
3318 proc)
3319 ;; Remove the ampersand.
3320 (setq command (substring command 0 (match-beginning 0)))
3321 ;; Ask the user what to do with already running process.
3322 (setq proc (get-buffer-process buffer))
3323 (when proc
3324 (cond
3325 ((eq async-shell-command-buffer 'confirm-kill-process)
3326 ;; If will kill a process, query first.
3327 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
3328 (kill-process proc)
3329 (error "Shell command in progress")))
3330 ((eq async-shell-command-buffer 'confirm-new-buffer)
3331 ;; If will create a new buffer, query first.
3332 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
3333 (setq buffer (generate-new-buffer
3334 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3335 output-buffer "*Async Shell Command*")))
3336 (error "Shell command in progress")))
3337 ((eq async-shell-command-buffer 'new-buffer)
3338 ;; It will create a new buffer.
3339 (setq buffer (generate-new-buffer
3340 (or (and (bufferp output-buffer) (buffer-name output-buffer))
3341 output-buffer "*Async Shell Command*"))))
3342 ((eq async-shell-command-buffer 'confirm-rename-buffer)
3343 ;; If will rename the buffer, query first.
3344 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
3345 (progn
3346 (with-current-buffer buffer
3347 (rename-uniquely))
3348 (setq buffer (get-buffer-create
3349 (or output-buffer "*Async Shell Command*"))))
3350 (error "Shell command in progress")))
3351 ((eq async-shell-command-buffer 'rename-buffer)
3352 ;; It will rename the buffer.
3353 (with-current-buffer buffer
3354 (rename-uniquely))
3355 (setq buffer (get-buffer-create
3356 (or output-buffer "*Async Shell Command*"))))))
3357 (with-current-buffer buffer
3358 (setq buffer-read-only nil)
3359 ;; Setting buffer-read-only to nil doesn't suffice
3360 ;; if some text has a non-nil read-only property,
3361 ;; which comint sometimes adds for prompts.
3362 (let ((inhibit-read-only t))
3363 (erase-buffer))
3364 (display-buffer buffer '(nil (allow-no-window . t)))
3365 (setq default-directory directory)
3366 (setq proc (start-process "Shell" buffer shell-file-name
3367 shell-command-switch command))
3368 (setq mode-line-process '(":%s"))
3369 (require 'shell) (shell-mode)
3370 (set-process-sentinel proc 'shell-command-sentinel)
3371 ;; Use the comint filter for proper handling of carriage motion
3372 ;; (see `comint-inhibit-carriage-motion'),.
3373 (set-process-filter proc 'comint-output-filter)
3374 ))
3375 ;; Otherwise, command is executed synchronously.
3376 (shell-command-on-region (point) (point) command
3377 output-buffer nil error-buffer)))))))
3378
3379 (defun display-message-or-buffer (message &optional buffer-name action frame)
3380 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
3381 MESSAGE may be either a string or a buffer.
3382
3383 A pop-up buffer is displayed using `display-buffer' if MESSAGE is too long
3384 for maximum height of the echo area, as defined by `max-mini-window-height'
3385 if `resize-mini-windows' is non-nil.
3386
3387 Returns either the string shown in the echo area, or when a pop-up
3388 buffer is used, the window used to display it.
3389
3390 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
3391 name of the buffer used to display it in the case where a pop-up buffer
3392 is used, defaulting to `*Message*'. In the case where MESSAGE is a
3393 string and it is displayed in the echo area, it is not specified whether
3394 the contents are inserted into the buffer anyway.
3395
3396 Optional arguments ACTION and FRAME are as for `display-buffer',
3397 and are only used if a pop-up buffer is displayed."
3398 (cond ((and (stringp message) (not (string-match "\n" message)))
3399 ;; Trivial case where we can use the echo area
3400 (message "%s" message))
3401 ((and (stringp message)
3402 (= (string-match "\n" message) (1- (length message))))
3403 ;; Trivial case where we can just remove single trailing newline
3404 (message "%s" (substring message 0 (1- (length message)))))
3405 (t
3406 ;; General case
3407 (with-current-buffer
3408 (if (bufferp message)
3409 message
3410 (get-buffer-create (or buffer-name "*Message*")))
3411
3412 (unless (bufferp message)
3413 (erase-buffer)
3414 (insert message))
3415
3416 (let ((lines
3417 (if (= (buffer-size) 0)
3418 0
3419 (count-screen-lines nil nil nil (minibuffer-window)))))
3420 (cond ((= lines 0))
3421 ((and (or (<= lines 1)
3422 (<= lines
3423 (if resize-mini-windows
3424 (cond ((floatp max-mini-window-height)
3425 (* (frame-height)
3426 max-mini-window-height))
3427 ((integerp max-mini-window-height)
3428 max-mini-window-height)
3429 (t
3430 1))
3431 1)))
3432 ;; Don't use the echo area if the output buffer is
3433 ;; already displayed in the selected frame.
3434 (not (get-buffer-window (current-buffer))))
3435 ;; Echo area
3436 (goto-char (point-max))
3437 (when (bolp)
3438 (backward-char 1))
3439 (message "%s" (buffer-substring (point-min) (point))))
3440 (t
3441 ;; Buffer
3442 (goto-char (point-min))
3443 (display-buffer (current-buffer) action frame))))))))
3444
3445
3446 ;; We have a sentinel to prevent insertion of a termination message
3447 ;; in the buffer itself.
3448 (defun shell-command-sentinel (process signal)
3449 (if (memq (process-status process) '(exit signal))
3450 (message "%s: %s."
3451 (car (cdr (cdr (process-command process))))
3452 (substring signal 0 -1))))
3453
3454 (defun shell-command-on-region (start end command
3455 &optional output-buffer replace
3456 error-buffer display-error-buffer
3457 region-noncontiguous-p)
3458 "Execute string COMMAND in inferior shell with region as input.
3459 Normally display output (if any) in temp buffer `*Shell Command Output*';
3460 Prefix arg means replace the region with it. Return the exit code of
3461 COMMAND.
3462
3463 To specify a coding system for converting non-ASCII characters
3464 in the input and output to the shell command, use \\[universal-coding-system-argument]
3465 before this command. By default, the input (from the current buffer)
3466 is encoded using coding-system specified by `process-coding-system-alist',
3467 falling back to `default-process-coding-system' if no match for COMMAND
3468 is found in `process-coding-system-alist'.
3469
3470 Noninteractive callers can specify coding systems by binding
3471 `coding-system-for-read' and `coding-system-for-write'.
3472
3473 If the command generates output, the output may be displayed
3474 in the echo area or in a buffer.
3475 If the output is short enough to display in the echo area
3476 \(determined by the variable `max-mini-window-height' if
3477 `resize-mini-windows' is non-nil), it is shown there.
3478 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3479 The output is available in that buffer in both cases.
3480
3481 If there is output and an error, a message about the error
3482 appears at the end of the output. If there is no output, or if
3483 output is inserted in the current buffer, the buffer `*Shell
3484 Command Output*' is deleted.
3485
3486 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3487 command's output. If the value is a buffer or buffer name,
3488 put the output there. If the value is nil, use the buffer
3489 `*Shell Command Output*'. Any other value, excluding nil,
3490 means to insert the output in the current buffer. In either case,
3491 the output is inserted after point (leaving mark after it).
3492
3493 Optional fifth arg REPLACE, if non-nil, means to insert the
3494 output in place of text from START to END, putting point and mark
3495 around it.
3496
3497 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3498 or buffer name to which to direct the command's standard error
3499 output. If nil, error output is mingled with regular output.
3500 When called interactively, `shell-command-default-error-buffer'
3501 is used for ERROR-BUFFER.
3502
3503 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3504 display the error buffer if there were any errors. When called
3505 interactively, this is t."
3506 (interactive (let (string)
3507 (unless (mark)
3508 (user-error "The mark is not set now, so there is no region"))
3509 ;; Do this before calling region-beginning
3510 ;; and region-end, in case subprocess output
3511 ;; relocates them while we are in the minibuffer.
3512 (setq string (read-shell-command "Shell command on region: "))
3513 ;; call-interactively recognizes region-beginning and
3514 ;; region-end specially, leaving them in the history.
3515 (list (region-beginning) (region-end)
3516 string
3517 current-prefix-arg
3518 current-prefix-arg
3519 shell-command-default-error-buffer
3520 t
3521 (region-noncontiguous-p))))
3522 (let ((error-file
3523 (if error-buffer
3524 (make-temp-file
3525 (expand-file-name "scor"
3526 (or small-temporary-file-directory
3527 temporary-file-directory)))
3528 nil))
3529 exit-status)
3530 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
3531 (if region-noncontiguous-p
3532 (let ((input (concat (funcall region-extract-function 'delete) "\n"))
3533 output)
3534 (with-temp-buffer
3535 (insert input)
3536 (call-process-region (point-min) (point-max)
3537 shell-file-name t t
3538 nil shell-command-switch
3539 command)
3540 (setq output (split-string (buffer-string) "\n")))
3541 (goto-char start)
3542 (funcall region-insert-function output))
3543 (if (or replace
3544 (and output-buffer
3545 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3546 ;; Replace specified region with output from command.
3547 (let ((swap (and replace (< start end))))
3548 ;; Don't muck with mark unless REPLACE says we should.
3549 (goto-char start)
3550 (and replace (push-mark (point) 'nomsg))
3551 (setq exit-status
3552 (call-process-region start end shell-file-name replace
3553 (if error-file
3554 (list t error-file)
3555 t)
3556 nil shell-command-switch command))
3557 ;; It is rude to delete a buffer which the command is not using.
3558 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3559 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3560 ;; (kill-buffer shell-buffer)))
3561 ;; Don't muck with mark unless REPLACE says we should.
3562 (and replace swap (exchange-point-and-mark)))
3563 ;; No prefix argument: put the output in a temp buffer,
3564 ;; replacing its entire contents.
3565 (let ((buffer (get-buffer-create
3566 (or output-buffer "*Shell Command Output*"))))
3567 (unwind-protect
3568 (if (eq buffer (current-buffer))
3569 ;; If the input is the same buffer as the output,
3570 ;; delete everything but the specified region,
3571 ;; then replace that region with the output.
3572 (progn (setq buffer-read-only nil)
3573 (delete-region (max start end) (point-max))
3574 (delete-region (point-min) (min start end))
3575 (setq exit-status
3576 (call-process-region (point-min) (point-max)
3577 shell-file-name t
3578 (if error-file
3579 (list t error-file)
3580 t)
3581 nil shell-command-switch
3582 command)))
3583 ;; Clear the output buffer, then run the command with
3584 ;; output there.
3585 (let ((directory default-directory))
3586 (with-current-buffer buffer
3587 (setq buffer-read-only nil)
3588 (if (not output-buffer)
3589 (setq default-directory directory))
3590 (erase-buffer)))
3591 (setq exit-status
3592 (call-process-region start end shell-file-name nil
3593 (if error-file
3594 (list buffer error-file)
3595 buffer)
3596 nil shell-command-switch command)))
3597 ;; Report the output.
3598 (with-current-buffer buffer
3599 (setq mode-line-process
3600 (cond ((null exit-status)
3601 " - Error")
3602 ((stringp exit-status)
3603 (format " - Signal [%s]" exit-status))
3604 ((not (equal 0 exit-status))
3605 (format " - Exit [%d]" exit-status)))))
3606 (if (with-current-buffer buffer (> (point-max) (point-min)))
3607 ;; There's some output, display it
3608 (display-message-or-buffer buffer)
3609 ;; No output; error?
3610 (let ((output
3611 (if (and error-file
3612 (< 0 (nth 7 (file-attributes error-file))))
3613 (format "some error output%s"
3614 (if shell-command-default-error-buffer
3615 (format " to the \"%s\" buffer"
3616 shell-command-default-error-buffer)
3617 ""))
3618 "no output")))
3619 (cond ((null exit-status)
3620 (message "(Shell command failed with error)"))
3621 ((equal 0 exit-status)
3622 (message "(Shell command succeeded with %s)"
3623 output))
3624 ((stringp exit-status)
3625 (message "(Shell command killed by signal %s)"
3626 exit-status))
3627 (t
3628 (message "(Shell command failed with code %d and %s)"
3629 exit-status output))))
3630 ;; Don't kill: there might be useful info in the undo-log.
3631 ;; (kill-buffer buffer)
3632 )))))
3633
3634 (when (and error-file (file-exists-p error-file))
3635 (if (< 0 (nth 7 (file-attributes error-file)))
3636 (with-current-buffer (get-buffer-create error-buffer)
3637 (let ((pos-from-end (- (point-max) (point))))
3638 (or (bobp)
3639 (insert "\f\n"))
3640 ;; Do no formatting while reading error file,
3641 ;; because that can run a shell command, and we
3642 ;; don't want that to cause an infinite recursion.
3643 (format-insert-file error-file nil)
3644 ;; Put point after the inserted errors.
3645 (goto-char (- (point-max) pos-from-end)))
3646 (and display-error-buffer
3647 (display-buffer (current-buffer)))))
3648 (delete-file error-file))
3649 exit-status))
3650
3651 (defun shell-command-to-string (command)
3652 "Execute shell command COMMAND and return its output as a string."
3653 (with-output-to-string
3654 (with-current-buffer
3655 standard-output
3656 (process-file shell-file-name nil t nil shell-command-switch command))))
3657
3658 (defun process-file (program &optional infile buffer display &rest args)
3659 "Process files synchronously in a separate process.
3660 Similar to `call-process', but may invoke a file handler based on
3661 `default-directory'. The current working directory of the
3662 subprocess is `default-directory'.
3663
3664 File names in INFILE and BUFFER are handled normally, but file
3665 names in ARGS should be relative to `default-directory', as they
3666 are passed to the process verbatim. (This is a difference to
3667 `call-process' which does not support file handlers for INFILE
3668 and BUFFER.)
3669
3670 Some file handlers might not support all variants, for example
3671 they might behave as if DISPLAY was nil, regardless of the actual
3672 value passed."
3673 (let ((fh (find-file-name-handler default-directory 'process-file))
3674 lc stderr-file)
3675 (unwind-protect
3676 (if fh (apply fh 'process-file program infile buffer display args)
3677 (when infile (setq lc (file-local-copy infile)))
3678 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3679 (make-temp-file "emacs")))
3680 (prog1
3681 (apply 'call-process program
3682 (or lc infile)
3683 (if stderr-file (list (car buffer) stderr-file) buffer)
3684 display args)
3685 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3686 (when stderr-file (delete-file stderr-file))
3687 (when lc (delete-file lc)))))
3688
3689 (defvar process-file-side-effects t
3690 "Whether a call of `process-file' changes remote files.
3691
3692 By default, this variable is always set to t, meaning that a
3693 call of `process-file' could potentially change any file on a
3694 remote host. When set to nil, a file handler could optimize
3695 its behavior with respect to remote file attribute caching.
3696
3697 You should only ever change this variable with a let-binding;
3698 never with `setq'.")
3699
3700 (defun start-file-process (name buffer program &rest program-args)
3701 "Start a program in a subprocess. Return the process object for it.
3702
3703 Similar to `start-process', but may invoke a file handler based on
3704 `default-directory'. See Info node `(elisp)Magic File Names'.
3705
3706 This handler ought to run PROGRAM, perhaps on the local host,
3707 perhaps on a remote host that corresponds to `default-directory'.
3708 In the latter case, the local part of `default-directory' becomes
3709 the working directory of the process.
3710
3711 PROGRAM and PROGRAM-ARGS might be file names. They are not
3712 objects of file handler invocation. File handlers might not
3713 support pty association, if PROGRAM is nil."
3714 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3715 (if fh (apply fh 'start-file-process name buffer program program-args)
3716 (apply 'start-process name buffer program program-args))))
3717 \f
3718 ;;;; Process menu
3719
3720 (defvar tabulated-list-format)
3721 (defvar tabulated-list-entries)
3722 (defvar tabulated-list-sort-key)
3723 (declare-function tabulated-list-init-header "tabulated-list" ())
3724 (declare-function tabulated-list-print "tabulated-list"
3725 (&optional remember-pos update))
3726
3727 (defvar process-menu-query-only nil)
3728
3729 (defvar process-menu-mode-map
3730 (let ((map (make-sparse-keymap)))
3731 (define-key map [?d] 'process-menu-delete-process)
3732 map))
3733
3734 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3735 "Major mode for listing the processes called by Emacs."
3736 (setq tabulated-list-format [("Process" 15 t)
3737 ("Status" 7 t)
3738 ("Buffer" 15 t)
3739 ("TTY" 12 t)
3740 ("Command" 0 t)])
3741 (make-local-variable 'process-menu-query-only)
3742 (setq tabulated-list-sort-key (cons "Process" nil))
3743 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3744 (tabulated-list-init-header))
3745
3746 (defun process-menu-delete-process ()
3747 "Kill process at point in a `list-processes' buffer."
3748 (interactive)
3749 (let ((pos (point)))
3750 (delete-process (tabulated-list-get-id))
3751 (revert-buffer)
3752 (goto-char (min pos (point-max)))
3753 (if (eobp)
3754 (forward-line -1)
3755 (beginning-of-line))))
3756
3757 (defun list-processes--refresh ()
3758 "Recompute the list of processes for the Process List buffer.
3759 Also, delete any process that is exited or signaled."
3760 (setq tabulated-list-entries nil)
3761 (dolist (p (process-list))
3762 (cond ((memq (process-status p) '(exit signal closed))
3763 (delete-process p))
3764 ((or (not process-menu-query-only)
3765 (process-query-on-exit-flag p))
3766 (let* ((buf (process-buffer p))
3767 (type (process-type p))
3768 (name (process-name p))
3769 (status (symbol-name (process-status p)))
3770 (buf-label (if (buffer-live-p buf)
3771 `(,(buffer-name buf)
3772 face link
3773 help-echo ,(format-message
3774 "Visit buffer `%s'"
3775 (buffer-name buf))
3776 follow-link t
3777 process-buffer ,buf
3778 action process-menu-visit-buffer)
3779 "--"))
3780 (tty (or (process-tty-name p) "--"))
3781 (cmd
3782 (if (memq type '(network serial))
3783 (let ((contact (process-contact p t)))
3784 (if (eq type 'network)
3785 (format "(%s %s)"
3786 (if (plist-get contact :type)
3787 "datagram"
3788 "network")
3789 (if (plist-get contact :server)
3790 (format "server on %s"
3791 (or
3792 (plist-get contact :host)
3793 (plist-get contact :local)))
3794 (format "connection to %s"
3795 (plist-get contact :host))))
3796 (format "(serial port %s%s)"
3797 (or (plist-get contact :port) "?")
3798 (let ((speed (plist-get contact :speed)))
3799 (if speed
3800 (format " at %s b/s" speed)
3801 "")))))
3802 (mapconcat 'identity (process-command p) " "))))
3803 (push (list p (vector name status buf-label tty cmd))
3804 tabulated-list-entries))))))
3805
3806 (defun process-menu-visit-buffer (button)
3807 (display-buffer (button-get button 'process-buffer)))
3808
3809 (defun list-processes (&optional query-only buffer)
3810 "Display a list of all processes that are Emacs sub-processes.
3811 If optional argument QUERY-ONLY is non-nil, only processes with
3812 the query-on-exit flag set are listed.
3813 Any process listed as exited or signaled is actually eliminated
3814 after the listing is made.
3815 Optional argument BUFFER specifies a buffer to use, instead of
3816 \"*Process List*\".
3817 The return value is always nil.
3818
3819 This function lists only processes that were launched by Emacs. To
3820 see other processes running on the system, use `list-system-processes'."
3821 (interactive)
3822 (or (fboundp 'process-list)
3823 (error "Asynchronous subprocesses are not supported on this system"))
3824 (unless (bufferp buffer)
3825 (setq buffer (get-buffer-create "*Process List*")))
3826 (with-current-buffer buffer
3827 (process-menu-mode)
3828 (setq process-menu-query-only query-only)
3829 (list-processes--refresh)
3830 (tabulated-list-print))
3831 (display-buffer buffer)
3832 nil)
3833 \f
3834 ;;;; Prefix commands
3835
3836 (setq prefix-command--needs-update nil)
3837 (setq prefix-command--last-echo nil)
3838
3839 (defun internal-echo-keystrokes-prefix ()
3840 ;; BEWARE: Called directly from C code.
3841 ;; If the return value is non-nil, it means we are in the middle of
3842 ;; a command with prefix, such as a command invoked with prefix-arg.
3843 (if (not prefix-command--needs-update)
3844 prefix-command--last-echo
3845 (setq prefix-command--last-echo
3846 (let ((strs nil))
3847 (run-hook-wrapped 'prefix-command-echo-keystrokes-functions
3848 (lambda (fun) (push (funcall fun) strs)))
3849 (setq strs (delq nil strs))
3850 (when strs (mapconcat #'identity strs " "))))))
3851
3852 (defvar prefix-command-echo-keystrokes-functions nil
3853 "Abnormal hook which constructs the description of the current prefix state.
3854 Each function is called with no argument, should return a string or nil.")
3855
3856 (defun prefix-command-update ()
3857 "Update state of prefix commands.
3858 Call it whenever you change the \"prefix command state\"."
3859 (setq prefix-command--needs-update t))
3860
3861 (defvar prefix-command-preserve-state-hook nil
3862 "Normal hook run when a command needs to preserve the prefix.")
3863
3864 (defun prefix-command-preserve-state ()
3865 "Pass the current prefix command state to the next command.
3866 Should be called by all prefix commands.
3867 Runs `prefix-command-preserve-state-hook'."
3868 (run-hooks 'prefix-command-preserve-state-hook)
3869 ;; If the current command is a prefix command, we don't want the next (real)
3870 ;; command to have `last-command' set to, say, `universal-argument'.
3871 (setq this-command last-command)
3872 (setq real-this-command real-last-command)
3873 (prefix-command-update))
3874
3875 (defun reset-this-command-lengths ()
3876 (declare (obsolete prefix-command-preserve-state "25.1"))
3877 nil)
3878
3879 ;;;;; The main prefix command.
3880
3881 ;; FIXME: Declaration of `prefix-arg' should be moved here!?
3882
3883 (add-hook 'prefix-command-echo-keystrokes-functions
3884 #'universal-argument--description)
3885 (defun universal-argument--description ()
3886 (when prefix-arg
3887 (concat "C-u"
3888 (pcase prefix-arg
3889 (`(-) " -")
3890 (`(,(and (pred integerp) n))
3891 (let ((str ""))
3892 (while (and (> n 4) (= (mod n 4) 0))
3893 (setq str (concat str " C-u"))
3894 (setq n (/ n 4)))
3895 (if (= n 4) str (format " %s" prefix-arg))))
3896 (_ (format " %s" prefix-arg))))))
3897
3898 (add-hook 'prefix-command-preserve-state-hook
3899 #'universal-argument--preserve)
3900 (defun universal-argument--preserve ()
3901 (setq prefix-arg current-prefix-arg))
3902
3903 (defvar universal-argument-map
3904 (let ((map (make-sparse-keymap))
3905 (universal-argument-minus
3906 ;; For backward compatibility, minus with no modifiers is an ordinary
3907 ;; command if digits have already been entered.
3908 `(menu-item "" negative-argument
3909 :filter ,(lambda (cmd)
3910 (if (integerp prefix-arg) nil cmd)))))
3911 (define-key map [switch-frame]
3912 (lambda (e) (interactive "e")
3913 (handle-switch-frame e) (universal-argument--mode)))
3914 (define-key map [?\C-u] 'universal-argument-more)
3915 (define-key map [?-] universal-argument-minus)
3916 (define-key map [?0] 'digit-argument)
3917 (define-key map [?1] 'digit-argument)
3918 (define-key map [?2] 'digit-argument)
3919 (define-key map [?3] 'digit-argument)
3920 (define-key map [?4] 'digit-argument)
3921 (define-key map [?5] 'digit-argument)
3922 (define-key map [?6] 'digit-argument)
3923 (define-key map [?7] 'digit-argument)
3924 (define-key map [?8] 'digit-argument)
3925 (define-key map [?9] 'digit-argument)
3926 (define-key map [kp-0] 'digit-argument)
3927 (define-key map [kp-1] 'digit-argument)
3928 (define-key map [kp-2] 'digit-argument)
3929 (define-key map [kp-3] 'digit-argument)
3930 (define-key map [kp-4] 'digit-argument)
3931 (define-key map [kp-5] 'digit-argument)
3932 (define-key map [kp-6] 'digit-argument)
3933 (define-key map [kp-7] 'digit-argument)
3934 (define-key map [kp-8] 'digit-argument)
3935 (define-key map [kp-9] 'digit-argument)
3936 (define-key map [kp-subtract] universal-argument-minus)
3937 map)
3938 "Keymap used while processing \\[universal-argument].")
3939
3940 (defun universal-argument--mode ()
3941 (prefix-command-update)
3942 (set-transient-map universal-argument-map nil))
3943
3944 (defun universal-argument ()
3945 "Begin a numeric argument for the following command.
3946 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3947 \\[universal-argument] following the digits or minus sign ends the argument.
3948 \\[universal-argument] without digits or minus sign provides 4 as argument.
3949 Repeating \\[universal-argument] without digits or minus sign
3950 multiplies the argument by 4 each time.
3951 For some commands, just \\[universal-argument] by itself serves as a flag
3952 which is different in effect from any particular numeric argument.
3953 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3954 (interactive)
3955 (prefix-command-preserve-state)
3956 (setq prefix-arg (list 4))
3957 (universal-argument--mode))
3958
3959 (defun universal-argument-more (arg)
3960 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3961 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3962 (interactive "P")
3963 (prefix-command-preserve-state)
3964 (setq prefix-arg (if (consp arg)
3965 (list (* 4 (car arg)))
3966 (if (eq arg '-)
3967 (list -4)
3968 arg)))
3969 (when (consp prefix-arg) (universal-argument--mode)))
3970
3971 (defun negative-argument (arg)
3972 "Begin a negative numeric argument for the next command.
3973 \\[universal-argument] following digits or minus sign ends the argument."
3974 (interactive "P")
3975 (prefix-command-preserve-state)
3976 (setq prefix-arg (cond ((integerp arg) (- arg))
3977 ((eq arg '-) nil)
3978 (t '-)))
3979 (universal-argument--mode))
3980
3981 (defun digit-argument (arg)
3982 "Part of the numeric argument for the next command.
3983 \\[universal-argument] following digits or minus sign ends the argument."
3984 (interactive "P")
3985 (prefix-command-preserve-state)
3986 (let* ((char (if (integerp last-command-event)
3987 last-command-event
3988 (get last-command-event 'ascii-character)))
3989 (digit (- (logand char ?\177) ?0)))
3990 (setq prefix-arg (cond ((integerp arg)
3991 (+ (* arg 10)
3992 (if (< arg 0) (- digit) digit)))
3993 ((eq arg '-)
3994 ;; Treat -0 as just -, so that -01 will work.
3995 (if (zerop digit) '- (- digit)))
3996 (t
3997 digit))))
3998 (universal-argument--mode))
3999 \f
4000
4001 (defvar filter-buffer-substring-functions nil
4002 "This variable is a wrapper hook around `buffer-substring--filter'.")
4003 (make-obsolete-variable 'filter-buffer-substring-functions
4004 'filter-buffer-substring-function "24.4")
4005
4006 (defvar filter-buffer-substring-function #'buffer-substring--filter
4007 "Function to perform the filtering in `filter-buffer-substring'.
4008 The function is called with the same 3 arguments (BEG END DELETE)
4009 that `filter-buffer-substring' received. It should return the
4010 buffer substring between BEG and END, after filtering. If DELETE is
4011 non-nil, it should delete the text between BEG and END from the buffer.")
4012
4013 (defvar buffer-substring-filters nil
4014 "List of filter functions for `buffer-substring--filter'.
4015 Each function must accept a single argument, a string, and return a string.
4016 The buffer substring is passed to the first function in the list,
4017 and the return value of each function is passed to the next.
4018 As a special convention, point is set to the start of the buffer text
4019 being operated on (i.e., the first argument of `buffer-substring--filter')
4020 before these functions are called.")
4021 (make-obsolete-variable 'buffer-substring-filters
4022 'filter-buffer-substring-function "24.1")
4023
4024 (defun filter-buffer-substring (beg end &optional delete)
4025 "Return the buffer substring between BEG and END, after filtering.
4026 If DELETE is non-nil, delete the text between BEG and END from the buffer.
4027
4028 This calls the function that `filter-buffer-substring-function' specifies
4029 \(passing the same three arguments that it received) to do the work,
4030 and returns whatever it does. The default function does no filtering,
4031 unless a hook has been set.
4032
4033 Use `filter-buffer-substring' instead of `buffer-substring',
4034 `buffer-substring-no-properties', or `delete-and-extract-region' when
4035 you want to allow filtering to take place. For example, major or minor
4036 modes can use `filter-buffer-substring-function' to extract characters
4037 that are special to a buffer, and should not be copied into other buffers."
4038 (funcall filter-buffer-substring-function beg end delete))
4039
4040 (defun buffer-substring--filter (beg end &optional delete)
4041 "Default function to use for `filter-buffer-substring-function'.
4042 Its arguments and return value are as specified for `filter-buffer-substring'.
4043 This respects the wrapper hook `filter-buffer-substring-functions',
4044 and the abnormal hook `buffer-substring-filters'.
4045 No filtering is done unless a hook says to."
4046 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
4047 (cond
4048 ((or delete buffer-substring-filters)
4049 (save-excursion
4050 (goto-char beg)
4051 (let ((string (if delete (delete-and-extract-region beg end)
4052 (buffer-substring beg end))))
4053 (dolist (filter buffer-substring-filters)
4054 (setq string (funcall filter string)))
4055 string)))
4056 (t
4057 (buffer-substring beg end)))))
4058
4059
4060 ;;;; Window system cut and paste hooks.
4061
4062 (defvar interprogram-cut-function #'gui-select-text
4063 "Function to call to make a killed region available to other programs.
4064 Most window systems provide a facility for cutting and pasting
4065 text between different programs, such as the clipboard on X and
4066 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4067
4068 This variable holds a function that Emacs calls whenever text is
4069 put in the kill ring, to make the new kill available to other
4070 programs. The function takes one argument, TEXT, which is a
4071 string containing the text which should be made available.")
4072
4073 (defvar interprogram-paste-function #'gui-selection-value
4074 "Function to call to get text cut from other programs.
4075 Most window systems provide a facility for cutting and pasting
4076 text between different programs, such as the clipboard on X and
4077 MS-Windows, or the pasteboard on Nextstep/Mac OS.
4078
4079 This variable holds a function that Emacs calls to obtain text
4080 that other programs have provided for pasting. The function is
4081 called with no arguments. If no other program has provided text
4082 to paste, the function should return nil (in which case the
4083 caller, usually `current-kill', should use the top of the Emacs
4084 kill ring). If another program has provided text to paste, the
4085 function should return that text as a string (in which case the
4086 caller should put this string in the kill ring as the latest
4087 kill).
4088
4089 The function may also return a list of strings if the window
4090 system supports multiple selections. The first string will be
4091 used as the pasted text, but the other will be placed in the kill
4092 ring for easy access via `yank-pop'.
4093
4094 Note that the function should return a string only if a program
4095 other than Emacs has provided a string for pasting; if Emacs
4096 provided the most recent string, the function should return nil.
4097 If it is difficult to tell whether Emacs or some other program
4098 provided the current string, it is probably good enough to return
4099 nil if the string is equal (according to `string=') to the last
4100 text Emacs provided.")
4101 \f
4102
4103
4104 ;;;; The kill ring data structure.
4105
4106 (defvar kill-ring nil
4107 "List of killed text sequences.
4108 Since the kill ring is supposed to interact nicely with cut-and-paste
4109 facilities offered by window systems, use of this variable should
4110 interact nicely with `interprogram-cut-function' and
4111 `interprogram-paste-function'. The functions `kill-new',
4112 `kill-append', and `current-kill' are supposed to implement this
4113 interaction; you may want to use them instead of manipulating the kill
4114 ring directly.")
4115
4116 (defcustom kill-ring-max 60
4117 "Maximum length of kill ring before oldest elements are thrown away."
4118 :type 'integer
4119 :group 'killing)
4120
4121 (defvar kill-ring-yank-pointer nil
4122 "The tail of the kill ring whose car is the last thing yanked.")
4123
4124 (defcustom save-interprogram-paste-before-kill nil
4125 "Save clipboard strings into kill ring before replacing them.
4126 When one selects something in another program to paste it into Emacs,
4127 but kills something in Emacs before actually pasting it,
4128 this selection is gone unless this variable is non-nil,
4129 in which case the other program's selection is saved in the `kill-ring'
4130 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
4131 :type 'boolean
4132 :group 'killing
4133 :version "23.2")
4134
4135 (defcustom kill-do-not-save-duplicates nil
4136 "Do not add a new string to `kill-ring' if it duplicates the last one.
4137 The comparison is done using `equal-including-properties'."
4138 :type 'boolean
4139 :group 'killing
4140 :version "23.2")
4141
4142 (defun kill-new (string &optional replace)
4143 "Make STRING the latest kill in the kill ring.
4144 Set `kill-ring-yank-pointer' to point to it.
4145 If `interprogram-cut-function' is non-nil, apply it to STRING.
4146 Optional second argument REPLACE non-nil means that STRING will replace
4147 the front of the kill ring, rather than being added to the list.
4148
4149 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
4150 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
4151 STRING.
4152
4153 When the yank handler has a non-nil PARAM element, the original STRING
4154 argument is not used by `insert-for-yank'. However, since Lisp code
4155 may access and use elements from the kill ring directly, the STRING
4156 argument should still be a \"useful\" string for such uses."
4157 (unless (and kill-do-not-save-duplicates
4158 ;; Due to text properties such as 'yank-handler that
4159 ;; can alter the contents to yank, comparison using
4160 ;; `equal' is unsafe.
4161 (equal-including-properties string (car kill-ring)))
4162 (if (fboundp 'menu-bar-update-yank-menu)
4163 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4164 (when save-interprogram-paste-before-kill
4165 (let ((interprogram-paste (and interprogram-paste-function
4166 (funcall interprogram-paste-function))))
4167 (when interprogram-paste
4168 (dolist (s (if (listp interprogram-paste)
4169 (nreverse interprogram-paste)
4170 (list interprogram-paste)))
4171 (unless (and kill-do-not-save-duplicates
4172 (equal-including-properties s (car kill-ring)))
4173 (push s kill-ring))))))
4174 (unless (and kill-do-not-save-duplicates
4175 (equal-including-properties string (car kill-ring)))
4176 (if (and replace kill-ring)
4177 (setcar kill-ring string)
4178 (push string kill-ring)
4179 (if (> (length kill-ring) kill-ring-max)
4180 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
4181 (setq kill-ring-yank-pointer kill-ring)
4182 (if interprogram-cut-function
4183 (funcall interprogram-cut-function string)))
4184
4185 ;; It has been argued that this should work similar to `self-insert-command'
4186 ;; which merges insertions in undo-list in groups of 20 (hard-coded in cmds.c).
4187 (defcustom kill-append-merge-undo nil
4188 "Whether appending to kill ring also makes \\[undo] restore both pieces of text simultaneously."
4189 :type 'boolean
4190 :group 'killing
4191 :version "25.1")
4192
4193 (defun kill-append (string before-p)
4194 "Append STRING to the end of the latest kill in the kill ring.
4195 If BEFORE-P is non-nil, prepend STRING to the kill.
4196 Also removes the last undo boundary in the current buffer,
4197 depending on `kill-append-merge-undo'.
4198 If `interprogram-cut-function' is set, pass the resulting kill to it."
4199 (let* ((cur (car kill-ring)))
4200 (kill-new (if before-p (concat string cur) (concat cur string))
4201 (or (= (length cur) 0)
4202 (equal nil (get-text-property 0 'yank-handler cur))))
4203 (when (and kill-append-merge-undo (not buffer-read-only))
4204 (let ((prev buffer-undo-list)
4205 (next (cdr buffer-undo-list)))
4206 ;; find the next undo boundary
4207 (while (car next)
4208 (pop next)
4209 (pop prev))
4210 ;; remove this undo boundary
4211 (when prev
4212 (setcdr prev (cdr next)))))))
4213
4214 (defcustom yank-pop-change-selection nil
4215 "Whether rotating the kill ring changes the window system selection.
4216 If non-nil, whenever the kill ring is rotated (usually via the
4217 `yank-pop' command), Emacs also calls `interprogram-cut-function'
4218 to copy the new kill to the window system selection."
4219 :type 'boolean
4220 :group 'killing
4221 :version "23.1")
4222
4223 (defun current-kill (n &optional do-not-move)
4224 "Rotate the yanking point by N places, and then return that kill.
4225 If N is zero and `interprogram-paste-function' is set to a
4226 function that returns a string or a list of strings, and if that
4227 function doesn't return nil, then that string (or list) is added
4228 to the front of the kill ring and the string (or first string in
4229 the list) is returned as the latest kill.
4230
4231 If N is not zero, and if `yank-pop-change-selection' is
4232 non-nil, use `interprogram-cut-function' to transfer the
4233 kill at the new yank point into the window system selection.
4234
4235 If optional arg DO-NOT-MOVE is non-nil, then don't actually
4236 move the yanking point; just return the Nth kill forward."
4237
4238 (let ((interprogram-paste (and (= n 0)
4239 interprogram-paste-function
4240 (funcall interprogram-paste-function))))
4241 (if interprogram-paste
4242 (progn
4243 ;; Disable the interprogram cut function when we add the new
4244 ;; text to the kill ring, so Emacs doesn't try to own the
4245 ;; selection, with identical text.
4246 (let ((interprogram-cut-function nil))
4247 (if (listp interprogram-paste)
4248 (mapc 'kill-new (nreverse interprogram-paste))
4249 (kill-new interprogram-paste)))
4250 (car kill-ring))
4251 (or kill-ring (error "Kill ring is empty"))
4252 (let ((ARGth-kill-element
4253 (nthcdr (mod (- n (length kill-ring-yank-pointer))
4254 (length kill-ring))
4255 kill-ring)))
4256 (unless do-not-move
4257 (setq kill-ring-yank-pointer ARGth-kill-element)
4258 (when (and yank-pop-change-selection
4259 (> n 0)
4260 interprogram-cut-function)
4261 (funcall interprogram-cut-function (car ARGth-kill-element))))
4262 (car ARGth-kill-element)))))
4263
4264
4265
4266 ;;;; Commands for manipulating the kill ring.
4267
4268 (defcustom kill-read-only-ok nil
4269 "Non-nil means don't signal an error for killing read-only text."
4270 :type 'boolean
4271 :group 'killing)
4272
4273 (defun kill-region (beg end &optional region)
4274 "Kill (\"cut\") text between point and mark.
4275 This deletes the text from the buffer and saves it in the kill ring.
4276 The command \\[yank] can retrieve it from there.
4277 \(If you want to save the region without killing it, use \\[kill-ring-save].)
4278
4279 If you want to append the killed region to the last killed text,
4280 use \\[append-next-kill] before \\[kill-region].
4281
4282 Any command that calls this function is a \"kill command\".
4283 If the previous command was also a kill command,
4284 the text killed this time appends to the text killed last time
4285 to make one entry in the kill ring.
4286
4287 The killed text is filtered by `filter-buffer-substring' before it is
4288 saved in the kill ring, so the actual saved text might be different
4289 from what was killed.
4290
4291 If the buffer is read-only, Emacs will beep and refrain from deleting
4292 the text, but put the text in the kill ring anyway. This means that
4293 you can use the killing commands to copy text from a read-only buffer.
4294
4295 Lisp programs should use this function for killing text.
4296 (To delete text, use `delete-region'.)
4297 Supply two arguments, character positions BEG and END indicating the
4298 stretch of text to be killed. If the optional argument REGION is
4299 non-nil, the function ignores BEG and END, and kills the current
4300 region instead."
4301 ;; Pass mark first, then point, because the order matters when
4302 ;; calling `kill-append'.
4303 (interactive (list (mark) (point) 'region))
4304 (unless (and beg end)
4305 (user-error "The mark is not set now, so there is no region"))
4306 (condition-case nil
4307 (let ((string (if region
4308 (funcall region-extract-function 'delete)
4309 (filter-buffer-substring beg end 'delete))))
4310 (when string ;STRING is nil if BEG = END
4311 ;; Add that string to the kill ring, one way or another.
4312 (if (eq last-command 'kill-region)
4313 (kill-append string (< end beg))
4314 (kill-new string)))
4315 (when (or string (eq last-command 'kill-region))
4316 (setq this-command 'kill-region))
4317 (setq deactivate-mark t)
4318 nil)
4319 ((buffer-read-only text-read-only)
4320 ;; The code above failed because the buffer, or some of the characters
4321 ;; in the region, are read-only.
4322 ;; We should beep, in case the user just isn't aware of this.
4323 ;; However, there's no harm in putting
4324 ;; the region's text in the kill ring, anyway.
4325 (copy-region-as-kill beg end region)
4326 ;; Set this-command now, so it will be set even if we get an error.
4327 (setq this-command 'kill-region)
4328 ;; This should barf, if appropriate, and give us the correct error.
4329 (if kill-read-only-ok
4330 (progn (message "Read only text copied to kill ring") nil)
4331 ;; Signal an error if the buffer is read-only.
4332 (barf-if-buffer-read-only)
4333 ;; If the buffer isn't read-only, the text is.
4334 (signal 'text-read-only (list (current-buffer)))))))
4335
4336 ;; copy-region-as-kill no longer sets this-command, because it's confusing
4337 ;; to get two copies of the text when the user accidentally types M-w and
4338 ;; then corrects it with the intended C-w.
4339 (defun copy-region-as-kill (beg end &optional region)
4340 "Save the region as if killed, but don't kill it.
4341 In Transient Mark mode, deactivate the mark.
4342 If `interprogram-cut-function' is non-nil, also save the text for a window
4343 system cut and paste.
4344
4345 The copied text is filtered by `filter-buffer-substring' before it is
4346 saved in the kill ring, so the actual saved text might be different
4347 from what was in the buffer.
4348
4349 When called from Lisp, save in the kill ring the stretch of text
4350 between BEG and END, unless the optional argument REGION is
4351 non-nil, in which case ignore BEG and END, and save the current
4352 region instead.
4353
4354 This command's old key binding has been given to `kill-ring-save'."
4355 ;; Pass mark first, then point, because the order matters when
4356 ;; calling `kill-append'.
4357 (interactive (list (mark) (point)
4358 (prefix-numeric-value current-prefix-arg)))
4359 (let ((str (if region
4360 (funcall region-extract-function nil)
4361 (filter-buffer-substring beg end))))
4362 (if (eq last-command 'kill-region)
4363 (kill-append str (< end beg))
4364 (kill-new str)))
4365 (setq deactivate-mark t)
4366 nil)
4367
4368 (defun kill-ring-save (beg end &optional region)
4369 "Save the region as if killed, but don't kill it.
4370 In Transient Mark mode, deactivate the mark.
4371 If `interprogram-cut-function' is non-nil, also save the text for a window
4372 system cut and paste.
4373
4374 If you want to append the killed line to the last killed text,
4375 use \\[append-next-kill] before \\[kill-ring-save].
4376
4377 The copied text is filtered by `filter-buffer-substring' before it is
4378 saved in the kill ring, so the actual saved text might be different
4379 from what was in the buffer.
4380
4381 When called from Lisp, save in the kill ring the stretch of text
4382 between BEG and END, unless the optional argument REGION is
4383 non-nil, in which case ignore BEG and END, and save the current
4384 region instead.
4385
4386 This command is similar to `copy-region-as-kill', except that it gives
4387 visual feedback indicating the extent of the region being copied."
4388 ;; Pass mark first, then point, because the order matters when
4389 ;; calling `kill-append'.
4390 (interactive (list (mark) (point)
4391 (prefix-numeric-value current-prefix-arg)))
4392 (copy-region-as-kill beg end region)
4393 ;; This use of called-interactively-p is correct because the code it
4394 ;; controls just gives the user visual feedback.
4395 (if (called-interactively-p 'interactive)
4396 (indicate-copied-region)))
4397
4398 (defun indicate-copied-region (&optional message-len)
4399 "Indicate that the region text has been copied interactively.
4400 If the mark is visible in the selected window, blink the cursor
4401 between point and mark if there is currently no active region
4402 highlighting.
4403
4404 If the mark lies outside the selected window, display an
4405 informative message containing a sample of the copied text. The
4406 optional argument MESSAGE-LEN, if non-nil, specifies the length
4407 of this sample text; it defaults to 40."
4408 (let ((mark (mark t))
4409 (point (point))
4410 ;; Inhibit quitting so we can make a quit here
4411 ;; look like a C-g typed as a command.
4412 (inhibit-quit t))
4413 (if (pos-visible-in-window-p mark (selected-window))
4414 ;; Swap point-and-mark quickly so as to show the region that
4415 ;; was selected. Don't do it if the region is highlighted.
4416 (unless (and (region-active-p)
4417 (face-background 'region))
4418 ;; Swap point and mark.
4419 (set-marker (mark-marker) (point) (current-buffer))
4420 (goto-char mark)
4421 (sit-for blink-matching-delay)
4422 ;; Swap back.
4423 (set-marker (mark-marker) mark (current-buffer))
4424 (goto-char point)
4425 ;; If user quit, deactivate the mark
4426 ;; as C-g would as a command.
4427 (and quit-flag (region-active-p)
4428 (deactivate-mark)))
4429 (let ((len (min (abs (- mark point))
4430 (or message-len 40))))
4431 (if (< point mark)
4432 ;; Don't say "killed"; that is misleading.
4433 (message "Saved text until \"%s\""
4434 (buffer-substring-no-properties (- mark len) mark))
4435 (message "Saved text from \"%s\""
4436 (buffer-substring-no-properties mark (+ mark len))))))))
4437
4438 (defun append-next-kill (&optional interactive)
4439 "Cause following command, if it kills, to add to previous kill.
4440 If the next command kills forward from point, the kill is
4441 appended to the previous killed text. If the command kills
4442 backward, the kill is prepended. Kill commands that act on the
4443 region, such as `kill-region', are regarded as killing forward if
4444 point is after mark, and killing backward if point is before
4445 mark.
4446
4447 If the next command is not a kill command, `append-next-kill' has
4448 no effect.
4449
4450 The argument is used for internal purposes; do not supply one."
4451 (interactive "p")
4452 ;; We don't use (interactive-p), since that breaks kbd macros.
4453 (if interactive
4454 (progn
4455 (setq this-command 'kill-region)
4456 (message "If the next command is a kill, it will append"))
4457 (setq last-command 'kill-region)))
4458
4459 (defvar bidi-directional-controls-chars "\x202a-\x202e\x2066-\x2069"
4460 "Character set that matches bidirectional formatting control characters.")
4461
4462 (defvar bidi-directional-non-controls-chars "^\x202a-\x202e\x2066-\x2069"
4463 "Character set that matches any character except bidirectional controls.")
4464
4465 (defun squeeze-bidi-context-1 (from to category replacement)
4466 "A subroutine of `squeeze-bidi-context'.
4467 FROM and TO should be markers, CATEGORY and REPLACEMENT should be strings."
4468 (let ((pt (copy-marker from))
4469 (limit (copy-marker to))
4470 (old-pt 0)
4471 lim1)
4472 (setq lim1 limit)
4473 (goto-char pt)
4474 (while (< pt limit)
4475 (if (> pt old-pt)
4476 (move-marker lim1
4477 (save-excursion
4478 ;; L and R categories include embedding and
4479 ;; override controls, but we don't want to
4480 ;; replace them, because that might change
4481 ;; the visual order. Likewise with PDF and
4482 ;; isolate controls.
4483 (+ pt (skip-chars-forward
4484 bidi-directional-non-controls-chars
4485 limit)))))
4486 ;; Replace any run of non-RTL characters by a single LRM.
4487 (if (null (re-search-forward category lim1 t))
4488 ;; No more characters of CATEGORY, we are done.
4489 (setq pt limit)
4490 (replace-match replacement nil t)
4491 (move-marker pt (point)))
4492 (setq old-pt pt)
4493 ;; Skip directional controls, if any.
4494 (move-marker
4495 pt (+ pt (skip-chars-forward bidi-directional-controls-chars limit))))))
4496
4497 (defun squeeze-bidi-context (from to)
4498 "Replace characters between FROM and TO while keeping bidi context.
4499
4500 This function replaces the region of text with as few characters
4501 as possible, while preserving the effect that region will have on
4502 bidirectional display before and after the region."
4503 (let ((start (set-marker (make-marker)
4504 (if (> from 0) from (+ (point-max) from))))
4505 (end (set-marker (make-marker) to))
4506 ;; This is for when they copy text with read-only text
4507 ;; properties.
4508 (inhibit-read-only t))
4509 (if (null (marker-position end))
4510 (setq end (point-max-marker)))
4511 ;; Replace each run of non-RTL characters with a single LRM.
4512 (squeeze-bidi-context-1 start end "\\CR+" "\x200e")
4513 ;; Replace each run of non-LTR characters with a single RLM. Note
4514 ;; that the \cR category includes both the Arabic Letter (AL) and
4515 ;; R characters; here we ignore the distinction between them,
4516 ;; because that distinction only affects Arabic Number (AN)
4517 ;; characters, which are weak and don't affect the reordering.
4518 (squeeze-bidi-context-1 start end "\\CL+" "\x200f")))
4519
4520 (defun line-substring-with-bidi-context (start end &optional no-properties)
4521 "Return buffer text between START and END with its bidi context.
4522
4523 START and END are assumed to belong to the same physical line
4524 of buffer text. This function prepends and appends to the text
4525 between START and END bidi control characters that preserve the
4526 visual order of that text when it is inserted at some other place."
4527 (if (or (< start (point-min))
4528 (> end (point-max)))
4529 (signal 'args-out-of-range (list (current-buffer) start end)))
4530 (let ((buf (current-buffer))
4531 substr para-dir from to)
4532 (save-excursion
4533 (goto-char start)
4534 (setq para-dir (current-bidi-paragraph-direction))
4535 (setq from (line-beginning-position)
4536 to (line-end-position))
4537 (goto-char from)
4538 ;; If we don't have any mixed directional characters in the
4539 ;; entire line, we can just copy the substring without adding
4540 ;; any context.
4541 (if (or (looking-at-p "\\CR*$")
4542 (looking-at-p "\\CL*$"))
4543 (setq substr (if no-properties
4544 (buffer-substring-no-properties start end)
4545 (buffer-substring start end)))
4546 (setq substr
4547 (with-temp-buffer
4548 (if no-properties
4549 (insert-buffer-substring-no-properties buf from to)
4550 (insert-buffer-substring buf from to))
4551 (squeeze-bidi-context 1 (1+ (- start from)))
4552 (squeeze-bidi-context (- end to) nil)
4553 (buffer-substring 1 (point-max)))))
4554
4555 ;; Wrap the string in LRI/RLI..PDI pair to achieve 2 effects:
4556 ;; (1) force the string to have the same base embedding
4557 ;; direction as the paragraph direction at the source, no matter
4558 ;; what is the paragraph direction at destination; and (2) avoid
4559 ;; affecting the visual order of the surrounding text at
4560 ;; destination if there are characters of different
4561 ;; directionality there.
4562 (concat (if (eq para-dir 'left-to-right) "\x2066" "\x2067")
4563 substr "\x2069"))))
4564
4565 (defun buffer-substring-with-bidi-context (start end &optional no-properties)
4566 "Return portion of current buffer between START and END with bidi context.
4567
4568 This function works similar to `buffer-substring', but it prepends and
4569 appends to the text bidi directional control characters necessary to
4570 preserve the visual appearance of the text if it is inserted at another
4571 place. This is useful when the buffer substring includes bidirectional
4572 text and control characters that cause non-trivial reordering on display.
4573 If copied verbatim, such text can have a very different visual appearance,
4574 and can also change the visual appearance of the surrounding text at the
4575 destination of the copy.
4576
4577 Optional argument NO-PROPERTIES, if non-nil, means copy the text without
4578 the text properties."
4579 (let (line-end substr)
4580 (if (or (< start (point-min))
4581 (> end (point-max)))
4582 (signal 'args-out-of-range (list (current-buffer) start end)))
4583 (save-excursion
4584 (goto-char start)
4585 (setq line-end (min end (line-end-position)))
4586 (while (< start end)
4587 (setq substr
4588 (concat substr
4589 (if substr "\n" "")
4590 (line-substring-with-bidi-context start line-end
4591 no-properties)))
4592 (forward-line 1)
4593 (setq start (point))
4594 (setq line-end (min end (line-end-position))))
4595 substr)))
4596 \f
4597 ;; Yanking.
4598
4599 (defcustom yank-handled-properties
4600 '((font-lock-face . yank-handle-font-lock-face-property)
4601 (category . yank-handle-category-property))
4602 "List of special text property handling conditions for yanking.
4603 Each element should have the form (PROP . FUN), where PROP is a
4604 property symbol and FUN is a function. When the `yank' command
4605 inserts text into the buffer, it scans the inserted text for
4606 stretches of text that have `eq' values of the text property
4607 PROP; for each such stretch of text, FUN is called with three
4608 arguments: the property's value in that text, and the start and
4609 end positions of the text.
4610
4611 This is done prior to removing the properties specified by
4612 `yank-excluded-properties'."
4613 :group 'killing
4614 :type '(repeat (cons (symbol :tag "property symbol")
4615 function))
4616 :version "24.3")
4617
4618 ;; This is actually used in subr.el but defcustom does not work there.
4619 (defcustom yank-excluded-properties
4620 '(category field follow-link fontified font-lock-face help-echo
4621 intangible invisible keymap local-map mouse-face read-only
4622 yank-handler)
4623 "Text properties to discard when yanking.
4624 The value should be a list of text properties to discard or t,
4625 which means to discard all text properties.
4626
4627 See also `yank-handled-properties'."
4628 :type '(choice (const :tag "All" t) (repeat symbol))
4629 :group 'killing
4630 :version "24.3")
4631
4632 (defvar yank-window-start nil)
4633 (defvar yank-undo-function nil
4634 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
4635 Function is called with two parameters, START and END corresponding to
4636 the value of the mark and point; it is guaranteed that START <= END.
4637 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
4638
4639 (defun yank-pop (&optional arg)
4640 "Replace just-yanked stretch of killed text with a different stretch.
4641 This command is allowed only immediately after a `yank' or a `yank-pop'.
4642 At such a time, the region contains a stretch of reinserted
4643 previously-killed text. `yank-pop' deletes that text and inserts in its
4644 place a different stretch of killed text.
4645
4646 With no argument, the previous kill is inserted.
4647 With argument N, insert the Nth previous kill.
4648 If N is negative, this is a more recent kill.
4649
4650 The sequence of kills wraps around, so that after the oldest one
4651 comes the newest one.
4652
4653 When this command inserts killed text into the buffer, it honors
4654 `yank-excluded-properties' and `yank-handler' as described in the
4655 doc string for `insert-for-yank-1', which see."
4656 (interactive "*p")
4657 (if (not (eq last-command 'yank))
4658 (user-error "Previous command was not a yank"))
4659 (setq this-command 'yank)
4660 (unless arg (setq arg 1))
4661 (let ((inhibit-read-only t)
4662 (before (< (point) (mark t))))
4663 (if before
4664 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
4665 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
4666 (setq yank-undo-function nil)
4667 (set-marker (mark-marker) (point) (current-buffer))
4668 (insert-for-yank (current-kill arg))
4669 ;; Set the window start back where it was in the yank command,
4670 ;; if possible.
4671 (set-window-start (selected-window) yank-window-start t)
4672 (if before
4673 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4674 ;; It is cleaner to avoid activation, even though the command
4675 ;; loop would deactivate the mark because we inserted text.
4676 (goto-char (prog1 (mark t)
4677 (set-marker (mark-marker) (point) (current-buffer))))))
4678 nil)
4679
4680 (defun yank (&optional arg)
4681 "Reinsert (\"paste\") the last stretch of killed text.
4682 More precisely, reinsert the most recent kill, which is the
4683 stretch of killed text most recently killed OR yanked. Put point
4684 at the end, and set mark at the beginning without activating it.
4685 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
4686 With argument N, reinsert the Nth most recent kill.
4687
4688 When this command inserts text into the buffer, it honors the
4689 `yank-handled-properties' and `yank-excluded-properties'
4690 variables, and the `yank-handler' text property. See
4691 `insert-for-yank-1' for details.
4692
4693 See also the command `yank-pop' (\\[yank-pop])."
4694 (interactive "*P")
4695 (setq yank-window-start (window-start))
4696 ;; If we don't get all the way thru, make last-command indicate that
4697 ;; for the following command.
4698 (setq this-command t)
4699 (push-mark (point))
4700 (insert-for-yank (current-kill (cond
4701 ((listp arg) 0)
4702 ((eq arg '-) -2)
4703 (t (1- arg)))))
4704 (if (consp arg)
4705 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4706 ;; It is cleaner to avoid activation, even though the command
4707 ;; loop would deactivate the mark because we inserted text.
4708 (goto-char (prog1 (mark t)
4709 (set-marker (mark-marker) (point) (current-buffer)))))
4710 ;; If we do get all the way thru, make this-command indicate that.
4711 (if (eq this-command t)
4712 (setq this-command 'yank))
4713 nil)
4714
4715 (defun rotate-yank-pointer (arg)
4716 "Rotate the yanking point in the kill ring.
4717 With ARG, rotate that many kills forward (or backward, if negative)."
4718 (interactive "p")
4719 (current-kill arg))
4720 \f
4721 ;; Some kill commands.
4722
4723 ;; Internal subroutine of delete-char
4724 (defun kill-forward-chars (arg)
4725 (if (listp arg) (setq arg (car arg)))
4726 (if (eq arg '-) (setq arg -1))
4727 (kill-region (point) (+ (point) arg)))
4728
4729 ;; Internal subroutine of backward-delete-char
4730 (defun kill-backward-chars (arg)
4731 (if (listp arg) (setq arg (car arg)))
4732 (if (eq arg '-) (setq arg -1))
4733 (kill-region (point) (- (point) arg)))
4734
4735 (defcustom backward-delete-char-untabify-method 'untabify
4736 "The method for untabifying when deleting backward.
4737 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4738 `hungry' -- delete all whitespace, both tabs and spaces;
4739 `all' -- delete all whitespace, including tabs, spaces and newlines;
4740 nil -- just delete one character."
4741 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4742 :version "20.3"
4743 :group 'killing)
4744
4745 (defun backward-delete-char-untabify (arg &optional killp)
4746 "Delete characters backward, changing tabs into spaces.
4747 The exact behavior depends on `backward-delete-char-untabify-method'.
4748 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4749 Interactively, ARG is the prefix arg (default 1)
4750 and KILLP is t if a prefix arg was specified."
4751 (interactive "*p\nP")
4752 (when (eq backward-delete-char-untabify-method 'untabify)
4753 (let ((count arg))
4754 (save-excursion
4755 (while (and (> count 0) (not (bobp)))
4756 (if (= (preceding-char) ?\t)
4757 (let ((col (current-column)))
4758 (forward-char -1)
4759 (setq col (- col (current-column)))
4760 (insert-char ?\s col)
4761 (delete-char 1)))
4762 (forward-char -1)
4763 (setq count (1- count))))))
4764 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4765 ((eq backward-delete-char-untabify-method 'all)
4766 " \t\n\r")))
4767 (n (if skip
4768 (let* ((oldpt (point))
4769 (wh (- oldpt (save-excursion
4770 (skip-chars-backward skip)
4771 (constrain-to-field nil oldpt)))))
4772 (+ arg (if (zerop wh) 0 (1- wh))))
4773 arg)))
4774 ;; Avoid warning about delete-backward-char
4775 (with-no-warnings (delete-backward-char n killp))))
4776
4777 (defun zap-to-char (arg char)
4778 "Kill up to and including ARGth occurrence of CHAR.
4779 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4780 Goes backward if ARG is negative; error if CHAR not found."
4781 (interactive (list (prefix-numeric-value current-prefix-arg)
4782 (read-char "Zap to char: " t)))
4783 ;; Avoid "obsolete" warnings for translation-table-for-input.
4784 (with-no-warnings
4785 (if (char-table-p translation-table-for-input)
4786 (setq char (or (aref translation-table-for-input char) char))))
4787 (kill-region (point) (progn
4788 (search-forward (char-to-string char) nil nil arg)
4789 (point))))
4790
4791 ;; kill-line and its subroutines.
4792
4793 (defcustom kill-whole-line nil
4794 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4795 :type 'boolean
4796 :group 'killing)
4797
4798 (defun kill-line (&optional arg)
4799 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4800 With prefix argument ARG, kill that many lines from point.
4801 Negative arguments kill lines backward.
4802 With zero argument, kills the text before point on the current line.
4803
4804 When calling from a program, nil means \"no arg\",
4805 a number counts as a prefix arg.
4806
4807 To kill a whole line, when point is not at the beginning, type \
4808 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4809
4810 If `show-trailing-whitespace' is non-nil, this command will just
4811 kill the rest of the current line, even if there are only
4812 nonblanks there.
4813
4814 If option `kill-whole-line' is non-nil, then this command kills the whole line
4815 including its terminating newline, when used at the beginning of a line
4816 with no argument. As a consequence, you can always kill a whole line
4817 by typing \\[move-beginning-of-line] \\[kill-line].
4818
4819 If you want to append the killed line to the last killed text,
4820 use \\[append-next-kill] before \\[kill-line].
4821
4822 If the buffer is read-only, Emacs will beep and refrain from deleting
4823 the line, but put the line in the kill ring anyway. This means that
4824 you can use this command to copy text from a read-only buffer.
4825 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4826 even beep.)"
4827 (interactive "P")
4828 (kill-region (point)
4829 ;; It is better to move point to the other end of the kill
4830 ;; before killing. That way, in a read-only buffer, point
4831 ;; moves across the text that is copied to the kill ring.
4832 ;; The choice has no effect on undo now that undo records
4833 ;; the value of point from before the command was run.
4834 (progn
4835 (if arg
4836 (forward-visible-line (prefix-numeric-value arg))
4837 (if (eobp)
4838 (signal 'end-of-buffer nil))
4839 (let ((end
4840 (save-excursion
4841 (end-of-visible-line) (point))))
4842 (if (or (save-excursion
4843 ;; If trailing whitespace is visible,
4844 ;; don't treat it as nothing.
4845 (unless show-trailing-whitespace
4846 (skip-chars-forward " \t" end))
4847 (= (point) end))
4848 (and kill-whole-line (bolp)))
4849 (forward-visible-line 1)
4850 (goto-char end))))
4851 (point))))
4852
4853 (defun kill-whole-line (&optional arg)
4854 "Kill current line.
4855 With prefix ARG, kill that many lines starting from the current line.
4856 If ARG is negative, kill backward. Also kill the preceding newline.
4857 \(This is meant to make \\[repeat] work well with negative arguments.)
4858 If ARG is zero, kill current line but exclude the trailing newline."
4859 (interactive "p")
4860 (or arg (setq arg 1))
4861 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4862 (signal 'end-of-buffer nil))
4863 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4864 (signal 'beginning-of-buffer nil))
4865 (unless (eq last-command 'kill-region)
4866 (kill-new "")
4867 (setq last-command 'kill-region))
4868 (cond ((zerop arg)
4869 ;; We need to kill in two steps, because the previous command
4870 ;; could have been a kill command, in which case the text
4871 ;; before point needs to be prepended to the current kill
4872 ;; ring entry and the text after point appended. Also, we
4873 ;; need to use save-excursion to avoid copying the same text
4874 ;; twice to the kill ring in read-only buffers.
4875 (save-excursion
4876 (kill-region (point) (progn (forward-visible-line 0) (point))))
4877 (kill-region (point) (progn (end-of-visible-line) (point))))
4878 ((< arg 0)
4879 (save-excursion
4880 (kill-region (point) (progn (end-of-visible-line) (point))))
4881 (kill-region (point)
4882 (progn (forward-visible-line (1+ arg))
4883 (unless (bobp) (backward-char))
4884 (point))))
4885 (t
4886 (save-excursion
4887 (kill-region (point) (progn (forward-visible-line 0) (point))))
4888 (kill-region (point)
4889 (progn (forward-visible-line arg) (point))))))
4890
4891 (defun forward-visible-line (arg)
4892 "Move forward by ARG lines, ignoring currently invisible newlines only.
4893 If ARG is negative, move backward -ARG lines.
4894 If ARG is zero, move to the beginning of the current line."
4895 (condition-case nil
4896 (if (> arg 0)
4897 (progn
4898 (while (> arg 0)
4899 (or (zerop (forward-line 1))
4900 (signal 'end-of-buffer nil))
4901 ;; If the newline we just skipped is invisible,
4902 ;; don't count it.
4903 (let ((prop
4904 (get-char-property (1- (point)) 'invisible)))
4905 (if (if (eq buffer-invisibility-spec t)
4906 prop
4907 (or (memq prop buffer-invisibility-spec)
4908 (assq prop buffer-invisibility-spec)))
4909 (setq arg (1+ arg))))
4910 (setq arg (1- arg)))
4911 ;; If invisible text follows, and it is a number of complete lines,
4912 ;; skip it.
4913 (let ((opoint (point)))
4914 (while (and (not (eobp))
4915 (let ((prop
4916 (get-char-property (point) 'invisible)))
4917 (if (eq buffer-invisibility-spec t)
4918 prop
4919 (or (memq prop buffer-invisibility-spec)
4920 (assq prop buffer-invisibility-spec)))))
4921 (goto-char
4922 (if (get-text-property (point) 'invisible)
4923 (or (next-single-property-change (point) 'invisible)
4924 (point-max))
4925 (next-overlay-change (point)))))
4926 (unless (bolp)
4927 (goto-char opoint))))
4928 (let ((first t))
4929 (while (or first (<= arg 0))
4930 (if first
4931 (beginning-of-line)
4932 (or (zerop (forward-line -1))
4933 (signal 'beginning-of-buffer nil)))
4934 ;; If the newline we just moved to is invisible,
4935 ;; don't count it.
4936 (unless (bobp)
4937 (let ((prop
4938 (get-char-property (1- (point)) 'invisible)))
4939 (unless (if (eq buffer-invisibility-spec t)
4940 prop
4941 (or (memq prop buffer-invisibility-spec)
4942 (assq prop buffer-invisibility-spec)))
4943 (setq arg (1+ arg)))))
4944 (setq first nil))
4945 ;; If invisible text follows, and it is a number of complete lines,
4946 ;; skip it.
4947 (let ((opoint (point)))
4948 (while (and (not (bobp))
4949 (let ((prop
4950 (get-char-property (1- (point)) 'invisible)))
4951 (if (eq buffer-invisibility-spec t)
4952 prop
4953 (or (memq prop buffer-invisibility-spec)
4954 (assq prop buffer-invisibility-spec)))))
4955 (goto-char
4956 (if (get-text-property (1- (point)) 'invisible)
4957 (or (previous-single-property-change (point) 'invisible)
4958 (point-min))
4959 (previous-overlay-change (point)))))
4960 (unless (bolp)
4961 (goto-char opoint)))))
4962 ((beginning-of-buffer end-of-buffer)
4963 nil)))
4964
4965 (defun end-of-visible-line ()
4966 "Move to end of current visible line."
4967 (end-of-line)
4968 ;; If the following character is currently invisible,
4969 ;; skip all characters with that same `invisible' property value,
4970 ;; then find the next newline.
4971 (while (and (not (eobp))
4972 (save-excursion
4973 (skip-chars-forward "^\n")
4974 (let ((prop
4975 (get-char-property (point) 'invisible)))
4976 (if (eq buffer-invisibility-spec t)
4977 prop
4978 (or (memq prop buffer-invisibility-spec)
4979 (assq prop buffer-invisibility-spec))))))
4980 (skip-chars-forward "^\n")
4981 (if (get-text-property (point) 'invisible)
4982 (goto-char (or (next-single-property-change (point) 'invisible)
4983 (point-max)))
4984 (goto-char (next-overlay-change (point))))
4985 (end-of-line)))
4986 \f
4987 (defun insert-buffer (buffer)
4988 "Insert after point the contents of BUFFER.
4989 Puts mark after the inserted text.
4990 BUFFER may be a buffer or a buffer name."
4991 (declare (interactive-only insert-buffer-substring))
4992 (interactive
4993 (list
4994 (progn
4995 (barf-if-buffer-read-only)
4996 (read-buffer "Insert buffer: "
4997 (if (eq (selected-window) (next-window))
4998 (other-buffer (current-buffer))
4999 (window-buffer (next-window)))
5000 t))))
5001 (push-mark
5002 (save-excursion
5003 (insert-buffer-substring (get-buffer buffer))
5004 (point)))
5005 nil)
5006
5007 (defun append-to-buffer (buffer start end)
5008 "Append to specified buffer the text of the region.
5009 It is inserted into that buffer before its point.
5010
5011 When calling from a program, give three arguments:
5012 BUFFER (or buffer name), START and END.
5013 START and END specify the portion of the current buffer to be copied."
5014 (interactive
5015 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5016 (region-beginning) (region-end)))
5017 (let* ((oldbuf (current-buffer))
5018 (append-to (get-buffer-create buffer))
5019 (windows (get-buffer-window-list append-to t t))
5020 point)
5021 (save-excursion
5022 (with-current-buffer append-to
5023 (setq point (point))
5024 (barf-if-buffer-read-only)
5025 (insert-buffer-substring oldbuf start end)
5026 (dolist (window windows)
5027 (when (= (window-point window) point)
5028 (set-window-point window (point))))))))
5029
5030 (defun prepend-to-buffer (buffer start end)
5031 "Prepend to specified buffer the text of the region.
5032 It is inserted into that buffer after its point.
5033
5034 When calling from a program, give three arguments:
5035 BUFFER (or buffer name), START and END.
5036 START and END specify the portion of the current buffer to be copied."
5037 (interactive "BPrepend to buffer: \nr")
5038 (let ((oldbuf (current-buffer)))
5039 (with-current-buffer (get-buffer-create buffer)
5040 (barf-if-buffer-read-only)
5041 (save-excursion
5042 (insert-buffer-substring oldbuf start end)))))
5043
5044 (defun copy-to-buffer (buffer start end)
5045 "Copy to specified buffer the text of the region.
5046 It is inserted into that buffer, replacing existing text there.
5047
5048 When calling from a program, give three arguments:
5049 BUFFER (or buffer name), START and END.
5050 START and END specify the portion of the current buffer to be copied."
5051 (interactive "BCopy to buffer: \nr")
5052 (let ((oldbuf (current-buffer)))
5053 (with-current-buffer (get-buffer-create buffer)
5054 (barf-if-buffer-read-only)
5055 (erase-buffer)
5056 (save-excursion
5057 (insert-buffer-substring oldbuf start end)))))
5058 \f
5059 (define-error 'mark-inactive (purecopy "The mark is not active now"))
5060
5061 (defvar activate-mark-hook nil
5062 "Hook run when the mark becomes active.
5063 It is also run at the end of a command, if the mark is active and
5064 it is possible that the region may have changed.")
5065
5066 (defvar deactivate-mark-hook nil
5067 "Hook run when the mark becomes inactive.")
5068
5069 (defun mark (&optional force)
5070 "Return this buffer's mark value as integer, or nil if never set.
5071
5072 In Transient Mark mode, this function signals an error if
5073 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
5074 or the argument FORCE is non-nil, it disregards whether the mark
5075 is active, and returns an integer or nil in the usual way.
5076
5077 If you are using this in an editing command, you are most likely making
5078 a mistake; see the documentation of `set-mark'."
5079 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
5080 (marker-position (mark-marker))
5081 (signal 'mark-inactive nil)))
5082
5083 ;; Behind display-selections-p.
5084
5085 (defun deactivate-mark (&optional force)
5086 "Deactivate the mark.
5087 If Transient Mark mode is disabled, this function normally does
5088 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
5089
5090 Deactivating the mark sets `mark-active' to nil, updates the
5091 primary selection according to `select-active-regions', and runs
5092 `deactivate-mark-hook'.
5093
5094 If Transient Mark mode was temporarily enabled, reset the value
5095 of the variable `transient-mark-mode'; if this causes Transient
5096 Mark mode to be disabled, don't change `mark-active' to nil or
5097 run `deactivate-mark-hook'."
5098 (when (or (region-active-p) force)
5099 (when (and (if (eq select-active-regions 'only)
5100 (eq (car-safe transient-mark-mode) 'only)
5101 select-active-regions)
5102 (region-active-p)
5103 (display-selections-p))
5104 ;; The var `saved-region-selection', if non-nil, is the text in
5105 ;; the region prior to the last command modifying the buffer.
5106 ;; Set the selection to that, or to the current region.
5107 (cond (saved-region-selection
5108 (if (gui-backend-selection-owner-p 'PRIMARY)
5109 (gui-set-selection 'PRIMARY saved-region-selection))
5110 (setq saved-region-selection nil))
5111 ;; If another program has acquired the selection, region
5112 ;; deactivation should not clobber it (Bug#11772).
5113 ((and (/= (region-beginning) (region-end))
5114 (or (gui-backend-selection-owner-p 'PRIMARY)
5115 (null (gui-backend-selection-exists-p 'PRIMARY))))
5116 (gui-set-selection 'PRIMARY
5117 (funcall region-extract-function nil)))))
5118 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
5119 (cond
5120 ((eq (car-safe transient-mark-mode) 'only)
5121 (setq transient-mark-mode (cdr transient-mark-mode))
5122 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5123 (kill-local-variable 'transient-mark-mode)))
5124 ((eq transient-mark-mode 'lambda)
5125 (kill-local-variable 'transient-mark-mode)))
5126 (setq mark-active nil)
5127 (run-hooks 'deactivate-mark-hook)
5128 (redisplay--update-region-highlight (selected-window))))
5129
5130 (defun activate-mark (&optional no-tmm)
5131 "Activate the mark.
5132 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
5133 (when (mark t)
5134 (unless (region-active-p)
5135 (force-mode-line-update) ;Refresh toolbar (bug#16382).
5136 (setq mark-active t)
5137 (unless (or transient-mark-mode no-tmm)
5138 (setq-local transient-mark-mode 'lambda))
5139 (run-hooks 'activate-mark-hook))))
5140
5141 (defun set-mark (pos)
5142 "Set this buffer's mark to POS. Don't use this function!
5143 That is to say, don't use this function unless you want
5144 the user to see that the mark has moved, and you want the previous
5145 mark position to be lost.
5146
5147 Normally, when a new mark is set, the old one should go on the stack.
5148 This is why most applications should use `push-mark', not `set-mark'.
5149
5150 Novice Emacs Lisp programmers often try to use the mark for the wrong
5151 purposes. The mark saves a location for the user's convenience.
5152 Most editing commands should not alter the mark.
5153 To remember a location for internal use in the Lisp program,
5154 store it in a Lisp variable. Example:
5155
5156 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
5157 (if pos
5158 (progn
5159 (set-marker (mark-marker) pos (current-buffer))
5160 (activate-mark 'no-tmm))
5161 ;; Normally we never clear mark-active except in Transient Mark mode.
5162 ;; But when we actually clear out the mark value too, we must
5163 ;; clear mark-active in any mode.
5164 (deactivate-mark t)
5165 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
5166 ;; it should never be nil if the mark is nil.
5167 (setq mark-active nil)
5168 (set-marker (mark-marker) nil)))
5169
5170 (defun save-mark-and-excursion--save ()
5171 (cons
5172 (let ((mark (mark-marker)))
5173 (and (marker-position mark) (copy-marker mark)))
5174 mark-active))
5175
5176 (defun save-mark-and-excursion--restore (saved-mark-info)
5177 (let ((saved-mark (car saved-mark-info))
5178 (omark (marker-position (mark-marker)))
5179 (nmark nil)
5180 (saved-mark-active (cdr saved-mark-info)))
5181 ;; Mark marker
5182 (if (null saved-mark)
5183 (set-marker (mark-marker) nil)
5184 (setf nmark (marker-position saved-mark))
5185 (set-marker (mark-marker) nmark)
5186 (set-marker saved-mark nil))
5187 ;; Mark active
5188 (let ((cur-mark-active mark-active))
5189 (setq mark-active saved-mark-active)
5190 ;; If mark is active now, and either was not active or was at a
5191 ;; different place, run the activate hook.
5192 (if saved-mark-active
5193 (when (or (not cur-mark-active)
5194 (not (eq omark nmark)))
5195 (run-hooks 'activate-mark-hook))
5196 ;; If mark has ceased to be active, run deactivate hook.
5197 (when cur-mark-active
5198 (run-hooks 'deactivate-mark-hook))))))
5199
5200 (defmacro save-mark-and-excursion (&rest body)
5201 "Like `save-excursion', but also save and restore the mark state.
5202 This macro does what `save-excursion' did before Emacs 25.1."
5203 (let ((saved-marker-sym (make-symbol "saved-marker")))
5204 `(let ((,saved-marker-sym (save-mark-and-excursion--save)))
5205 (unwind-protect
5206 (save-excursion ,@body)
5207 (save-mark-and-excursion--restore ,saved-marker-sym)))))
5208
5209 (defcustom use-empty-active-region nil
5210 "Whether \"region-aware\" commands should act on empty regions.
5211 If nil, region-aware commands treat empty regions as inactive.
5212 If non-nil, region-aware commands treat the region as active as
5213 long as the mark is active, even if the region is empty.
5214
5215 Region-aware commands are those that act on the region if it is
5216 active and Transient Mark mode is enabled, and on the text near
5217 point otherwise."
5218 :type 'boolean
5219 :version "23.1"
5220 :group 'editing-basics)
5221
5222 (defun use-region-p ()
5223 "Return t if the region is active and it is appropriate to act on it.
5224 This is used by commands that act specially on the region under
5225 Transient Mark mode.
5226
5227 The return value is t if Transient Mark mode is enabled and the
5228 mark is active; furthermore, if `use-empty-active-region' is nil,
5229 the region must not be empty. Otherwise, the return value is nil.
5230
5231 For some commands, it may be appropriate to ignore the value of
5232 `use-empty-active-region'; in that case, use `region-active-p'."
5233 (and (region-active-p)
5234 (or use-empty-active-region (> (region-end) (region-beginning)))))
5235
5236 (defun region-active-p ()
5237 "Return non-nil if Transient Mark mode is enabled and the mark is active.
5238
5239 Some commands act specially on the region when Transient Mark
5240 mode is enabled. Usually, such commands should use
5241 `use-region-p' instead of this function, because `use-region-p'
5242 also checks the value of `use-empty-active-region'."
5243 (and transient-mark-mode mark-active
5244 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
5245 ;; without the mark being set (e.g. bug#17324). We really should fix
5246 ;; that problem, but in the mean time, let's make sure we don't say the
5247 ;; region is active when there's no mark.
5248 (progn (cl-assert (mark)) t)))
5249
5250 (defun region-noncontiguous-p ()
5251 "Return non-nil if the region contains several pieces.
5252 An example is a rectangular region handled as a list of
5253 separate contiguous regions for each line."
5254 (> (length (funcall region-extract-function 'bounds)) 1))
5255
5256 (defvar redisplay-unhighlight-region-function
5257 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
5258
5259 (defvar redisplay-highlight-region-function
5260 (lambda (start end window rol)
5261 (if (not (overlayp rol))
5262 (let ((nrol (make-overlay start end)))
5263 (funcall redisplay-unhighlight-region-function rol)
5264 (overlay-put nrol 'window window)
5265 (overlay-put nrol 'face 'region)
5266 ;; Normal priority so that a large region doesn't hide all the
5267 ;; overlays within it, but high secondary priority so that if it
5268 ;; ends/starts in the middle of a small overlay, that small overlay
5269 ;; won't hide the region's boundaries.
5270 (overlay-put nrol 'priority '(nil . 100))
5271 nrol)
5272 (unless (and (eq (overlay-buffer rol) (current-buffer))
5273 (eq (overlay-start rol) start)
5274 (eq (overlay-end rol) end))
5275 (move-overlay rol start end (current-buffer)))
5276 rol)))
5277
5278 (defun redisplay--update-region-highlight (window)
5279 (let ((rol (window-parameter window 'internal-region-overlay)))
5280 (if (not (and (region-active-p)
5281 (or highlight-nonselected-windows
5282 (eq window (selected-window))
5283 (and (window-minibuffer-p)
5284 (eq window (minibuffer-selected-window))))))
5285 (funcall redisplay-unhighlight-region-function rol)
5286 (let* ((pt (window-point window))
5287 (mark (mark))
5288 (start (min pt mark))
5289 (end (max pt mark))
5290 (new
5291 (funcall redisplay-highlight-region-function
5292 start end window rol)))
5293 (unless (equal new rol)
5294 (set-window-parameter window 'internal-region-overlay
5295 new))))))
5296
5297 (defvar pre-redisplay-functions (list #'redisplay--update-region-highlight)
5298 "Hook run just before redisplay.
5299 It is called in each window that is to be redisplayed. It takes one argument,
5300 which is the window that will be redisplayed. When run, the `current-buffer'
5301 is set to the buffer displayed in that window.")
5302
5303 (defun redisplay--pre-redisplay-functions (windows)
5304 (with-demoted-errors "redisplay--pre-redisplay-functions: %S"
5305 (if (null windows)
5306 (with-current-buffer (window-buffer (selected-window))
5307 (run-hook-with-args 'pre-redisplay-functions (selected-window)))
5308 (dolist (win (if (listp windows) windows (window-list-1 nil nil t)))
5309 (with-current-buffer (window-buffer win)
5310 (run-hook-with-args 'pre-redisplay-functions win))))))
5311
5312 (add-function :before pre-redisplay-function
5313 #'redisplay--pre-redisplay-functions)
5314
5315
5316 (defvar-local mark-ring nil
5317 "The list of former marks of the current buffer, most recent first.")
5318 (put 'mark-ring 'permanent-local t)
5319
5320 (defcustom mark-ring-max 16
5321 "Maximum size of mark ring. Start discarding off end if gets this big."
5322 :type 'integer
5323 :group 'editing-basics)
5324
5325 (defvar global-mark-ring nil
5326 "The list of saved global marks, most recent first.")
5327
5328 (defcustom global-mark-ring-max 16
5329 "Maximum size of global mark ring. \
5330 Start discarding off end if gets this big."
5331 :type 'integer
5332 :group 'editing-basics)
5333
5334 (defun pop-to-mark-command ()
5335 "Jump to mark, and pop a new position for mark off the ring.
5336 \(Does not affect global mark ring)."
5337 (interactive)
5338 (if (null (mark t))
5339 (user-error "No mark set in this buffer")
5340 (if (= (point) (mark t))
5341 (message "Mark popped"))
5342 (goto-char (mark t))
5343 (pop-mark)))
5344
5345 (defun push-mark-command (arg &optional nomsg)
5346 "Set mark at where point is.
5347 If no prefix ARG and mark is already set there, just activate it.
5348 Display `Mark set' unless the optional second arg NOMSG is non-nil."
5349 (interactive "P")
5350 (let ((mark (mark t)))
5351 (if (or arg (null mark) (/= mark (point)))
5352 (push-mark nil nomsg t)
5353 (activate-mark 'no-tmm)
5354 (unless nomsg
5355 (message "Mark activated")))))
5356
5357 (defcustom set-mark-command-repeat-pop nil
5358 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
5359 That means that C-u \\[set-mark-command] \\[set-mark-command]
5360 will pop the mark twice, and
5361 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
5362 will pop the mark three times.
5363
5364 A value of nil means \\[set-mark-command]'s behavior does not change
5365 after C-u \\[set-mark-command]."
5366 :type 'boolean
5367 :group 'editing-basics)
5368
5369 (defun set-mark-command (arg)
5370 "Set the mark where point is, or jump to the mark.
5371 Setting the mark also alters the region, which is the text
5372 between point and mark; this is the closest equivalent in
5373 Emacs to what some editors call the \"selection\".
5374
5375 With no prefix argument, set the mark at point, and push the
5376 old mark position on local mark ring. Also push the old mark on
5377 global mark ring, if the previous mark was set in another buffer.
5378
5379 When Transient Mark Mode is off, immediately repeating this
5380 command activates `transient-mark-mode' temporarily.
5381
5382 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
5383 jump to the mark, and set the mark from
5384 position popped off the local mark ring (this does not affect the global
5385 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
5386 mark ring (see `pop-global-mark').
5387
5388 If `set-mark-command-repeat-pop' is non-nil, repeating
5389 the \\[set-mark-command] command with no prefix argument pops the next position
5390 off the local (or global) mark ring and jumps there.
5391
5392 With \\[universal-argument] \\[universal-argument] as prefix
5393 argument, unconditionally set mark where point is, even if
5394 `set-mark-command-repeat-pop' is non-nil.
5395
5396 Novice Emacs Lisp programmers often try to use the mark for the wrong
5397 purposes. See the documentation of `set-mark' for more information."
5398 (interactive "P")
5399 (cond ((eq transient-mark-mode 'lambda)
5400 (kill-local-variable 'transient-mark-mode))
5401 ((eq (car-safe transient-mark-mode) 'only)
5402 (deactivate-mark)))
5403 (cond
5404 ((and (consp arg) (> (prefix-numeric-value arg) 4))
5405 (push-mark-command nil))
5406 ((not (eq this-command 'set-mark-command))
5407 (if arg
5408 (pop-to-mark-command)
5409 (push-mark-command t)))
5410 ((and set-mark-command-repeat-pop
5411 (eq last-command 'pop-global-mark)
5412 (not arg))
5413 (setq this-command 'pop-global-mark)
5414 (pop-global-mark))
5415 ((or (and set-mark-command-repeat-pop
5416 (eq last-command 'pop-to-mark-command))
5417 arg)
5418 (setq this-command 'pop-to-mark-command)
5419 (pop-to-mark-command))
5420 ((eq last-command 'set-mark-command)
5421 (if (region-active-p)
5422 (progn
5423 (deactivate-mark)
5424 (message "Mark deactivated"))
5425 (activate-mark)
5426 (message "Mark activated")))
5427 (t
5428 (push-mark-command nil))))
5429
5430 (defun push-mark (&optional location nomsg activate)
5431 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
5432 If the last global mark pushed was not in the current buffer,
5433 also push LOCATION on the global mark ring.
5434 Display `Mark set' unless the optional second arg NOMSG is non-nil.
5435
5436 Novice Emacs Lisp programmers often try to use the mark for the wrong
5437 purposes. See the documentation of `set-mark' for more information.
5438
5439 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
5440 (unless (null (mark t))
5441 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
5442 (when (> (length mark-ring) mark-ring-max)
5443 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
5444 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
5445 (set-marker (mark-marker) (or location (point)) (current-buffer))
5446 ;; Now push the mark on the global mark ring.
5447 (if (and global-mark-ring
5448 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
5449 ;; The last global mark pushed was in this same buffer.
5450 ;; Don't push another one.
5451 nil
5452 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
5453 (when (> (length global-mark-ring) global-mark-ring-max)
5454 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
5455 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
5456 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
5457 (message "Mark set"))
5458 (if (or activate (not transient-mark-mode))
5459 (set-mark (mark t)))
5460 nil)
5461
5462 (defun pop-mark ()
5463 "Pop off mark ring into the buffer's actual mark.
5464 Does not set point. Does nothing if mark ring is empty."
5465 (when mark-ring
5466 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
5467 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
5468 (move-marker (car mark-ring) nil)
5469 (if (null (mark t)) (ding))
5470 (setq mark-ring (cdr mark-ring)))
5471 (deactivate-mark))
5472
5473 (define-obsolete-function-alias
5474 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
5475 (defun exchange-point-and-mark (&optional arg)
5476 "Put the mark where point is now, and point where the mark is now.
5477 This command works even when the mark is not active,
5478 and it reactivates the mark.
5479
5480 If Transient Mark mode is on, a prefix ARG deactivates the mark
5481 if it is active, and otherwise avoids reactivating it. If
5482 Transient Mark mode is off, a prefix ARG enables Transient Mark
5483 mode temporarily."
5484 (interactive "P")
5485 (let ((omark (mark t))
5486 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
5487 (if (null omark)
5488 (user-error "No mark set in this buffer"))
5489 (set-mark (point))
5490 (goto-char omark)
5491 (cond (temp-highlight
5492 (setq-local transient-mark-mode (cons 'only transient-mark-mode)))
5493 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
5494 (not (or arg (region-active-p))))
5495 (deactivate-mark))
5496 (t (activate-mark)))
5497 nil))
5498
5499 (defcustom shift-select-mode t
5500 "When non-nil, shifted motion keys activate the mark momentarily.
5501
5502 While the mark is activated in this way, any shift-translated point
5503 motion key extends the region, and if Transient Mark mode was off, it
5504 is temporarily turned on. Furthermore, the mark will be deactivated
5505 by any subsequent point motion key that was not shift-translated, or
5506 by any action that normally deactivates the mark in Transient Mark mode.
5507
5508 See `this-command-keys-shift-translated' for the meaning of
5509 shift-translation."
5510 :type 'boolean
5511 :group 'editing-basics)
5512
5513 (defun handle-shift-selection ()
5514 "Activate/deactivate mark depending on invocation thru shift translation.
5515 This function is called by `call-interactively' when a command
5516 with a `^' character in its `interactive' spec is invoked, before
5517 running the command itself.
5518
5519 If `shift-select-mode' is enabled and the command was invoked
5520 through shift translation, set the mark and activate the region
5521 temporarily, unless it was already set in this way. See
5522 `this-command-keys-shift-translated' for the meaning of shift
5523 translation.
5524
5525 Otherwise, if the region has been activated temporarily,
5526 deactivate it, and restore the variable `transient-mark-mode' to
5527 its earlier value."
5528 (cond ((and shift-select-mode this-command-keys-shift-translated)
5529 (unless (and mark-active
5530 (eq (car-safe transient-mark-mode) 'only))
5531 (setq-local transient-mark-mode
5532 (cons 'only
5533 (unless (eq transient-mark-mode 'lambda)
5534 transient-mark-mode)))
5535 (push-mark nil nil t)))
5536 ((eq (car-safe transient-mark-mode) 'only)
5537 (setq transient-mark-mode (cdr transient-mark-mode))
5538 (if (eq transient-mark-mode (default-value 'transient-mark-mode))
5539 (kill-local-variable 'transient-mark-mode))
5540 (deactivate-mark))))
5541
5542 (define-minor-mode transient-mark-mode
5543 "Toggle Transient Mark mode.
5544 With a prefix argument ARG, enable Transient Mark mode if ARG is
5545 positive, and disable it otherwise. If called from Lisp, enable
5546 Transient Mark mode if ARG is omitted or nil.
5547
5548 Transient Mark mode is a global minor mode. When enabled, the
5549 region is highlighted with the `region' face whenever the mark
5550 is active. The mark is \"deactivated\" by changing the buffer,
5551 and after certain other operations that set the mark but whose
5552 main purpose is something else--for example, incremental search,
5553 \\[beginning-of-buffer], and \\[end-of-buffer].
5554
5555 You can also deactivate the mark by typing \\[keyboard-quit] or
5556 \\[keyboard-escape-quit].
5557
5558 Many commands change their behavior when Transient Mark mode is
5559 in effect and the mark is active, by acting on the region instead
5560 of their usual default part of the buffer's text. Examples of
5561 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
5562 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
5563 To see the documentation of commands which are sensitive to the
5564 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
5565 or \"mark.*active\" at the prompt."
5566 :global t
5567 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
5568 :variable (default-value 'transient-mark-mode))
5569
5570 (defvar widen-automatically t
5571 "Non-nil means it is ok for commands to call `widen' when they want to.
5572 Some commands will do this in order to go to positions outside
5573 the current accessible part of the buffer.
5574
5575 If `widen-automatically' is nil, these commands will do something else
5576 as a fallback, and won't change the buffer bounds.")
5577
5578 (defvar non-essential nil
5579 "Whether the currently executing code is performing an essential task.
5580 This variable should be non-nil only when running code which should not
5581 disturb the user. E.g. it can be used to prevent Tramp from prompting the
5582 user for a password when we are simply scanning a set of files in the
5583 background or displaying possible completions before the user even asked
5584 for it.")
5585
5586 (defun pop-global-mark ()
5587 "Pop off global mark ring and jump to the top location."
5588 (interactive)
5589 ;; Pop entries which refer to non-existent buffers.
5590 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
5591 (setq global-mark-ring (cdr global-mark-ring)))
5592 (or global-mark-ring
5593 (error "No global mark set"))
5594 (let* ((marker (car global-mark-ring))
5595 (buffer (marker-buffer marker))
5596 (position (marker-position marker)))
5597 (setq global-mark-ring (nconc (cdr global-mark-ring)
5598 (list (car global-mark-ring))))
5599 (set-buffer buffer)
5600 (or (and (>= position (point-min))
5601 (<= position (point-max)))
5602 (if widen-automatically
5603 (widen)
5604 (error "Global mark position is outside accessible part of buffer")))
5605 (goto-char position)
5606 (switch-to-buffer buffer)))
5607 \f
5608 (defcustom next-line-add-newlines nil
5609 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
5610 :type 'boolean
5611 :version "21.1"
5612 :group 'editing-basics)
5613
5614 (defun next-line (&optional arg try-vscroll)
5615 "Move cursor vertically down ARG lines.
5616 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5617 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5618 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5619 function will not vscroll.
5620
5621 ARG defaults to 1.
5622
5623 If there is no character in the target line exactly under the current column,
5624 the cursor is positioned after the character in that line which spans this
5625 column, or at the end of the line if it is not long enough.
5626 If there is no line in the buffer after this one, behavior depends on the
5627 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
5628 to create a line, and moves the cursor to that line. Otherwise it moves the
5629 cursor to the end of the buffer.
5630
5631 If the variable `line-move-visual' is non-nil, this command moves
5632 by display lines. Otherwise, it moves by buffer lines, without
5633 taking variable-width characters or continued lines into account.
5634
5635 The command \\[set-goal-column] can be used to create
5636 a semipermanent goal column for this command.
5637 Then instead of trying to move exactly vertically (or as close as possible),
5638 this command moves to the specified goal column (or as close as possible).
5639 The goal column is stored in the variable `goal-column', which is nil
5640 when there is no goal column. Note that setting `goal-column'
5641 overrides `line-move-visual' and causes this command to move by buffer
5642 lines rather than by display lines."
5643 (declare (interactive-only forward-line))
5644 (interactive "^p\np")
5645 (or arg (setq arg 1))
5646 (if (and next-line-add-newlines (= arg 1))
5647 (if (save-excursion (end-of-line) (eobp))
5648 ;; When adding a newline, don't expand an abbrev.
5649 (let ((abbrev-mode nil))
5650 (end-of-line)
5651 (insert (if use-hard-newlines hard-newline "\n")))
5652 (line-move arg nil nil try-vscroll))
5653 (if (called-interactively-p 'interactive)
5654 (condition-case err
5655 (line-move arg nil nil try-vscroll)
5656 ((beginning-of-buffer end-of-buffer)
5657 (signal (car err) (cdr err))))
5658 (line-move arg nil nil try-vscroll)))
5659 nil)
5660
5661 (defun previous-line (&optional arg try-vscroll)
5662 "Move cursor vertically up ARG lines.
5663 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
5664 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
5665 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
5666 function will not vscroll.
5667
5668 ARG defaults to 1.
5669
5670 If there is no character in the target line exactly over the current column,
5671 the cursor is positioned after the character in that line which spans this
5672 column, or at the end of the line if it is not long enough.
5673
5674 If the variable `line-move-visual' is non-nil, this command moves
5675 by display lines. Otherwise, it moves by buffer lines, without
5676 taking variable-width characters or continued lines into account.
5677
5678 The command \\[set-goal-column] can be used to create
5679 a semipermanent goal column for this command.
5680 Then instead of trying to move exactly vertically (or as close as possible),
5681 this command moves to the specified goal column (or as close as possible).
5682 The goal column is stored in the variable `goal-column', which is nil
5683 when there is no goal column. Note that setting `goal-column'
5684 overrides `line-move-visual' and causes this command to move by buffer
5685 lines rather than by display lines."
5686 (declare (interactive-only
5687 "use `forward-line' with negative argument instead."))
5688 (interactive "^p\np")
5689 (or arg (setq arg 1))
5690 (if (called-interactively-p 'interactive)
5691 (condition-case err
5692 (line-move (- arg) nil nil try-vscroll)
5693 ((beginning-of-buffer end-of-buffer)
5694 (signal (car err) (cdr err))))
5695 (line-move (- arg) nil nil try-vscroll))
5696 nil)
5697
5698 (defcustom track-eol nil
5699 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
5700 This means moving to the end of each line moved onto.
5701 The beginning of a blank line does not count as the end of a line.
5702 This has no effect when the variable `line-move-visual' is non-nil."
5703 :type 'boolean
5704 :group 'editing-basics)
5705
5706 (defcustom goal-column nil
5707 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
5708 A non-nil setting overrides the variable `line-move-visual', which see."
5709 :type '(choice integer
5710 (const :tag "None" nil))
5711 :group 'editing-basics)
5712 (make-variable-buffer-local 'goal-column)
5713
5714 (defvar temporary-goal-column 0
5715 "Current goal column for vertical motion.
5716 It is the column where point was at the start of the current run
5717 of vertical motion commands.
5718
5719 When moving by visual lines via the function `line-move-visual', it is a cons
5720 cell (COL . HSCROLL), where COL is the x-position, in pixels,
5721 divided by the default column width, and HSCROLL is the number of
5722 columns by which window is scrolled from left margin.
5723
5724 When the `track-eol' feature is doing its job, the value is
5725 `most-positive-fixnum'.")
5726
5727 (defcustom line-move-ignore-invisible t
5728 "Non-nil means commands that move by lines ignore invisible newlines.
5729 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5730 as if newlines that are invisible didn't exist, and count
5731 only visible newlines. Thus, moving across across 2 newlines
5732 one of which is invisible will be counted as a one-line move.
5733 Also, a non-nil value causes invisible text to be ignored when
5734 counting columns for the purposes of keeping point in the same
5735 column by \\[next-line] and \\[previous-line].
5736
5737 Outline mode sets this."
5738 :type 'boolean
5739 :group 'editing-basics)
5740
5741 (defcustom line-move-visual t
5742 "When non-nil, `line-move' moves point by visual lines.
5743 This movement is based on where the cursor is displayed on the
5744 screen, instead of relying on buffer contents alone. It takes
5745 into account variable-width characters and line continuation.
5746 If nil, `line-move' moves point by logical lines.
5747 A non-nil setting of `goal-column' overrides the value of this variable
5748 and forces movement by logical lines.
5749 A window that is horizontally scrolled also forces movement by logical
5750 lines."
5751 :type 'boolean
5752 :group 'editing-basics
5753 :version "23.1")
5754
5755 ;; Only used if display-graphic-p.
5756 (declare-function font-info "font.c" (name &optional frame))
5757
5758 (defun default-font-height ()
5759 "Return the height in pixels of the current buffer's default face font.
5760
5761 If the default font is remapped (see `face-remapping-alist'), the
5762 function returns the height of the remapped face."
5763 (let ((default-font (face-font 'default)))
5764 (cond
5765 ((and (display-multi-font-p)
5766 ;; Avoid calling font-info if the frame's default font was
5767 ;; not changed since the frame was created. That's because
5768 ;; font-info is expensive for some fonts, see bug #14838.
5769 (not (string= (frame-parameter nil 'font) default-font)))
5770 (aref (font-info default-font) 3))
5771 (t (frame-char-height)))))
5772
5773 (defun default-font-width ()
5774 "Return the width in pixels of the current buffer's default face font.
5775
5776 If the default font is remapped (see `face-remapping-alist'), the
5777 function returns the width of the remapped face."
5778 (let ((default-font (face-font 'default)))
5779 (cond
5780 ((and (display-multi-font-p)
5781 ;; Avoid calling font-info if the frame's default font was
5782 ;; not changed since the frame was created. That's because
5783 ;; font-info is expensive for some fonts, see bug #14838.
5784 (not (string= (frame-parameter nil 'font) default-font)))
5785 (let* ((info (font-info (face-font 'default)))
5786 (width (aref info 11)))
5787 (if (> width 0)
5788 width
5789 (aref info 10))))
5790 (t (frame-char-width)))))
5791
5792 (defun default-line-height ()
5793 "Return the pixel height of current buffer's default-face text line.
5794
5795 The value includes `line-spacing', if any, defined for the buffer
5796 or the frame."
5797 (let ((dfh (default-font-height))
5798 (lsp (if (display-graphic-p)
5799 (or line-spacing
5800 (default-value 'line-spacing)
5801 (frame-parameter nil 'line-spacing)
5802 0)
5803 0)))
5804 (if (floatp lsp)
5805 (setq lsp (truncate (* (frame-char-height) lsp))))
5806 (+ dfh lsp)))
5807
5808 (defun window-screen-lines ()
5809 "Return the number of screen lines in the text area of the selected window.
5810
5811 This is different from `window-text-height' in that this function counts
5812 lines in units of the height of the font used by the default face displayed
5813 in the window, not in units of the frame's default font, and also accounts
5814 for `line-spacing', if any, defined for the window's buffer or frame.
5815
5816 The value is a floating-point number."
5817 (let ((edges (window-inside-pixel-edges))
5818 (dlh (default-line-height)))
5819 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5820
5821 ;; Returns non-nil if partial move was done.
5822 (defun line-move-partial (arg noerror to-end)
5823 (if (< arg 0)
5824 ;; Move backward (up).
5825 ;; If already vscrolled, reduce vscroll
5826 (let ((vs (window-vscroll nil t))
5827 (dlh (default-line-height)))
5828 (when (> vs dlh)
5829 (set-window-vscroll nil (- vs dlh) t)))
5830
5831 ;; Move forward (down).
5832 (let* ((lh (window-line-height -1))
5833 (rowh (car lh))
5834 (vpos (nth 1 lh))
5835 (ypos (nth 2 lh))
5836 (rbot (nth 3 lh))
5837 (this-lh (window-line-height))
5838 (this-height (car this-lh))
5839 (this-ypos (nth 2 this-lh))
5840 (dlh (default-line-height))
5841 (wslines (window-screen-lines))
5842 (edges (window-inside-pixel-edges))
5843 (winh (- (nth 3 edges) (nth 1 edges) 1))
5844 py vs last-line)
5845 (if (> (mod wslines 1.0) 0.0)
5846 (setq wslines (round (+ wslines 0.5))))
5847 (when (or (null lh)
5848 (>= rbot dlh)
5849 (<= ypos (- dlh))
5850 (null this-lh)
5851 (<= this-ypos (- dlh)))
5852 (unless lh
5853 (let ((wend (pos-visible-in-window-p t nil t)))
5854 (setq rbot (nth 3 wend)
5855 rowh (nth 4 wend)
5856 vpos (nth 5 wend))))
5857 (unless this-lh
5858 (let ((wstart (pos-visible-in-window-p nil nil t)))
5859 (setq this-ypos (nth 2 wstart)
5860 this-height (nth 4 wstart))))
5861 (setq py
5862 (or (nth 1 this-lh)
5863 (let ((ppos (posn-at-point))
5864 col-row)
5865 (setq col-row (posn-actual-col-row ppos))
5866 (if col-row
5867 (- (cdr col-row) (window-vscroll))
5868 (cdr (posn-col-row ppos))))))
5869 ;; VPOS > 0 means the last line is only partially visible.
5870 ;; But if the part that is visible is at least as tall as the
5871 ;; default font, that means the line is actually fully
5872 ;; readable, and something like line-spacing is hidden. So in
5873 ;; that case we accept the last line in the window as still
5874 ;; visible, and consider the margin as starting one line
5875 ;; later.
5876 (if (and vpos (> vpos 0))
5877 (if (and rowh
5878 (>= rowh (default-font-height))
5879 (< rowh dlh))
5880 (setq last-line (min (- wslines scroll-margin) vpos))
5881 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
5882 (cond
5883 ;; If last line of window is fully visible, and vscrolling
5884 ;; more would make this line invisible, move forward.
5885 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
5886 (null this-height)
5887 (<= this-height dlh))
5888 (or (null rbot) (= rbot 0)))
5889 nil)
5890 ;; If cursor is not in the bottom scroll margin, and the
5891 ;; current line is is not too tall, move forward.
5892 ((and (or (null this-height) (<= this-height winh))
5893 vpos
5894 (> vpos 0)
5895 (< py last-line))
5896 nil)
5897 ;; When already vscrolled, we vscroll some more if we can,
5898 ;; or clear vscroll and move forward at end of tall image.
5899 ((> vs 0)
5900 (when (or (and rbot (> rbot 0))
5901 (and this-height (> this-height dlh)))
5902 (set-window-vscroll nil (+ vs dlh) t)))
5903 ;; If cursor just entered the bottom scroll margin, move forward,
5904 ;; but also optionally vscroll one line so redisplay won't recenter.
5905 ((and vpos
5906 (> vpos 0)
5907 (= py last-line))
5908 ;; Don't vscroll if the partially-visible line at window
5909 ;; bottom is not too tall (a.k.a. "just one more text
5910 ;; line"): in that case, we do want redisplay to behave
5911 ;; normally, i.e. recenter or whatever.
5912 ;;
5913 ;; Note: ROWH + RBOT from the value returned by
5914 ;; pos-visible-in-window-p give the total height of the
5915 ;; partially-visible glyph row at the end of the window. As
5916 ;; we are dealing with floats, we disregard sub-pixel
5917 ;; discrepancies between that and DLH.
5918 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
5919 (set-window-vscroll nil dlh t))
5920 (line-move-1 arg noerror to-end)
5921 t)
5922 ;; If there are lines above the last line, scroll-up one line.
5923 ((and vpos (> vpos 0))
5924 (scroll-up 1)
5925 t)
5926 ;; Finally, start vscroll.
5927 (t
5928 (set-window-vscroll nil dlh t)))))))
5929
5930
5931 ;; This is like line-move-1 except that it also performs
5932 ;; vertical scrolling of tall images if appropriate.
5933 ;; That is not really a clean thing to do, since it mixes
5934 ;; scrolling with cursor motion. But so far we don't have
5935 ;; a cleaner solution to the problem of making C-n do something
5936 ;; useful given a tall image.
5937 (defun line-move (arg &optional noerror to-end try-vscroll)
5938 "Move forward ARG lines.
5939 If NOERROR, don't signal an error if we can't move ARG lines.
5940 TO-END is unused.
5941 TRY-VSCROLL controls whether to vscroll tall lines: if either
5942 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
5943 not vscroll."
5944 (if noninteractive
5945 (line-move-1 arg noerror to-end)
5946 (unless (and auto-window-vscroll try-vscroll
5947 ;; Only vscroll for single line moves
5948 (= (abs arg) 1)
5949 ;; Under scroll-conservatively, the display engine
5950 ;; does this better.
5951 (zerop scroll-conservatively)
5952 ;; But don't vscroll in a keyboard macro.
5953 (not defining-kbd-macro)
5954 (not executing-kbd-macro)
5955 (line-move-partial arg noerror to-end))
5956 (set-window-vscroll nil 0 t)
5957 (if (and line-move-visual
5958 ;; Display-based column are incompatible with goal-column.
5959 (not goal-column)
5960 ;; When the text in the window is scrolled to the left,
5961 ;; display-based motion doesn't make sense (because each
5962 ;; logical line occupies exactly one screen line).
5963 (not (> (window-hscroll) 0))
5964 ;; Likewise when the text _was_ scrolled to the left
5965 ;; when the current run of vertical motion commands
5966 ;; started.
5967 (not (and (memq last-command
5968 `(next-line previous-line ,this-command))
5969 auto-hscroll-mode
5970 (numberp temporary-goal-column)
5971 (>= temporary-goal-column
5972 (- (window-width) hscroll-margin)))))
5973 (prog1 (line-move-visual arg noerror)
5974 ;; If we moved into a tall line, set vscroll to make
5975 ;; scrolling through tall images more smooth.
5976 (let ((lh (line-pixel-height))
5977 (edges (window-inside-pixel-edges))
5978 (dlh (default-line-height))
5979 winh)
5980 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
5981 (if (and (< arg 0)
5982 (< (point) (window-start))
5983 (> lh winh))
5984 (set-window-vscroll
5985 nil
5986 (- lh dlh) t))))
5987 (line-move-1 arg noerror to-end)))))
5988
5989 ;; Display-based alternative to line-move-1.
5990 ;; Arg says how many lines to move. The value is t if we can move the
5991 ;; specified number of lines.
5992 (defun line-move-visual (arg &optional noerror)
5993 "Move ARG lines forward.
5994 If NOERROR, don't signal an error if we can't move that many lines."
5995 (let ((opoint (point))
5996 (hscroll (window-hscroll))
5997 target-hscroll)
5998 ;; Check if the previous command was a line-motion command, or if
5999 ;; we were called from some other command.
6000 (if (and (consp temporary-goal-column)
6001 (memq last-command `(next-line previous-line ,this-command)))
6002 ;; If so, there's no need to reset `temporary-goal-column',
6003 ;; but we may need to hscroll.
6004 (if (or (/= (cdr temporary-goal-column) hscroll)
6005 (> (cdr temporary-goal-column) 0))
6006 (setq target-hscroll (cdr temporary-goal-column)))
6007 ;; Otherwise, we should reset `temporary-goal-column'.
6008 (let ((posn (posn-at-point))
6009 x-pos)
6010 (cond
6011 ;; Handle the `overflow-newline-into-fringe' case:
6012 ((eq (nth 1 posn) 'right-fringe)
6013 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
6014 ((car (posn-x-y posn))
6015 (setq x-pos (car (posn-x-y posn)))
6016 ;; In R2L lines, the X pixel coordinate is measured from the
6017 ;; left edge of the window, but columns are still counted
6018 ;; from the logical-order beginning of the line, i.e. from
6019 ;; the right edge in this case. We need to adjust for that.
6020 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
6021 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
6022 (setq temporary-goal-column
6023 (cons (/ (float x-pos)
6024 (frame-char-width))
6025 hscroll))))))
6026 (if target-hscroll
6027 (set-window-hscroll (selected-window) target-hscroll))
6028 ;; vertical-motion can move more than it was asked to if it moves
6029 ;; across display strings with newlines. We don't want to ring
6030 ;; the bell and announce beginning/end of buffer in that case.
6031 (or (and (or (and (>= arg 0)
6032 (>= (vertical-motion
6033 (cons (or goal-column
6034 (if (consp temporary-goal-column)
6035 (car temporary-goal-column)
6036 temporary-goal-column))
6037 arg))
6038 arg))
6039 (and (< arg 0)
6040 (<= (vertical-motion
6041 (cons (or goal-column
6042 (if (consp temporary-goal-column)
6043 (car temporary-goal-column)
6044 temporary-goal-column))
6045 arg))
6046 arg)))
6047 (or (>= arg 0)
6048 (/= (point) opoint)
6049 ;; If the goal column lies on a display string,
6050 ;; `vertical-motion' advances the cursor to the end
6051 ;; of the string. For arg < 0, this can cause the
6052 ;; cursor to get stuck. (Bug#3020).
6053 (= (vertical-motion arg) arg)))
6054 (unless noerror
6055 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
6056 nil)))))
6057
6058 ;; This is the guts of next-line and previous-line.
6059 ;; Arg says how many lines to move.
6060 ;; The value is t if we can move the specified number of lines.
6061 (defun line-move-1 (arg &optional noerror _to-end)
6062 ;; Don't run any point-motion hooks, and disregard intangibility,
6063 ;; for intermediate positions.
6064 (let ((inhibit-point-motion-hooks t)
6065 (opoint (point))
6066 (orig-arg arg))
6067 (if (consp temporary-goal-column)
6068 (setq temporary-goal-column (+ (car temporary-goal-column)
6069 (cdr temporary-goal-column))))
6070 (unwind-protect
6071 (progn
6072 (if (not (memq last-command '(next-line previous-line)))
6073 (setq temporary-goal-column
6074 (if (and track-eol (eolp)
6075 ;; Don't count beg of empty line as end of line
6076 ;; unless we just did explicit end-of-line.
6077 (or (not (bolp)) (eq last-command 'move-end-of-line)))
6078 most-positive-fixnum
6079 (current-column))))
6080
6081 (if (not (or (integerp selective-display)
6082 line-move-ignore-invisible))
6083 ;; Use just newline characters.
6084 ;; Set ARG to 0 if we move as many lines as requested.
6085 (or (if (> arg 0)
6086 (progn (if (> arg 1) (forward-line (1- arg)))
6087 ;; This way of moving forward ARG lines
6088 ;; verifies that we have a newline after the last one.
6089 ;; It doesn't get confused by intangible text.
6090 (end-of-line)
6091 (if (zerop (forward-line 1))
6092 (setq arg 0)))
6093 (and (zerop (forward-line arg))
6094 (bolp)
6095 (setq arg 0)))
6096 (unless noerror
6097 (signal (if (< arg 0)
6098 'beginning-of-buffer
6099 'end-of-buffer)
6100 nil)))
6101 ;; Move by arg lines, but ignore invisible ones.
6102 (let (done)
6103 (while (and (> arg 0) (not done))
6104 ;; If the following character is currently invisible,
6105 ;; skip all characters with that same `invisible' property value.
6106 (while (and (not (eobp)) (invisible-p (point)))
6107 (goto-char (next-char-property-change (point))))
6108 ;; Move a line.
6109 ;; We don't use `end-of-line', since we want to escape
6110 ;; from field boundaries occurring exactly at point.
6111 (goto-char (constrain-to-field
6112 (let ((inhibit-field-text-motion t))
6113 (line-end-position))
6114 (point) t t
6115 'inhibit-line-move-field-capture))
6116 ;; If there's no invisibility here, move over the newline.
6117 (cond
6118 ((eobp)
6119 (if (not noerror)
6120 (signal 'end-of-buffer nil)
6121 (setq done t)))
6122 ((and (> arg 1) ;; Use vertical-motion for last move
6123 (not (integerp selective-display))
6124 (not (invisible-p (point))))
6125 ;; We avoid vertical-motion when possible
6126 ;; because that has to fontify.
6127 (forward-line 1))
6128 ;; Otherwise move a more sophisticated way.
6129 ((zerop (vertical-motion 1))
6130 (if (not noerror)
6131 (signal 'end-of-buffer nil)
6132 (setq done t))))
6133 (unless done
6134 (setq arg (1- arg))))
6135 ;; The logic of this is the same as the loop above,
6136 ;; it just goes in the other direction.
6137 (while (and (< arg 0) (not done))
6138 ;; For completely consistency with the forward-motion
6139 ;; case, we should call beginning-of-line here.
6140 ;; However, if point is inside a field and on a
6141 ;; continued line, the call to (vertical-motion -1)
6142 ;; below won't move us back far enough; then we return
6143 ;; to the same column in line-move-finish, and point
6144 ;; gets stuck -- cyd
6145 (forward-line 0)
6146 (cond
6147 ((bobp)
6148 (if (not noerror)
6149 (signal 'beginning-of-buffer nil)
6150 (setq done t)))
6151 ((and (< arg -1) ;; Use vertical-motion for last move
6152 (not (integerp selective-display))
6153 (not (invisible-p (1- (point)))))
6154 (forward-line -1))
6155 ((zerop (vertical-motion -1))
6156 (if (not noerror)
6157 (signal 'beginning-of-buffer nil)
6158 (setq done t))))
6159 (unless done
6160 (setq arg (1+ arg))
6161 (while (and ;; Don't move over previous invis lines
6162 ;; if our target is the middle of this line.
6163 (or (zerop (or goal-column temporary-goal-column))
6164 (< arg 0))
6165 (not (bobp)) (invisible-p (1- (point))))
6166 (goto-char (previous-char-property-change (point))))))))
6167 ;; This is the value the function returns.
6168 (= arg 0))
6169
6170 (cond ((> arg 0)
6171 ;; If we did not move down as far as desired, at least go
6172 ;; to end of line. Be sure to call point-entered and
6173 ;; point-left-hooks.
6174 (let* ((npoint (prog1 (line-end-position)
6175 (goto-char opoint)))
6176 (inhibit-point-motion-hooks nil))
6177 (goto-char npoint)))
6178 ((< arg 0)
6179 ;; If we did not move up as far as desired,
6180 ;; at least go to beginning of line.
6181 (let* ((npoint (prog1 (line-beginning-position)
6182 (goto-char opoint)))
6183 (inhibit-point-motion-hooks nil))
6184 (goto-char npoint)))
6185 (t
6186 (line-move-finish (or goal-column temporary-goal-column)
6187 opoint (> orig-arg 0)))))))
6188
6189 (defun line-move-finish (column opoint forward)
6190 (let ((repeat t))
6191 (while repeat
6192 ;; Set REPEAT to t to repeat the whole thing.
6193 (setq repeat nil)
6194
6195 (let (new
6196 (old (point))
6197 (line-beg (line-beginning-position))
6198 (line-end
6199 ;; Compute the end of the line
6200 ;; ignoring effectively invisible newlines.
6201 (save-excursion
6202 ;; Like end-of-line but ignores fields.
6203 (skip-chars-forward "^\n")
6204 (while (and (not (eobp)) (invisible-p (point)))
6205 (goto-char (next-char-property-change (point)))
6206 (skip-chars-forward "^\n"))
6207 (point))))
6208
6209 ;; Move to the desired column.
6210 (line-move-to-column (truncate column))
6211
6212 ;; Corner case: suppose we start out in a field boundary in
6213 ;; the middle of a continued line. When we get to
6214 ;; line-move-finish, point is at the start of a new *screen*
6215 ;; line but the same text line; then line-move-to-column would
6216 ;; move us backwards. Test using C-n with point on the "x" in
6217 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
6218 (and forward
6219 (< (point) old)
6220 (goto-char old))
6221
6222 (setq new (point))
6223
6224 ;; Process intangibility within a line.
6225 ;; With inhibit-point-motion-hooks bound to nil, a call to
6226 ;; goto-char moves point past intangible text.
6227
6228 ;; However, inhibit-point-motion-hooks controls both the
6229 ;; intangibility and the point-entered/point-left hooks. The
6230 ;; following hack avoids calling the point-* hooks
6231 ;; unnecessarily. Note that we move *forward* past intangible
6232 ;; text when the initial and final points are the same.
6233 (goto-char new)
6234 (let ((inhibit-point-motion-hooks nil))
6235 (goto-char new)
6236
6237 ;; If intangibility moves us to a different (later) place
6238 ;; in the same line, use that as the destination.
6239 (if (<= (point) line-end)
6240 (setq new (point))
6241 ;; If that position is "too late",
6242 ;; try the previous allowable position.
6243 ;; See if it is ok.
6244 (backward-char)
6245 (if (if forward
6246 ;; If going forward, don't accept the previous
6247 ;; allowable position if it is before the target line.
6248 (< line-beg (point))
6249 ;; If going backward, don't accept the previous
6250 ;; allowable position if it is still after the target line.
6251 (<= (point) line-end))
6252 (setq new (point))
6253 ;; As a last resort, use the end of the line.
6254 (setq new line-end))))
6255
6256 ;; Now move to the updated destination, processing fields
6257 ;; as well as intangibility.
6258 (goto-char opoint)
6259 (let ((inhibit-point-motion-hooks nil))
6260 (goto-char
6261 ;; Ignore field boundaries if the initial and final
6262 ;; positions have the same `field' property, even if the
6263 ;; fields are non-contiguous. This seems to be "nicer"
6264 ;; behavior in many situations.
6265 (if (eq (get-char-property new 'field)
6266 (get-char-property opoint 'field))
6267 new
6268 (constrain-to-field new opoint t t
6269 'inhibit-line-move-field-capture))))
6270
6271 ;; If all this moved us to a different line,
6272 ;; retry everything within that new line.
6273 (when (or (< (point) line-beg) (> (point) line-end))
6274 ;; Repeat the intangibility and field processing.
6275 (setq repeat t))))))
6276
6277 (defun line-move-to-column (col)
6278 "Try to find column COL, considering invisibility.
6279 This function works only in certain cases,
6280 because what we really need is for `move-to-column'
6281 and `current-column' to be able to ignore invisible text."
6282 (if (zerop col)
6283 (beginning-of-line)
6284 (move-to-column col))
6285
6286 (when (and line-move-ignore-invisible
6287 (not (bolp)) (invisible-p (1- (point))))
6288 (let ((normal-location (point))
6289 (normal-column (current-column)))
6290 ;; If the following character is currently invisible,
6291 ;; skip all characters with that same `invisible' property value.
6292 (while (and (not (eobp))
6293 (invisible-p (point)))
6294 (goto-char (next-char-property-change (point))))
6295 ;; Have we advanced to a larger column position?
6296 (if (> (current-column) normal-column)
6297 ;; We have made some progress towards the desired column.
6298 ;; See if we can make any further progress.
6299 (line-move-to-column (+ (current-column) (- col normal-column)))
6300 ;; Otherwise, go to the place we originally found
6301 ;; and move back over invisible text.
6302 ;; that will get us to the same place on the screen
6303 ;; but with a more reasonable buffer position.
6304 (goto-char normal-location)
6305 (let ((line-beg
6306 ;; We want the real line beginning, so it's consistent
6307 ;; with bolp below, otherwise we might infloop.
6308 (let ((inhibit-field-text-motion t))
6309 (line-beginning-position))))
6310 (while (and (not (bolp)) (invisible-p (1- (point))))
6311 (goto-char (previous-char-property-change (point) line-beg))))))))
6312
6313 (defun move-end-of-line (arg)
6314 "Move point to end of current line as displayed.
6315 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6316 If point reaches the beginning or end of buffer, it stops there.
6317
6318 To ignore the effects of the `intangible' text or overlay
6319 property, bind `inhibit-point-motion-hooks' to t.
6320 If there is an image in the current line, this function
6321 disregards newlines that are part of the text on which the image
6322 rests."
6323 (interactive "^p")
6324 (or arg (setq arg 1))
6325 (let (done)
6326 (while (not done)
6327 (let ((newpos
6328 (save-excursion
6329 (let ((goal-column 0)
6330 (line-move-visual nil))
6331 (and (line-move arg t)
6332 ;; With bidi reordering, we may not be at bol,
6333 ;; so make sure we are.
6334 (skip-chars-backward "^\n")
6335 (not (bobp))
6336 (progn
6337 (while (and (not (bobp)) (invisible-p (1- (point))))
6338 (goto-char (previous-single-char-property-change
6339 (point) 'invisible)))
6340 (backward-char 1)))
6341 (point)))))
6342 (goto-char newpos)
6343 (if (and (> (point) newpos)
6344 (eq (preceding-char) ?\n))
6345 (backward-char 1)
6346 (if (and (> (point) newpos) (not (eobp))
6347 (not (eq (following-char) ?\n)))
6348 ;; If we skipped something intangible and now we're not
6349 ;; really at eol, keep going.
6350 (setq arg 1)
6351 (setq done t)))))))
6352
6353 (defun move-beginning-of-line (arg)
6354 "Move point to beginning of current line as displayed.
6355 \(If there's an image in the line, this disregards newlines
6356 which are part of the text that the image rests on.)
6357
6358 With argument ARG not nil or 1, move forward ARG - 1 lines first.
6359 If point reaches the beginning or end of buffer, it stops there.
6360 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6361 (interactive "^p")
6362 (or arg (setq arg 1))
6363
6364 (let ((orig (point))
6365 first-vis first-vis-field-value)
6366
6367 ;; Move by lines, if ARG is not 1 (the default).
6368 (if (/= arg 1)
6369 (let ((line-move-visual nil))
6370 (line-move (1- arg) t)))
6371
6372 ;; Move to beginning-of-line, ignoring fields and invisible text.
6373 (skip-chars-backward "^\n")
6374 (while (and (not (bobp)) (invisible-p (1- (point))))
6375 (goto-char (previous-char-property-change (point)))
6376 (skip-chars-backward "^\n"))
6377
6378 ;; Now find first visible char in the line.
6379 (while (and (< (point) orig) (invisible-p (point)))
6380 (goto-char (next-char-property-change (point) orig)))
6381 (setq first-vis (point))
6382
6383 ;; See if fields would stop us from reaching FIRST-VIS.
6384 (setq first-vis-field-value
6385 (constrain-to-field first-vis orig (/= arg 1) t nil))
6386
6387 (goto-char (if (/= first-vis-field-value first-vis)
6388 ;; If yes, obey them.
6389 first-vis-field-value
6390 ;; Otherwise, move to START with attention to fields.
6391 ;; (It is possible that fields never matter in this case.)
6392 (constrain-to-field (point) orig
6393 (/= arg 1) t nil)))))
6394
6395
6396 ;; Many people have said they rarely use this feature, and often type
6397 ;; it by accident. Maybe it shouldn't even be on a key.
6398 (put 'set-goal-column 'disabled t)
6399
6400 (defun set-goal-column (arg)
6401 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
6402 Those commands will move to this position in the line moved to
6403 rather than trying to keep the same horizontal position.
6404 With a non-nil argument ARG, clears out the goal column
6405 so that \\[next-line] and \\[previous-line] resume vertical motion.
6406 The goal column is stored in the variable `goal-column'."
6407 (interactive "P")
6408 (if arg
6409 (progn
6410 (setq goal-column nil)
6411 (message "No goal column"))
6412 (setq goal-column (current-column))
6413 ;; The older method below can be erroneous if `set-goal-column' is bound
6414 ;; to a sequence containing %
6415 ;;(message (substitute-command-keys
6416 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
6417 ;;goal-column)
6418 (message "%s"
6419 (concat
6420 (format "Goal column %d " goal-column)
6421 (substitute-command-keys
6422 "(use \\[set-goal-column] with an arg to unset it)")))
6423
6424 )
6425 nil)
6426 \f
6427 ;;; Editing based on visual lines, as opposed to logical lines.
6428
6429 (defun end-of-visual-line (&optional n)
6430 "Move point to end of current visual line.
6431 With argument N not nil or 1, move forward N - 1 visual lines first.
6432 If point reaches the beginning or end of buffer, it stops there.
6433 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6434 (interactive "^p")
6435 (or n (setq n 1))
6436 (if (/= n 1)
6437 (let ((line-move-visual t))
6438 (line-move (1- n) t)))
6439 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
6440 ;; constrain to field boundaries, so we don't either.
6441 (vertical-motion (cons (window-width) 0)))
6442
6443 (defun beginning-of-visual-line (&optional n)
6444 "Move point to beginning of current visual line.
6445 With argument N not nil or 1, move forward N - 1 visual lines first.
6446 If point reaches the beginning or end of buffer, it stops there.
6447 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
6448 (interactive "^p")
6449 (or n (setq n 1))
6450 (let ((opoint (point)))
6451 (if (/= n 1)
6452 (let ((line-move-visual t))
6453 (line-move (1- n) t)))
6454 (vertical-motion 0)
6455 ;; Constrain to field boundaries, like `move-beginning-of-line'.
6456 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
6457
6458 (defun kill-visual-line (&optional arg)
6459 "Kill the rest of the visual line.
6460 With prefix argument ARG, kill that many visual lines from point.
6461 If ARG is negative, kill visual lines backward.
6462 If ARG is zero, kill the text before point on the current visual
6463 line.
6464
6465 If you want to append the killed line to the last killed text,
6466 use \\[append-next-kill] before \\[kill-line].
6467
6468 If the buffer is read-only, Emacs will beep and refrain from deleting
6469 the line, but put the line in the kill ring anyway. This means that
6470 you can use this command to copy text from a read-only buffer.
6471 \(If the variable `kill-read-only-ok' is non-nil, then this won't
6472 even beep.)"
6473 (interactive "P")
6474 ;; Like in `kill-line', it's better to move point to the other end
6475 ;; of the kill before killing.
6476 (let ((opoint (point))
6477 (kill-whole-line (and kill-whole-line (bolp))))
6478 (if arg
6479 (vertical-motion (prefix-numeric-value arg))
6480 (end-of-visual-line 1)
6481 (if (= (point) opoint)
6482 (vertical-motion 1)
6483 ;; Skip any trailing whitespace at the end of the visual line.
6484 ;; We used to do this only if `show-trailing-whitespace' is
6485 ;; nil, but that's wrong; the correct thing would be to check
6486 ;; whether the trailing whitespace is highlighted. But, it's
6487 ;; OK to just do this unconditionally.
6488 (skip-chars-forward " \t")))
6489 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
6490 (1+ (point))
6491 (point)))))
6492
6493 (defun next-logical-line (&optional arg try-vscroll)
6494 "Move cursor vertically down ARG lines.
6495 This is identical to `next-line', except that it always moves
6496 by logical lines instead of visual lines, ignoring the value of
6497 the variable `line-move-visual'."
6498 (interactive "^p\np")
6499 (let ((line-move-visual nil))
6500 (with-no-warnings
6501 (next-line arg try-vscroll))))
6502
6503 (defun previous-logical-line (&optional arg try-vscroll)
6504 "Move cursor vertically up ARG lines.
6505 This is identical to `previous-line', except that it always moves
6506 by logical lines instead of visual lines, ignoring the value of
6507 the variable `line-move-visual'."
6508 (interactive "^p\np")
6509 (let ((line-move-visual nil))
6510 (with-no-warnings
6511 (previous-line arg try-vscroll))))
6512
6513 (defgroup visual-line nil
6514 "Editing based on visual lines."
6515 :group 'convenience
6516 :version "23.1")
6517
6518 (defvar visual-line-mode-map
6519 (let ((map (make-sparse-keymap)))
6520 (define-key map [remap kill-line] 'kill-visual-line)
6521 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
6522 (define-key map [remap move-end-of-line] 'end-of-visual-line)
6523 ;; These keybindings interfere with xterm function keys. Are
6524 ;; there any other suitable bindings?
6525 ;; (define-key map "\M-[" 'previous-logical-line)
6526 ;; (define-key map "\M-]" 'next-logical-line)
6527 map))
6528
6529 (defcustom visual-line-fringe-indicators '(nil nil)
6530 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
6531 The value should be a list of the form (LEFT RIGHT), where LEFT
6532 and RIGHT are symbols representing the bitmaps to display, to
6533 indicate wrapped lines, in the left and right fringes respectively.
6534 See also `fringe-indicator-alist'.
6535 The default is not to display fringe indicators for wrapped lines.
6536 This variable does not affect fringe indicators displayed for
6537 other purposes."
6538 :type '(list (choice (const :tag "Hide left indicator" nil)
6539 (const :tag "Left curly arrow" left-curly-arrow)
6540 (symbol :tag "Other bitmap"))
6541 (choice (const :tag "Hide right indicator" nil)
6542 (const :tag "Right curly arrow" right-curly-arrow)
6543 (symbol :tag "Other bitmap")))
6544 :set (lambda (symbol value)
6545 (dolist (buf (buffer-list))
6546 (with-current-buffer buf
6547 (when (and (boundp 'visual-line-mode)
6548 (symbol-value 'visual-line-mode))
6549 (setq fringe-indicator-alist
6550 (cons (cons 'continuation value)
6551 (assq-delete-all
6552 'continuation
6553 (copy-tree fringe-indicator-alist)))))))
6554 (set-default symbol value)))
6555
6556 (defvar visual-line--saved-state nil)
6557
6558 (define-minor-mode visual-line-mode
6559 "Toggle visual line based editing (Visual Line mode).
6560 With a prefix argument ARG, enable Visual Line mode if ARG is
6561 positive, and disable it otherwise. If called from Lisp, enable
6562 the mode if ARG is omitted or nil.
6563
6564 When Visual Line mode is enabled, `word-wrap' is turned on in
6565 this buffer, and simple editing commands are redefined to act on
6566 visual lines, not logical lines. See Info node `Visual Line
6567 Mode' for details."
6568 :keymap visual-line-mode-map
6569 :group 'visual-line
6570 :lighter " Wrap"
6571 (if visual-line-mode
6572 (progn
6573 (set (make-local-variable 'visual-line--saved-state) nil)
6574 ;; Save the local values of some variables, to be restored if
6575 ;; visual-line-mode is turned off.
6576 (dolist (var '(line-move-visual truncate-lines
6577 truncate-partial-width-windows
6578 word-wrap fringe-indicator-alist))
6579 (if (local-variable-p var)
6580 (push (cons var (symbol-value var))
6581 visual-line--saved-state)))
6582 (set (make-local-variable 'line-move-visual) t)
6583 (set (make-local-variable 'truncate-partial-width-windows) nil)
6584 (setq truncate-lines nil
6585 word-wrap t
6586 fringe-indicator-alist
6587 (cons (cons 'continuation visual-line-fringe-indicators)
6588 fringe-indicator-alist)))
6589 (kill-local-variable 'line-move-visual)
6590 (kill-local-variable 'word-wrap)
6591 (kill-local-variable 'truncate-lines)
6592 (kill-local-variable 'truncate-partial-width-windows)
6593 (kill-local-variable 'fringe-indicator-alist)
6594 (dolist (saved visual-line--saved-state)
6595 (set (make-local-variable (car saved)) (cdr saved)))
6596 (kill-local-variable 'visual-line--saved-state)))
6597
6598 (defun turn-on-visual-line-mode ()
6599 (visual-line-mode 1))
6600
6601 (define-globalized-minor-mode global-visual-line-mode
6602 visual-line-mode turn-on-visual-line-mode)
6603
6604 \f
6605 (defun transpose-chars (arg)
6606 "Interchange characters around point, moving forward one character.
6607 With prefix arg ARG, effect is to take character before point
6608 and drag it forward past ARG other characters (backward if ARG negative).
6609 If no argument and at end of line, the previous two chars are exchanged."
6610 (interactive "*P")
6611 (when (and (null arg) (eolp) (not (bobp))
6612 (not (get-text-property (1- (point)) 'read-only)))
6613 (forward-char -1))
6614 (transpose-subr 'forward-char (prefix-numeric-value arg)))
6615
6616 (defun transpose-words (arg)
6617 "Interchange words around point, leaving point at end of them.
6618 With prefix arg ARG, effect is to take word before or around point
6619 and drag it forward past ARG other words (backward if ARG negative).
6620 If ARG is zero, the words around or after point and around or after mark
6621 are interchanged."
6622 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
6623 (interactive "*p")
6624 (transpose-subr 'forward-word arg))
6625
6626 (defun transpose-sexps (arg)
6627 "Like \\[transpose-words] but applies to sexps.
6628 Does not work on a sexp that point is in the middle of
6629 if it is a list or string."
6630 (interactive "*p")
6631 (transpose-subr
6632 (lambda (arg)
6633 ;; Here we should try to simulate the behavior of
6634 ;; (cons (progn (forward-sexp x) (point))
6635 ;; (progn (forward-sexp (- x)) (point)))
6636 ;; Except that we don't want to rely on the second forward-sexp
6637 ;; putting us back to where we want to be, since forward-sexp-function
6638 ;; might do funny things like infix-precedence.
6639 (if (if (> arg 0)
6640 (looking-at "\\sw\\|\\s_")
6641 (and (not (bobp))
6642 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
6643 ;; Jumping over a symbol. We might be inside it, mind you.
6644 (progn (funcall (if (> arg 0)
6645 'skip-syntax-backward 'skip-syntax-forward)
6646 "w_")
6647 (cons (save-excursion (forward-sexp arg) (point)) (point)))
6648 ;; Otherwise, we're between sexps. Take a step back before jumping
6649 ;; to make sure we'll obey the same precedence no matter which direction
6650 ;; we're going.
6651 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
6652 (cons (save-excursion (forward-sexp arg) (point))
6653 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
6654 (not (zerop (funcall (if (> arg 0)
6655 'skip-syntax-forward
6656 'skip-syntax-backward)
6657 ".")))))
6658 (point)))))
6659 arg 'special))
6660
6661 (defun transpose-lines (arg)
6662 "Exchange current line and previous line, leaving point after both.
6663 With argument ARG, takes previous line and moves it past ARG lines.
6664 With argument 0, interchanges line point is in with line mark is in."
6665 (interactive "*p")
6666 (transpose-subr (function
6667 (lambda (arg)
6668 (if (> arg 0)
6669 (progn
6670 ;; Move forward over ARG lines,
6671 ;; but create newlines if necessary.
6672 (setq arg (forward-line arg))
6673 (if (/= (preceding-char) ?\n)
6674 (setq arg (1+ arg)))
6675 (if (> arg 0)
6676 (newline arg)))
6677 (forward-line arg))))
6678 arg))
6679
6680 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
6681 ;; which seems inconsistent with the ARG /= 0 case.
6682 ;; FIXME document SPECIAL.
6683 (defun transpose-subr (mover arg &optional special)
6684 "Subroutine to do the work of transposing objects.
6685 Works for lines, sentences, paragraphs, etc. MOVER is a function that
6686 moves forward by units of the given object (e.g. forward-sentence,
6687 forward-paragraph). If ARG is zero, exchanges the current object
6688 with the one containing mark. If ARG is an integer, moves the
6689 current object past ARG following (if ARG is positive) or
6690 preceding (if ARG is negative) objects, leaving point after the
6691 current object."
6692 (let ((aux (if special mover
6693 (lambda (x)
6694 (cons (progn (funcall mover x) (point))
6695 (progn (funcall mover (- x)) (point))))))
6696 pos1 pos2)
6697 (cond
6698 ((= arg 0)
6699 (save-excursion
6700 (setq pos1 (funcall aux 1))
6701 (goto-char (or (mark) (error "No mark set in this buffer")))
6702 (setq pos2 (funcall aux 1))
6703 (transpose-subr-1 pos1 pos2))
6704 (exchange-point-and-mark))
6705 ((> arg 0)
6706 (setq pos1 (funcall aux -1))
6707 (setq pos2 (funcall aux arg))
6708 (transpose-subr-1 pos1 pos2)
6709 (goto-char (car pos2)))
6710 (t
6711 (setq pos1 (funcall aux -1))
6712 (goto-char (car pos1))
6713 (setq pos2 (funcall aux arg))
6714 (transpose-subr-1 pos1 pos2)
6715 (goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
6716
6717 (defun transpose-subr-1 (pos1 pos2)
6718 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
6719 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
6720 (when (> (car pos1) (car pos2))
6721 (let ((swap pos1))
6722 (setq pos1 pos2 pos2 swap)))
6723 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
6724 (atomic-change-group
6725 ;; This sequence of insertions attempts to preserve marker
6726 ;; positions at the start and end of the transposed objects.
6727 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
6728 (len1 (- (cdr pos1) (car pos1)))
6729 (len2 (length word))
6730 (boundary (make-marker)))
6731 (set-marker boundary (car pos2))
6732 (goto-char (cdr pos1))
6733 (insert-before-markers word)
6734 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
6735 (goto-char boundary)
6736 (insert word)
6737 (goto-char (+ boundary len1))
6738 (delete-region (point) (+ (point) len2))
6739 (set-marker boundary nil))))
6740 \f
6741 (defun backward-word (&optional arg)
6742 "Move backward until encountering the beginning of a word.
6743 With argument ARG, do this that many times.
6744 If ARG is omitted or nil, move point backward one word.
6745
6746 The word boundaries are normally determined by the buffer's syntax
6747 table, but `find-word-boundary-function-table', such as set up
6748 by `subword-mode', can change that. If a Lisp program needs to
6749 move by words determined strictly by the syntax table, it should
6750 use `backward-word-strictly' instead."
6751 (interactive "^p")
6752 (forward-word (- (or arg 1))))
6753
6754 (defun mark-word (&optional arg allow-extend)
6755 "Set mark ARG words away from point.
6756 The place mark goes is the same place \\[forward-word] would
6757 move to with the same argument.
6758 Interactively, if this command is repeated
6759 or (in Transient Mark mode) if the mark is active,
6760 it marks the next ARG words after the ones already marked."
6761 (interactive "P\np")
6762 (cond ((and allow-extend
6763 (or (and (eq last-command this-command) (mark t))
6764 (region-active-p)))
6765 (setq arg (if arg (prefix-numeric-value arg)
6766 (if (< (mark) (point)) -1 1)))
6767 (set-mark
6768 (save-excursion
6769 (goto-char (mark))
6770 (forward-word arg)
6771 (point))))
6772 (t
6773 (push-mark
6774 (save-excursion
6775 (forward-word (prefix-numeric-value arg))
6776 (point))
6777 nil t))))
6778
6779 (defun kill-word (arg)
6780 "Kill characters forward until encountering the end of a word.
6781 With argument ARG, do this that many times."
6782 (interactive "p")
6783 (kill-region (point) (progn (forward-word arg) (point))))
6784
6785 (defun backward-kill-word (arg)
6786 "Kill characters backward until encountering the beginning of a word.
6787 With argument ARG, do this that many times."
6788 (interactive "p")
6789 (kill-word (- arg)))
6790
6791 (defun current-word (&optional strict really-word)
6792 "Return the symbol or word that point is on (or a nearby one) as a string.
6793 The return value includes no text properties.
6794 If optional arg STRICT is non-nil, return nil unless point is within
6795 or adjacent to a symbol or word. In all cases the value can be nil
6796 if there is no word nearby.
6797 The function, belying its name, normally finds a symbol.
6798 If optional arg REALLY-WORD is non-nil, it finds just a word."
6799 (save-excursion
6800 (let* ((oldpoint (point)) (start (point)) (end (point))
6801 (syntaxes (if really-word "w" "w_"))
6802 (not-syntaxes (concat "^" syntaxes)))
6803 (skip-syntax-backward syntaxes) (setq start (point))
6804 (goto-char oldpoint)
6805 (skip-syntax-forward syntaxes) (setq end (point))
6806 (when (and (eq start oldpoint) (eq end oldpoint)
6807 ;; Point is neither within nor adjacent to a word.
6808 (not strict))
6809 ;; Look for preceding word in same line.
6810 (skip-syntax-backward not-syntaxes (line-beginning-position))
6811 (if (bolp)
6812 ;; No preceding word in same line.
6813 ;; Look for following word in same line.
6814 (progn
6815 (skip-syntax-forward not-syntaxes (line-end-position))
6816 (setq start (point))
6817 (skip-syntax-forward syntaxes)
6818 (setq end (point)))
6819 (setq end (point))
6820 (skip-syntax-backward syntaxes)
6821 (setq start (point))))
6822 ;; If we found something nonempty, return it as a string.
6823 (unless (= start end)
6824 (buffer-substring-no-properties start end)))))
6825 \f
6826 (defcustom fill-prefix nil
6827 "String for filling to insert at front of new line, or nil for none."
6828 :type '(choice (const :tag "None" nil)
6829 string)
6830 :group 'fill)
6831 (make-variable-buffer-local 'fill-prefix)
6832 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
6833
6834 (defcustom auto-fill-inhibit-regexp nil
6835 "Regexp to match lines which should not be auto-filled."
6836 :type '(choice (const :tag "None" nil)
6837 regexp)
6838 :group 'fill)
6839
6840 (defun do-auto-fill ()
6841 "The default value for `normal-auto-fill-function'.
6842 This is the default auto-fill function, some major modes use a different one.
6843 Returns t if it really did any work."
6844 (let (fc justify give-up
6845 (fill-prefix fill-prefix))
6846 (if (or (not (setq justify (current-justification)))
6847 (null (setq fc (current-fill-column)))
6848 (and (eq justify 'left)
6849 (<= (current-column) fc))
6850 (and auto-fill-inhibit-regexp
6851 (save-excursion (beginning-of-line)
6852 (looking-at auto-fill-inhibit-regexp))))
6853 nil ;; Auto-filling not required
6854 (if (memq justify '(full center right))
6855 (save-excursion (unjustify-current-line)))
6856
6857 ;; Choose a fill-prefix automatically.
6858 (when (and adaptive-fill-mode
6859 (or (null fill-prefix) (string= fill-prefix "")))
6860 (let ((prefix
6861 (fill-context-prefix
6862 (save-excursion (fill-forward-paragraph -1) (point))
6863 (save-excursion (fill-forward-paragraph 1) (point)))))
6864 (and prefix (not (equal prefix ""))
6865 ;; Use auto-indentation rather than a guessed empty prefix.
6866 (not (and fill-indent-according-to-mode
6867 (string-match "\\`[ \t]*\\'" prefix)))
6868 (setq fill-prefix prefix))))
6869
6870 (while (and (not give-up) (> (current-column) fc))
6871 ;; Determine where to split the line.
6872 (let* (after-prefix
6873 (fill-point
6874 (save-excursion
6875 (beginning-of-line)
6876 (setq after-prefix (point))
6877 (and fill-prefix
6878 (looking-at (regexp-quote fill-prefix))
6879 (setq after-prefix (match-end 0)))
6880 (move-to-column (1+ fc))
6881 (fill-move-to-break-point after-prefix)
6882 (point))))
6883
6884 ;; See whether the place we found is any good.
6885 (if (save-excursion
6886 (goto-char fill-point)
6887 (or (bolp)
6888 ;; There is no use breaking at end of line.
6889 (save-excursion (skip-chars-forward " ") (eolp))
6890 ;; It is futile to split at the end of the prefix
6891 ;; since we would just insert the prefix again.
6892 (and after-prefix (<= (point) after-prefix))
6893 ;; Don't split right after a comment starter
6894 ;; since we would just make another comment starter.
6895 (and comment-start-skip
6896 (let ((limit (point)))
6897 (beginning-of-line)
6898 (and (re-search-forward comment-start-skip
6899 limit t)
6900 (eq (point) limit))))))
6901 ;; No good place to break => stop trying.
6902 (setq give-up t)
6903 ;; Ok, we have a useful place to break the line. Do it.
6904 (let ((prev-column (current-column)))
6905 ;; If point is at the fill-point, do not `save-excursion'.
6906 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6907 ;; point will end up before it rather than after it.
6908 (if (save-excursion
6909 (skip-chars-backward " \t")
6910 (= (point) fill-point))
6911 (default-indent-new-line t)
6912 (save-excursion
6913 (goto-char fill-point)
6914 (default-indent-new-line t)))
6915 ;; Now do justification, if required
6916 (if (not (eq justify 'left))
6917 (save-excursion
6918 (end-of-line 0)
6919 (justify-current-line justify nil t)))
6920 ;; If making the new line didn't reduce the hpos of
6921 ;; the end of the line, then give up now;
6922 ;; trying again will not help.
6923 (if (>= (current-column) prev-column)
6924 (setq give-up t))))))
6925 ;; Justify last line.
6926 (justify-current-line justify t t)
6927 t)))
6928
6929 (defvar comment-line-break-function 'comment-indent-new-line
6930 "Mode-specific function which line breaks and continues a comment.
6931 This function is called during auto-filling when a comment syntax
6932 is defined.
6933 The function should take a single optional argument, which is a flag
6934 indicating whether it should use soft newlines.")
6935
6936 (defun default-indent-new-line (&optional soft)
6937 "Break line at point and indent.
6938 If a comment syntax is defined, call `comment-indent-new-line'.
6939
6940 The inserted newline is marked hard if variable `use-hard-newlines' is true,
6941 unless optional argument SOFT is non-nil."
6942 (interactive)
6943 (if comment-start
6944 (funcall comment-line-break-function soft)
6945 ;; Insert the newline before removing empty space so that markers
6946 ;; get preserved better.
6947 (if soft (insert-and-inherit ?\n) (newline 1))
6948 (save-excursion (forward-char -1) (delete-horizontal-space))
6949 (delete-horizontal-space)
6950
6951 (if (and fill-prefix (not adaptive-fill-mode))
6952 ;; Blindly trust a non-adaptive fill-prefix.
6953 (progn
6954 (indent-to-left-margin)
6955 (insert-before-markers-and-inherit fill-prefix))
6956
6957 (cond
6958 ;; If there's an adaptive prefix, use it unless we're inside
6959 ;; a comment and the prefix is not a comment starter.
6960 (fill-prefix
6961 (indent-to-left-margin)
6962 (insert-and-inherit fill-prefix))
6963 ;; If we're not inside a comment, just try to indent.
6964 (t (indent-according-to-mode))))))
6965
6966 (defvar normal-auto-fill-function 'do-auto-fill
6967 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6968 Some major modes set this.")
6969
6970 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
6971 ;; `functions' and `hooks' are usually unsafe to set, but setting
6972 ;; auto-fill-function to nil in a file-local setting is safe and
6973 ;; can be useful to prevent auto-filling.
6974 (put 'auto-fill-function 'safe-local-variable 'null)
6975
6976 (define-minor-mode auto-fill-mode
6977 "Toggle automatic line breaking (Auto Fill mode).
6978 With a prefix argument ARG, enable Auto Fill mode if ARG is
6979 positive, and disable it otherwise. If called from Lisp, enable
6980 the mode if ARG is omitted or nil.
6981
6982 When Auto Fill mode is enabled, inserting a space at a column
6983 beyond `current-fill-column' automatically breaks the line at a
6984 previous space.
6985
6986 When `auto-fill-mode' is on, the `auto-fill-function' variable is
6987 non-nil.
6988
6989 The value of `normal-auto-fill-function' specifies the function to use
6990 for `auto-fill-function' when turning Auto Fill mode on."
6991 :variable (auto-fill-function
6992 . (lambda (v) (setq auto-fill-function
6993 (if v normal-auto-fill-function)))))
6994
6995 ;; This holds a document string used to document auto-fill-mode.
6996 (defun auto-fill-function ()
6997 "Automatically break line at a previous space, in insertion of text."
6998 nil)
6999
7000 (defun turn-on-auto-fill ()
7001 "Unconditionally turn on Auto Fill mode."
7002 (auto-fill-mode 1))
7003
7004 (defun turn-off-auto-fill ()
7005 "Unconditionally turn off Auto Fill mode."
7006 (auto-fill-mode -1))
7007
7008 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
7009
7010 (defun set-fill-column (arg)
7011 "Set `fill-column' to specified argument.
7012 Use \\[universal-argument] followed by a number to specify a column.
7013 Just \\[universal-argument] as argument means to use the current column."
7014 (interactive
7015 (list (or current-prefix-arg
7016 ;; We used to use current-column silently, but C-x f is too easily
7017 ;; typed as a typo for C-x C-f, so we turned it into an error and
7018 ;; now an interactive prompt.
7019 (read-number "Set fill-column to: " (current-column)))))
7020 (if (consp arg)
7021 (setq arg (current-column)))
7022 (if (not (integerp arg))
7023 ;; Disallow missing argument; it's probably a typo for C-x C-f.
7024 (error "set-fill-column requires an explicit argument")
7025 (message "Fill column set to %d (was %d)" arg fill-column)
7026 (setq fill-column arg)))
7027 \f
7028 (defun set-selective-display (arg)
7029 "Set `selective-display' to ARG; clear it if no arg.
7030 When the value of `selective-display' is a number > 0,
7031 lines whose indentation is >= that value are not displayed.
7032 The variable `selective-display' has a separate value for each buffer."
7033 (interactive "P")
7034 (if (eq selective-display t)
7035 (error "selective-display already in use for marked lines"))
7036 (let ((current-vpos
7037 (save-restriction
7038 (narrow-to-region (point-min) (point))
7039 (goto-char (window-start))
7040 (vertical-motion (window-height)))))
7041 (setq selective-display
7042 (and arg (prefix-numeric-value arg)))
7043 (recenter current-vpos))
7044 (set-window-start (selected-window) (window-start))
7045 (princ "selective-display set to " t)
7046 (prin1 selective-display t)
7047 (princ "." t))
7048
7049 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
7050
7051 (defun toggle-truncate-lines (&optional arg)
7052 "Toggle truncating of long lines for the current buffer.
7053 When truncating is off, long lines are folded.
7054 With prefix argument ARG, truncate long lines if ARG is positive,
7055 otherwise fold them. Note that in side-by-side windows, this
7056 command has no effect if `truncate-partial-width-windows' is
7057 non-nil."
7058 (interactive "P")
7059 (setq truncate-lines
7060 (if (null arg)
7061 (not truncate-lines)
7062 (> (prefix-numeric-value arg) 0)))
7063 (force-mode-line-update)
7064 (unless truncate-lines
7065 (let ((buffer (current-buffer)))
7066 (walk-windows (lambda (window)
7067 (if (eq buffer (window-buffer window))
7068 (set-window-hscroll window 0)))
7069 nil t)))
7070 (message "Truncate long lines %s"
7071 (if truncate-lines "enabled" "disabled")))
7072
7073 (defun toggle-word-wrap (&optional arg)
7074 "Toggle whether to use word-wrapping for continuation lines.
7075 With prefix argument ARG, wrap continuation lines at word boundaries
7076 if ARG is positive, otherwise wrap them at the right screen edge.
7077 This command toggles the value of `word-wrap'. It has no effect
7078 if long lines are truncated."
7079 (interactive "P")
7080 (setq word-wrap
7081 (if (null arg)
7082 (not word-wrap)
7083 (> (prefix-numeric-value arg) 0)))
7084 (force-mode-line-update)
7085 (message "Word wrapping %s"
7086 (if word-wrap "enabled" "disabled")))
7087
7088 (defvar overwrite-mode-textual (purecopy " Ovwrt")
7089 "The string displayed in the mode line when in overwrite mode.")
7090 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
7091 "The string displayed in the mode line when in binary overwrite mode.")
7092
7093 (define-minor-mode overwrite-mode
7094 "Toggle Overwrite mode.
7095 With a prefix argument ARG, enable Overwrite mode if ARG is
7096 positive, and disable it otherwise. If called from Lisp, enable
7097 the mode if ARG is omitted or nil.
7098
7099 When Overwrite mode is enabled, printing characters typed in
7100 replace existing text on a one-for-one basis, rather than pushing
7101 it to the right. At the end of a line, such characters extend
7102 the line. Before a tab, such characters insert until the tab is
7103 filled in. \\[quoted-insert] still inserts characters in
7104 overwrite mode; this is supposed to make it easier to insert
7105 characters when necessary."
7106 :variable (overwrite-mode
7107 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
7108
7109 (define-minor-mode binary-overwrite-mode
7110 "Toggle Binary Overwrite mode.
7111 With a prefix argument ARG, enable Binary Overwrite mode if ARG
7112 is positive, and disable it otherwise. If called from Lisp,
7113 enable the mode if ARG is omitted or nil.
7114
7115 When Binary Overwrite mode is enabled, printing characters typed
7116 in replace existing text. Newlines are not treated specially, so
7117 typing at the end of a line joins the line to the next, with the
7118 typed character between them. Typing before a tab character
7119 simply replaces the tab with the character typed.
7120 \\[quoted-insert] replaces the text at the cursor, just as
7121 ordinary typing characters do.
7122
7123 Note that Binary Overwrite mode is not its own minor mode; it is
7124 a specialization of overwrite mode, entered by setting the
7125 `overwrite-mode' variable to `overwrite-mode-binary'."
7126 :variable (overwrite-mode
7127 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
7128
7129 (define-minor-mode line-number-mode
7130 "Toggle line number display in the mode line (Line Number mode).
7131 With a prefix argument ARG, enable Line Number mode if ARG is
7132 positive, and disable it otherwise. If called from Lisp, enable
7133 the mode if ARG is omitted or nil.
7134
7135 Line numbers do not appear for very large buffers and buffers
7136 with very long lines; see variables `line-number-display-limit'
7137 and `line-number-display-limit-width'."
7138 :init-value t :global t :group 'mode-line)
7139
7140 (define-minor-mode column-number-mode
7141 "Toggle column number display in the mode line (Column Number mode).
7142 With a prefix argument ARG, enable Column Number mode if ARG is
7143 positive, and disable it otherwise.
7144
7145 If called from Lisp, enable the mode if ARG is omitted or nil."
7146 :global t :group 'mode-line)
7147
7148 (define-minor-mode size-indication-mode
7149 "Toggle buffer size display in the mode line (Size Indication mode).
7150 With a prefix argument ARG, enable Size Indication mode if ARG is
7151 positive, and disable it otherwise.
7152
7153 If called from Lisp, enable the mode if ARG is omitted or nil."
7154 :global t :group 'mode-line)
7155
7156 (define-minor-mode auto-save-mode
7157 "Toggle auto-saving in the current buffer (Auto Save mode).
7158 With a prefix argument ARG, enable Auto Save mode if ARG is
7159 positive, and disable it otherwise.
7160
7161 If called from Lisp, enable the mode if ARG is omitted or nil."
7162 :variable ((and buffer-auto-save-file-name
7163 ;; If auto-save is off because buffer has shrunk,
7164 ;; then toggling should turn it on.
7165 (>= buffer-saved-size 0))
7166 . (lambda (val)
7167 (setq buffer-auto-save-file-name
7168 (cond
7169 ((null val) nil)
7170 ((and buffer-file-name auto-save-visited-file-name
7171 (not buffer-read-only))
7172 buffer-file-name)
7173 (t (make-auto-save-file-name))))))
7174 ;; If -1 was stored here, to temporarily turn off saving,
7175 ;; turn it back on.
7176 (and (< buffer-saved-size 0)
7177 (setq buffer-saved-size 0)))
7178 \f
7179 (defgroup paren-blinking nil
7180 "Blinking matching of parens and expressions."
7181 :prefix "blink-matching-"
7182 :group 'paren-matching)
7183
7184 (defcustom blink-matching-paren t
7185 "Non-nil means show matching open-paren when close-paren is inserted.
7186 If t, highlight the paren. If `jump', briefly move cursor to its
7187 position. If `jump-offscreen', move cursor there even if the
7188 position is off screen. With any other non-nil value, the
7189 off-screen position of the opening paren will be shown in the
7190 echo area."
7191 :type '(choice
7192 (const :tag "Disable" nil)
7193 (const :tag "Highlight" t)
7194 (const :tag "Move cursor" jump)
7195 (const :tag "Move cursor, even if off screen" jump-offscreen))
7196 :group 'paren-blinking)
7197
7198 (defcustom blink-matching-paren-on-screen t
7199 "Non-nil means show matching open-paren when it is on screen.
7200 If nil, don't show it (but the open-paren can still be shown
7201 in the echo area when it is off screen).
7202
7203 This variable has no effect if `blink-matching-paren' is nil.
7204 \(In that case, the open-paren is never shown.)
7205 It is also ignored if `show-paren-mode' is enabled."
7206 :type 'boolean
7207 :group 'paren-blinking)
7208
7209 (defcustom blink-matching-paren-distance (* 100 1024)
7210 "If non-nil, maximum distance to search backwards for matching open-paren.
7211 If nil, search stops at the beginning of the accessible portion of the buffer."
7212 :version "23.2" ; 25->100k
7213 :type '(choice (const nil) integer)
7214 :group 'paren-blinking)
7215
7216 (defcustom blink-matching-delay 1
7217 "Time in seconds to delay after showing a matching paren."
7218 :type 'number
7219 :group 'paren-blinking)
7220
7221 (defcustom blink-matching-paren-dont-ignore-comments nil
7222 "If nil, `blink-matching-paren' ignores comments.
7223 More precisely, when looking for the matching parenthesis,
7224 it skips the contents of comments that end before point."
7225 :type 'boolean
7226 :group 'paren-blinking)
7227
7228 (defun blink-matching-check-mismatch (start end)
7229 "Return whether or not START...END are matching parens.
7230 END is the current point and START is the blink position.
7231 START might be nil if no matching starter was found.
7232 Returns non-nil if we find there is a mismatch."
7233 (let* ((end-syntax (syntax-after (1- end)))
7234 (matching-paren (and (consp end-syntax)
7235 (eq (syntax-class end-syntax) 5)
7236 (cdr end-syntax))))
7237 ;; For self-matched chars like " and $, we can't know when they're
7238 ;; mismatched or unmatched, so we can only do it for parens.
7239 (when matching-paren
7240 (not (and start
7241 (or
7242 (eq (char-after start) matching-paren)
7243 ;; The cdr might hold a new paren-class info rather than
7244 ;; a matching-char info, in which case the two CDRs
7245 ;; should match.
7246 (eq matching-paren (cdr-safe (syntax-after start)))))))))
7247
7248 (defvar blink-matching-check-function #'blink-matching-check-mismatch
7249 "Function to check parentheses mismatches.
7250 The function takes two arguments (START and END) where START is the
7251 position just before the opening token and END is the position right after.
7252 START can be nil, if it was not found.
7253 The function should return non-nil if the two tokens do not match.")
7254
7255 (defvar blink-matching--overlay
7256 (let ((ol (make-overlay (point) (point) nil t)))
7257 (overlay-put ol 'face 'show-paren-match)
7258 (delete-overlay ol)
7259 ol)
7260 "Overlay used to highlight the matching paren.")
7261
7262 (defun blink-matching-open ()
7263 "Momentarily highlight the beginning of the sexp before point."
7264 (interactive)
7265 (when (and (not (bobp))
7266 blink-matching-paren)
7267 (let* ((oldpos (point))
7268 (message-log-max nil) ; Don't log messages about paren matching.
7269 (blinkpos
7270 (save-excursion
7271 (save-restriction
7272 (if blink-matching-paren-distance
7273 (narrow-to-region
7274 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
7275 (- (point) blink-matching-paren-distance))
7276 oldpos))
7277 (let ((parse-sexp-ignore-comments
7278 (and parse-sexp-ignore-comments
7279 (not blink-matching-paren-dont-ignore-comments))))
7280 (condition-case ()
7281 (progn
7282 (syntax-propertize (point))
7283 (forward-sexp -1)
7284 ;; backward-sexp skips backward over prefix chars,
7285 ;; so move back to the matching paren.
7286 (while (and (< (point) (1- oldpos))
7287 (let ((code (syntax-after (point))))
7288 (or (eq (syntax-class code) 6)
7289 (eq (logand 1048576 (car code))
7290 1048576))))
7291 (forward-char 1))
7292 (point))
7293 (error nil))))))
7294 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
7295 (cond
7296 (mismatch
7297 (if blinkpos
7298 (if (minibufferp)
7299 (minibuffer-message "Mismatched parentheses")
7300 (message "Mismatched parentheses"))
7301 (if (minibufferp)
7302 (minibuffer-message "No matching parenthesis found")
7303 (message "No matching parenthesis found"))))
7304 ((not blinkpos) nil)
7305 ((or
7306 (eq blink-matching-paren 'jump-offscreen)
7307 (pos-visible-in-window-p blinkpos))
7308 ;; Matching open within window, temporarily move to or highlight
7309 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
7310 ;; is non-nil.
7311 (and blink-matching-paren-on-screen
7312 (not show-paren-mode)
7313 (if (memq blink-matching-paren '(jump jump-offscreen))
7314 (save-excursion
7315 (goto-char blinkpos)
7316 (sit-for blink-matching-delay))
7317 (unwind-protect
7318 (progn
7319 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
7320 (current-buffer))
7321 (sit-for blink-matching-delay))
7322 (delete-overlay blink-matching--overlay)))))
7323 (t
7324 (let ((open-paren-line-string
7325 (save-excursion
7326 (goto-char blinkpos)
7327 ;; Show what precedes the open in its line, if anything.
7328 (cond
7329 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
7330 (buffer-substring (line-beginning-position)
7331 (1+ blinkpos)))
7332 ;; Show what follows the open in its line, if anything.
7333 ((save-excursion
7334 (forward-char 1)
7335 (skip-chars-forward " \t")
7336 (not (eolp)))
7337 (buffer-substring blinkpos
7338 (line-end-position)))
7339 ;; Otherwise show the previous nonblank line,
7340 ;; if there is one.
7341 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
7342 (concat
7343 (buffer-substring (progn
7344 (skip-chars-backward "\n \t")
7345 (line-beginning-position))
7346 (progn (end-of-line)
7347 (skip-chars-backward " \t")
7348 (point)))
7349 ;; Replace the newline and other whitespace with `...'.
7350 "..."
7351 (buffer-substring blinkpos (1+ blinkpos))))
7352 ;; There is nothing to show except the char itself.
7353 (t (buffer-substring blinkpos (1+ blinkpos)))))))
7354 (minibuffer-message
7355 "Matches %s"
7356 (substring-no-properties open-paren-line-string))))))))
7357
7358 (defvar blink-paren-function 'blink-matching-open
7359 "Function called, if non-nil, whenever a close parenthesis is inserted.
7360 More precisely, a char with closeparen syntax is self-inserted.")
7361
7362 (defun blink-paren-post-self-insert-function ()
7363 (when (and (eq (char-before) last-command-event) ; Sanity check.
7364 (memq (char-syntax last-command-event) '(?\) ?\$))
7365 blink-paren-function
7366 (not executing-kbd-macro)
7367 (not noninteractive)
7368 ;; Verify an even number of quoting characters precede the close.
7369 ;; FIXME: Also check if this parenthesis closes a comment as
7370 ;; can happen in Pascal and SML.
7371 (= 1 (logand 1 (- (point)
7372 (save-excursion
7373 (forward-char -1)
7374 (skip-syntax-backward "/\\")
7375 (point))))))
7376 (funcall blink-paren-function)))
7377
7378 (put 'blink-paren-post-self-insert-function 'priority 100)
7379
7380 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
7381 ;; Most likely, this hook is nil, so this arg doesn't matter,
7382 ;; but I use it as a reminder that this function usually
7383 ;; likes to be run after others since it does
7384 ;; `sit-for'. That's also the reason it get a `priority' prop
7385 ;; of 100.
7386 'append)
7387 \f
7388 ;; This executes C-g typed while Emacs is waiting for a command.
7389 ;; Quitting out of a program does not go through here;
7390 ;; that happens in the QUIT macro at the C code level.
7391 (defun keyboard-quit ()
7392 "Signal a `quit' condition.
7393 During execution of Lisp code, this character causes a quit directly.
7394 At top-level, as an editor command, this simply beeps."
7395 (interactive)
7396 ;; Avoid adding the region to the window selection.
7397 (setq saved-region-selection nil)
7398 (let (select-active-regions)
7399 (deactivate-mark))
7400 (if (fboundp 'kmacro-keyboard-quit)
7401 (kmacro-keyboard-quit))
7402 (when completion-in-region-mode
7403 (completion-in-region-mode -1))
7404 ;; Force the next redisplay cycle to remove the "Def" indicator from
7405 ;; all the mode lines.
7406 (if defining-kbd-macro
7407 (force-mode-line-update t))
7408 (setq defining-kbd-macro nil)
7409 (let ((debug-on-quit nil))
7410 (signal 'quit nil)))
7411
7412 (defvar buffer-quit-function nil
7413 "Function to call to \"quit\" the current buffer, or nil if none.
7414 \\[keyboard-escape-quit] calls this function when its more local actions
7415 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
7416
7417 (defun keyboard-escape-quit ()
7418 "Exit the current \"mode\" (in a generalized sense of the word).
7419 This command can exit an interactive command such as `query-replace',
7420 can clear out a prefix argument or a region,
7421 can get out of the minibuffer or other recursive edit,
7422 cancel the use of the current buffer (for special-purpose buffers),
7423 or go back to just one window (by deleting all but the selected window)."
7424 (interactive)
7425 (cond ((eq last-command 'mode-exited) nil)
7426 ((region-active-p)
7427 (deactivate-mark))
7428 ((> (minibuffer-depth) 0)
7429 (abort-recursive-edit))
7430 (current-prefix-arg
7431 nil)
7432 ((> (recursion-depth) 0)
7433 (exit-recursive-edit))
7434 (buffer-quit-function
7435 (funcall buffer-quit-function))
7436 ((not (one-window-p t))
7437 (delete-other-windows))
7438 ((string-match "^ \\*" (buffer-name (current-buffer)))
7439 (bury-buffer))))
7440
7441 (defun play-sound-file (file &optional volume device)
7442 "Play sound stored in FILE.
7443 VOLUME and DEVICE correspond to the keywords of the sound
7444 specification for `play-sound'."
7445 (interactive "fPlay sound file: ")
7446 (let ((sound (list :file file)))
7447 (if volume
7448 (plist-put sound :volume volume))
7449 (if device
7450 (plist-put sound :device device))
7451 (push 'sound sound)
7452 (play-sound sound)))
7453
7454 \f
7455 (defcustom read-mail-command 'rmail
7456 "Your preference for a mail reading package.
7457 This is used by some keybindings which support reading mail.
7458 See also `mail-user-agent' concerning sending mail."
7459 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
7460 (function-item :tag "Gnus" :format "%t\n" gnus)
7461 (function-item :tag "Emacs interface to MH"
7462 :format "%t\n" mh-rmail)
7463 (function :tag "Other"))
7464 :version "21.1"
7465 :group 'mail)
7466
7467 (defcustom mail-user-agent 'message-user-agent
7468 "Your preference for a mail composition package.
7469 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
7470 outgoing email message. This variable lets you specify which
7471 mail-sending package you prefer.
7472
7473 Valid values include:
7474
7475 `message-user-agent' -- use the Message package.
7476 See Info node `(message)'.
7477 `sendmail-user-agent' -- use the Mail package.
7478 See Info node `(emacs)Sending Mail'.
7479 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
7480 See Info node `(mh-e)'.
7481 `gnus-user-agent' -- like `message-user-agent', but with Gnus
7482 paraphernalia if Gnus is running, particularly
7483 the Gcc: header for archiving.
7484
7485 Additional valid symbols may be available; check with the author of
7486 your package for details. The function should return non-nil if it
7487 succeeds.
7488
7489 See also `read-mail-command' concerning reading mail."
7490 :type '(radio (function-item :tag "Message package"
7491 :format "%t\n"
7492 message-user-agent)
7493 (function-item :tag "Mail package"
7494 :format "%t\n"
7495 sendmail-user-agent)
7496 (function-item :tag "Emacs interface to MH"
7497 :format "%t\n"
7498 mh-e-user-agent)
7499 (function-item :tag "Message with full Gnus features"
7500 :format "%t\n"
7501 gnus-user-agent)
7502 (function :tag "Other"))
7503 :version "23.2" ; sendmail->message
7504 :group 'mail)
7505
7506 (defcustom compose-mail-user-agent-warnings t
7507 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
7508 If the value of `mail-user-agent' is the default, and the user
7509 appears to have customizations applying to the old default,
7510 `compose-mail' issues a warning."
7511 :type 'boolean
7512 :version "23.2"
7513 :group 'mail)
7514
7515 (defun rfc822-goto-eoh ()
7516 "If the buffer starts with a mail header, move point to the header's end.
7517 Otherwise, moves to `point-min'.
7518 The end of the header is the start of the next line, if there is one,
7519 else the end of the last line. This function obeys RFC822."
7520 (goto-char (point-min))
7521 (when (re-search-forward
7522 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
7523 (goto-char (match-beginning 0))))
7524
7525 ;; Used by Rmail (e.g., rmail-forward).
7526 (defvar mail-encode-mml nil
7527 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
7528 the outgoing message before sending it.")
7529
7530 (defun compose-mail (&optional to subject other-headers continue
7531 switch-function yank-action send-actions
7532 return-action)
7533 "Start composing a mail message to send.
7534 This uses the user's chosen mail composition package
7535 as selected with the variable `mail-user-agent'.
7536 The optional arguments TO and SUBJECT specify recipients
7537 and the initial Subject field, respectively.
7538
7539 OTHER-HEADERS is an alist specifying additional
7540 header fields. Elements look like (HEADER . VALUE) where both
7541 HEADER and VALUE are strings.
7542
7543 CONTINUE, if non-nil, says to continue editing a message already
7544 being composed. Interactively, CONTINUE is the prefix argument.
7545
7546 SWITCH-FUNCTION, if non-nil, is a function to use to
7547 switch to and display the buffer used for mail composition.
7548
7549 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
7550 to insert the raw text of the message being replied to.
7551 It has the form (FUNCTION . ARGS). The user agent will apply
7552 FUNCTION to ARGS, to insert the raw text of the original message.
7553 \(The user agent will also run `mail-citation-hook', *after* the
7554 original text has been inserted in this way.)
7555
7556 SEND-ACTIONS is a list of actions to call when the message is sent.
7557 Each action has the form (FUNCTION . ARGS).
7558
7559 RETURN-ACTION, if non-nil, is an action for returning to the
7560 caller. It has the form (FUNCTION . ARGS). The function is
7561 called after the mail has been sent or put aside, and the mail
7562 buffer buried."
7563 (interactive
7564 (list nil nil nil current-prefix-arg))
7565
7566 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
7567 ;; from sendmail-user-agent to message-user-agent. Some users may
7568 ;; encounter incompatibilities. This hack tries to detect problems
7569 ;; and warn about them.
7570 (and compose-mail-user-agent-warnings
7571 (eq mail-user-agent 'message-user-agent)
7572 (let (warn-vars)
7573 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
7574 mail-yank-hooks mail-archive-file-name
7575 mail-default-reply-to mail-mailing-lists
7576 mail-self-blind))
7577 (and (boundp var)
7578 (symbol-value var)
7579 (push var warn-vars)))
7580 (when warn-vars
7581 (display-warning 'mail
7582 (format-message "\
7583 The default mail mode is now Message mode.
7584 You have the following Mail mode variable%s customized:
7585 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7586 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
7587 (if (> (length warn-vars) 1) "s" "")
7588 (mapconcat 'symbol-name
7589 warn-vars " "))))))
7590
7591 (let ((function (get mail-user-agent 'composefunc)))
7592 (funcall function to subject other-headers continue switch-function
7593 yank-action send-actions return-action)))
7594
7595 (defun compose-mail-other-window (&optional to subject other-headers continue
7596 yank-action send-actions
7597 return-action)
7598 "Like \\[compose-mail], but edit the outgoing message in another window."
7599 (interactive (list nil nil nil current-prefix-arg))
7600 (compose-mail to subject other-headers continue
7601 'switch-to-buffer-other-window yank-action send-actions
7602 return-action))
7603
7604 (defun compose-mail-other-frame (&optional to subject other-headers continue
7605 yank-action send-actions
7606 return-action)
7607 "Like \\[compose-mail], but edit the outgoing message in another frame."
7608 (interactive (list nil nil nil current-prefix-arg))
7609 (compose-mail to subject other-headers continue
7610 'switch-to-buffer-other-frame yank-action send-actions
7611 return-action))
7612
7613 \f
7614 (defvar set-variable-value-history nil
7615 "History of values entered with `set-variable'.
7616
7617 Maximum length of the history list is determined by the value
7618 of `history-length', which see.")
7619
7620 (defun set-variable (variable value &optional make-local)
7621 "Set VARIABLE to VALUE. VALUE is a Lisp object.
7622 VARIABLE should be a user option variable name, a Lisp variable
7623 meant to be customized by users. You should enter VALUE in Lisp syntax,
7624 so if you want VALUE to be a string, you must surround it with doublequotes.
7625 VALUE is used literally, not evaluated.
7626
7627 If VARIABLE has a `variable-interactive' property, that is used as if
7628 it were the arg to `interactive' (which see) to interactively read VALUE.
7629
7630 If VARIABLE has been defined with `defcustom', then the type information
7631 in the definition is used to check that VALUE is valid.
7632
7633 Note that this function is at heart equivalent to the basic `set' function.
7634 For a variable defined with `defcustom', it does not pay attention to
7635 any :set property that the variable might have (if you want that, use
7636 \\[customize-set-variable] instead).
7637
7638 With a prefix argument, set VARIABLE to VALUE buffer-locally."
7639 (interactive
7640 (let* ((default-var (variable-at-point))
7641 (var (if (custom-variable-p default-var)
7642 (read-variable (format "Set variable (default %s): " default-var)
7643 default-var)
7644 (read-variable "Set variable: ")))
7645 (minibuffer-help-form '(describe-variable var))
7646 (prop (get var 'variable-interactive))
7647 (obsolete (car (get var 'byte-obsolete-variable)))
7648 (prompt (format "Set %s %s to value: " var
7649 (cond ((local-variable-p var)
7650 "(buffer-local)")
7651 ((or current-prefix-arg
7652 (local-variable-if-set-p var))
7653 "buffer-locally")
7654 (t "globally"))))
7655 (val (progn
7656 (when obsolete
7657 (message (concat "`%S' is obsolete; "
7658 (if (symbolp obsolete) "use `%S' instead" "%s"))
7659 var obsolete)
7660 (sit-for 3))
7661 (if prop
7662 ;; Use VAR's `variable-interactive' property
7663 ;; as an interactive spec for prompting.
7664 (call-interactively `(lambda (arg)
7665 (interactive ,prop)
7666 arg))
7667 (read-from-minibuffer prompt nil
7668 read-expression-map t
7669 'set-variable-value-history
7670 (format "%S" (symbol-value var)))))))
7671 (list var val current-prefix-arg)))
7672
7673 (and (custom-variable-p variable)
7674 (not (get variable 'custom-type))
7675 (custom-load-symbol variable))
7676 (let ((type (get variable 'custom-type)))
7677 (when type
7678 ;; Match with custom type.
7679 (require 'cus-edit)
7680 (setq type (widget-convert type))
7681 (unless (widget-apply type :match value)
7682 (user-error "Value `%S' does not match type %S of %S"
7683 value (car type) variable))))
7684
7685 (if make-local
7686 (make-local-variable variable))
7687
7688 (set variable value)
7689
7690 ;; Force a thorough redisplay for the case that the variable
7691 ;; has an effect on the display, like `tab-width' has.
7692 (force-mode-line-update))
7693 \f
7694 ;; Define the major mode for lists of completions.
7695
7696 (defvar completion-list-mode-map
7697 (let ((map (make-sparse-keymap)))
7698 (define-key map [mouse-2] 'choose-completion)
7699 (define-key map [follow-link] 'mouse-face)
7700 (define-key map [down-mouse-2] nil)
7701 (define-key map "\C-m" 'choose-completion)
7702 (define-key map "\e\e\e" 'delete-completion-window)
7703 (define-key map [left] 'previous-completion)
7704 (define-key map [right] 'next-completion)
7705 (define-key map [?\t] 'next-completion)
7706 (define-key map [backtab] 'previous-completion)
7707 (define-key map "q" 'quit-window)
7708 (define-key map "z" 'kill-this-buffer)
7709 map)
7710 "Local map for completion list buffers.")
7711
7712 ;; Completion mode is suitable only for specially formatted data.
7713 (put 'completion-list-mode 'mode-class 'special)
7714
7715 (defvar completion-reference-buffer nil
7716 "Record the buffer that was current when the completion list was requested.
7717 This is a local variable in the completion list buffer.
7718 Initial value is nil to avoid some compiler warnings.")
7719
7720 (defvar completion-no-auto-exit nil
7721 "Non-nil means `choose-completion-string' should never exit the minibuffer.
7722 This also applies to other functions such as `choose-completion'.")
7723
7724 (defvar completion-base-position nil
7725 "Position of the base of the text corresponding to the shown completions.
7726 This variable is used in the *Completions* buffers.
7727 Its value is a list of the form (START END) where START is the place
7728 where the completion should be inserted and END (if non-nil) is the end
7729 of the text to replace. If END is nil, point is used instead.")
7730
7731 (defvar completion-list-insert-choice-function #'completion--replace
7732 "Function to use to insert the text chosen in *Completions*.
7733 Called with three arguments (BEG END TEXT), it should replace the text
7734 between BEG and END with TEXT. Expected to be set buffer-locally
7735 in the *Completions* buffer.")
7736
7737 (defvar completion-base-size nil
7738 "Number of chars before point not involved in completion.
7739 This is a local variable in the completion list buffer.
7740 It refers to the chars in the minibuffer if completing in the
7741 minibuffer, or in `completion-reference-buffer' otherwise.
7742 Only characters in the field at point are included.
7743
7744 If nil, Emacs determines which part of the tail end of the
7745 buffer's text is involved in completion by comparing the text
7746 directly.")
7747 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
7748
7749 (defun delete-completion-window ()
7750 "Delete the completion list window.
7751 Go to the window from which completion was requested."
7752 (interactive)
7753 (let ((buf completion-reference-buffer))
7754 (if (one-window-p t)
7755 (if (window-dedicated-p) (delete-frame))
7756 (delete-window (selected-window))
7757 (if (get-buffer-window buf)
7758 (select-window (get-buffer-window buf))))))
7759
7760 (defun previous-completion (n)
7761 "Move to the previous item in the completion list."
7762 (interactive "p")
7763 (next-completion (- n)))
7764
7765 (defun next-completion (n)
7766 "Move to the next item in the completion list.
7767 With prefix argument N, move N items (negative N means move backward)."
7768 (interactive "p")
7769 (let ((beg (point-min)) (end (point-max)))
7770 (while (and (> n 0) (not (eobp)))
7771 ;; If in a completion, move to the end of it.
7772 (when (get-text-property (point) 'mouse-face)
7773 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7774 ;; Move to start of next one.
7775 (unless (get-text-property (point) 'mouse-face)
7776 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
7777 (setq n (1- n)))
7778 (while (and (< n 0) (not (bobp)))
7779 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
7780 ;; If in a completion, move to the start of it.
7781 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
7782 (goto-char (previous-single-property-change
7783 (point) 'mouse-face nil beg)))
7784 ;; Move to end of the previous completion.
7785 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7786 (goto-char (previous-single-property-change
7787 (point) 'mouse-face nil beg)))
7788 ;; Move to the start of that one.
7789 (goto-char (previous-single-property-change
7790 (point) 'mouse-face nil beg))
7791 (setq n (1+ n))))))
7792
7793 (defun choose-completion (&optional event)
7794 "Choose the completion at point.
7795 If EVENT, use EVENT's position to determine the starting position."
7796 (interactive (list last-nonmenu-event))
7797 ;; In case this is run via the mouse, give temporary modes such as
7798 ;; isearch a chance to turn off.
7799 (run-hooks 'mouse-leave-buffer-hook)
7800 (with-current-buffer (window-buffer (posn-window (event-start event)))
7801 (let ((buffer completion-reference-buffer)
7802 (base-size completion-base-size)
7803 (base-position completion-base-position)
7804 (insert-function completion-list-insert-choice-function)
7805 (choice
7806 (save-excursion
7807 (goto-char (posn-point (event-start event)))
7808 (let (beg end)
7809 (cond
7810 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7811 (setq end (point) beg (1+ (point))))
7812 ((and (not (bobp))
7813 (get-text-property (1- (point)) 'mouse-face))
7814 (setq end (1- (point)) beg (point)))
7815 (t (error "No completion here")))
7816 (setq beg (previous-single-property-change beg 'mouse-face))
7817 (setq end (or (next-single-property-change end 'mouse-face)
7818 (point-max)))
7819 (buffer-substring-no-properties beg end)))))
7820
7821 (unless (buffer-live-p buffer)
7822 (error "Destination buffer is dead"))
7823 (quit-window nil (posn-window (event-start event)))
7824
7825 (with-current-buffer buffer
7826 (choose-completion-string
7827 choice buffer
7828 (or base-position
7829 (when base-size
7830 ;; Someone's using old completion code that doesn't know
7831 ;; about base-position yet.
7832 (list (+ base-size (field-beginning))))
7833 ;; If all else fails, just guess.
7834 (list (choose-completion-guess-base-position choice)))
7835 insert-function)))))
7836
7837 ;; Delete the longest partial match for STRING
7838 ;; that can be found before POINT.
7839 (defun choose-completion-guess-base-position (string)
7840 (save-excursion
7841 (let ((opoint (point))
7842 len)
7843 ;; Try moving back by the length of the string.
7844 (goto-char (max (- (point) (length string))
7845 (minibuffer-prompt-end)))
7846 ;; See how far back we were actually able to move. That is the
7847 ;; upper bound on how much we can match and delete.
7848 (setq len (- opoint (point)))
7849 (if completion-ignore-case
7850 (setq string (downcase string)))
7851 (while (and (> len 0)
7852 (let ((tail (buffer-substring (point) opoint)))
7853 (if completion-ignore-case
7854 (setq tail (downcase tail)))
7855 (not (string= tail (substring string 0 len)))))
7856 (setq len (1- len))
7857 (forward-char 1))
7858 (point))))
7859
7860 (defun choose-completion-delete-max-match (string)
7861 (declare (obsolete choose-completion-guess-base-position "23.2"))
7862 (delete-region (choose-completion-guess-base-position string) (point)))
7863
7864 (defvar choose-completion-string-functions nil
7865 "Functions that may override the normal insertion of a completion choice.
7866 These functions are called in order with three arguments:
7867 CHOICE - the string to insert in the buffer,
7868 BUFFER - the buffer in which the choice should be inserted,
7869 BASE-POSITION - where to insert the completion.
7870
7871 If a function in the list returns non-nil, that function is supposed
7872 to have inserted the CHOICE in the BUFFER, and possibly exited
7873 the minibuffer; no further functions will be called.
7874
7875 If all functions in the list return nil, that means to use
7876 the default method of inserting the completion in BUFFER.")
7877
7878 (defun choose-completion-string (choice &optional
7879 buffer base-position insert-function)
7880 "Switch to BUFFER and insert the completion choice CHOICE.
7881 BASE-POSITION says where to insert the completion.
7882 INSERT-FUNCTION says how to insert the completion and falls
7883 back on `completion-list-insert-choice-function' when nil."
7884
7885 ;; If BUFFER is the minibuffer, exit the minibuffer
7886 ;; unless it is reading a file name and CHOICE is a directory,
7887 ;; or completion-no-auto-exit is non-nil.
7888
7889 ;; Some older code may call us passing `base-size' instead of
7890 ;; `base-position'. It's difficult to make any use of `base-size',
7891 ;; so we just ignore it.
7892 (unless (consp base-position)
7893 (message "Obsolete `base-size' passed to choose-completion-string")
7894 (setq base-position nil))
7895
7896 (let* ((buffer (or buffer completion-reference-buffer))
7897 (mini-p (minibufferp buffer)))
7898 ;; If BUFFER is a minibuffer, barf unless it's the currently
7899 ;; active minibuffer.
7900 (if (and mini-p
7901 (not (and (active-minibuffer-window)
7902 (equal buffer
7903 (window-buffer (active-minibuffer-window))))))
7904 (error "Minibuffer is not active for completion")
7905 ;; Set buffer so buffer-local choose-completion-string-functions works.
7906 (set-buffer buffer)
7907 (unless (run-hook-with-args-until-success
7908 'choose-completion-string-functions
7909 ;; The fourth arg used to be `mini-p' but was useless
7910 ;; (since minibufferp can be used on the `buffer' arg)
7911 ;; and indeed unused. The last used to be `base-size', so we
7912 ;; keep it to try and avoid breaking old code.
7913 choice buffer base-position nil)
7914 ;; This remove-text-properties should be unnecessary since `choice'
7915 ;; comes from buffer-substring-no-properties.
7916 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7917 ;; Insert the completion into the buffer where it was requested.
7918 (funcall (or insert-function completion-list-insert-choice-function)
7919 (or (car base-position) (point))
7920 (or (cadr base-position) (point))
7921 choice)
7922 ;; Update point in the window that BUFFER is showing in.
7923 (let ((window (get-buffer-window buffer t)))
7924 (set-window-point window (point)))
7925 ;; If completing for the minibuffer, exit it with this choice.
7926 (and (not completion-no-auto-exit)
7927 (minibufferp buffer)
7928 minibuffer-completion-table
7929 ;; If this is reading a file name, and the file name chosen
7930 ;; is a directory, don't exit the minibuffer.
7931 (let* ((result (buffer-substring (field-beginning) (point)))
7932 (bounds
7933 (completion-boundaries result minibuffer-completion-table
7934 minibuffer-completion-predicate
7935 "")))
7936 (if (eq (car bounds) (length result))
7937 ;; The completion chosen leads to a new set of completions
7938 ;; (e.g. it's a directory): don't exit the minibuffer yet.
7939 (let ((mini (active-minibuffer-window)))
7940 (select-window mini)
7941 (when minibuffer-auto-raise
7942 (raise-frame (window-frame mini))))
7943 (exit-minibuffer))))))))
7944
7945 (define-derived-mode completion-list-mode nil "Completion List"
7946 "Major mode for buffers showing lists of possible completions.
7947 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
7948 to select the completion near point.
7949 Or click to select one with the mouse.
7950
7951 \\{completion-list-mode-map}"
7952 (set (make-local-variable 'completion-base-size) nil))
7953
7954 (defun completion-list-mode-finish ()
7955 "Finish setup of the completions buffer.
7956 Called from `temp-buffer-show-hook'."
7957 (when (eq major-mode 'completion-list-mode)
7958 (setq buffer-read-only t)))
7959
7960 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
7961
7962
7963 ;; Variables and faces used in `completion-setup-function'.
7964
7965 (defcustom completion-show-help t
7966 "Non-nil means show help message in *Completions* buffer."
7967 :type 'boolean
7968 :version "22.1"
7969 :group 'completion)
7970
7971 ;; This function goes in completion-setup-hook, so that it is called
7972 ;; after the text of the completion list buffer is written.
7973 (defun completion-setup-function ()
7974 (let* ((mainbuf (current-buffer))
7975 (base-dir
7976 ;; FIXME: This is a bad hack. We try to set the default-directory
7977 ;; in the *Completions* buffer so that the relative file names
7978 ;; displayed there can be treated as valid file names, independently
7979 ;; from the completion context. But this suffers from many problems:
7980 ;; - It's not clear when the completions are file names. With some
7981 ;; completion tables (e.g. bzr revision specs), the listed
7982 ;; completions can mix file names and other things.
7983 ;; - It doesn't pay attention to possible quoting.
7984 ;; - With fancy completion styles, the code below will not always
7985 ;; find the right base directory.
7986 (if minibuffer-completing-file-name
7987 (file-name-as-directory
7988 (expand-file-name
7989 (buffer-substring (minibuffer-prompt-end)
7990 (- (point) (or completion-base-size 0))))))))
7991 (with-current-buffer standard-output
7992 (let ((base-size completion-base-size) ;Read before killing localvars.
7993 (base-position completion-base-position)
7994 (insert-fun completion-list-insert-choice-function))
7995 (completion-list-mode)
7996 (set (make-local-variable 'completion-base-size) base-size)
7997 (set (make-local-variable 'completion-base-position) base-position)
7998 (set (make-local-variable 'completion-list-insert-choice-function)
7999 insert-fun))
8000 (set (make-local-variable 'completion-reference-buffer) mainbuf)
8001 (if base-dir (setq default-directory base-dir))
8002 ;; Maybe insert help string.
8003 (when completion-show-help
8004 (goto-char (point-min))
8005 (if (display-mouse-p)
8006 (insert "Click on a completion to select it.\n"))
8007 (insert (substitute-command-keys
8008 "In this buffer, type \\[choose-completion] to \
8009 select the completion near point.\n\n"))))))
8010
8011 (add-hook 'completion-setup-hook 'completion-setup-function)
8012
8013 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
8014 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
8015
8016 (defun switch-to-completions ()
8017 "Select the completion list window."
8018 (interactive)
8019 (let ((window (or (get-buffer-window "*Completions*" 0)
8020 ;; Make sure we have a completions window.
8021 (progn (minibuffer-completion-help)
8022 (get-buffer-window "*Completions*" 0)))))
8023 (when window
8024 (select-window window)
8025 ;; In the new buffer, go to the first completion.
8026 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
8027 (when (bobp)
8028 (next-completion 1)))))
8029 \f
8030 ;;; Support keyboard commands to turn on various modifiers.
8031
8032 ;; These functions -- which are not commands -- each add one modifier
8033 ;; to the following event.
8034
8035 (defun event-apply-alt-modifier (_ignore-prompt)
8036 "\\<function-key-map>Add the Alt modifier to the following event.
8037 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
8038 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
8039 (defun event-apply-super-modifier (_ignore-prompt)
8040 "\\<function-key-map>Add the Super modifier to the following event.
8041 For example, type \\[event-apply-super-modifier] & to enter Super-&."
8042 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
8043 (defun event-apply-hyper-modifier (_ignore-prompt)
8044 "\\<function-key-map>Add the Hyper modifier to the following event.
8045 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
8046 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
8047 (defun event-apply-shift-modifier (_ignore-prompt)
8048 "\\<function-key-map>Add the Shift modifier to the following event.
8049 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
8050 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
8051 (defun event-apply-control-modifier (_ignore-prompt)
8052 "\\<function-key-map>Add the Ctrl modifier to the following event.
8053 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
8054 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
8055 (defun event-apply-meta-modifier (_ignore-prompt)
8056 "\\<function-key-map>Add the Meta modifier to the following event.
8057 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
8058 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
8059
8060 (defun event-apply-modifier (event symbol lshiftby prefix)
8061 "Apply a modifier flag to event EVENT.
8062 SYMBOL is the name of this modifier, as a symbol.
8063 LSHIFTBY is the numeric value of this modifier, in keyboard events.
8064 PREFIX is the string that represents this modifier in an event type symbol."
8065 (if (numberp event)
8066 (cond ((eq symbol 'control)
8067 (if (and (<= (downcase event) ?z)
8068 (>= (downcase event) ?a))
8069 (- (downcase event) ?a -1)
8070 (if (and (<= (downcase event) ?Z)
8071 (>= (downcase event) ?A))
8072 (- (downcase event) ?A -1)
8073 (logior (lsh 1 lshiftby) event))))
8074 ((eq symbol 'shift)
8075 (if (and (<= (downcase event) ?z)
8076 (>= (downcase event) ?a))
8077 (upcase event)
8078 (logior (lsh 1 lshiftby) event)))
8079 (t
8080 (logior (lsh 1 lshiftby) event)))
8081 (if (memq symbol (event-modifiers event))
8082 event
8083 (let ((event-type (if (symbolp event) event (car event))))
8084 (setq event-type (intern (concat prefix (symbol-name event-type))))
8085 (if (symbolp event)
8086 event-type
8087 (cons event-type (cdr event)))))))
8088
8089 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
8090 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
8091 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
8092 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
8093 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
8094 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
8095 \f
8096 ;;;; Keypad support.
8097
8098 ;; Make the keypad keys act like ordinary typing keys. If people add
8099 ;; bindings for the function key symbols, then those bindings will
8100 ;; override these, so this shouldn't interfere with any existing
8101 ;; bindings.
8102
8103 ;; Also tell read-char how to handle these keys.
8104 (mapc
8105 (lambda (keypad-normal)
8106 (let ((keypad (nth 0 keypad-normal))
8107 (normal (nth 1 keypad-normal)))
8108 (put keypad 'ascii-character normal)
8109 (define-key function-key-map (vector keypad) (vector normal))))
8110 ;; See also kp-keys bound in bindings.el.
8111 '((kp-space ?\s)
8112 (kp-tab ?\t)
8113 (kp-enter ?\r)
8114 (kp-separator ?,)
8115 (kp-equal ?=)
8116 ;; Do the same for various keys that are represented as symbols under
8117 ;; GUIs but naturally correspond to characters.
8118 (backspace 127)
8119 (delete 127)
8120 (tab ?\t)
8121 (linefeed ?\n)
8122 (clear ?\C-l)
8123 (return ?\C-m)
8124 (escape ?\e)
8125 ))
8126 \f
8127 ;;;;
8128 ;;;; forking a twin copy of a buffer.
8129 ;;;;
8130
8131 (defvar clone-buffer-hook nil
8132 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
8133
8134 (defvar clone-indirect-buffer-hook nil
8135 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
8136
8137 (defun clone-process (process &optional newname)
8138 "Create a twin copy of PROCESS.
8139 If NEWNAME is nil, it defaults to PROCESS' name;
8140 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
8141 If PROCESS is associated with a buffer, the new process will be associated
8142 with the current buffer instead.
8143 Returns nil if PROCESS has already terminated."
8144 (setq newname (or newname (process-name process)))
8145 (if (string-match "<[0-9]+>\\'" newname)
8146 (setq newname (substring newname 0 (match-beginning 0))))
8147 (when (memq (process-status process) '(run stop open))
8148 (let* ((process-connection-type (process-tty-name process))
8149 (new-process
8150 (if (memq (process-status process) '(open))
8151 (let ((args (process-contact process t)))
8152 (setq args (plist-put args :name newname))
8153 (setq args (plist-put args :buffer
8154 (if (process-buffer process)
8155 (current-buffer))))
8156 (apply 'make-network-process args))
8157 (apply 'start-process newname
8158 (if (process-buffer process) (current-buffer))
8159 (process-command process)))))
8160 (set-process-query-on-exit-flag
8161 new-process (process-query-on-exit-flag process))
8162 (set-process-inherit-coding-system-flag
8163 new-process (process-inherit-coding-system-flag process))
8164 (set-process-filter new-process (process-filter process))
8165 (set-process-sentinel new-process (process-sentinel process))
8166 (set-process-plist new-process (copy-sequence (process-plist process)))
8167 new-process)))
8168
8169 ;; things to maybe add (currently partly covered by `funcall mode'):
8170 ;; - syntax-table
8171 ;; - overlays
8172 (defun clone-buffer (&optional newname display-flag)
8173 "Create and return a twin copy of the current buffer.
8174 Unlike an indirect buffer, the new buffer can be edited
8175 independently of the old one (if it is not read-only).
8176 NEWNAME is the name of the new buffer. It may be modified by
8177 adding or incrementing <N> at the end as necessary to create a
8178 unique buffer name. If nil, it defaults to the name of the
8179 current buffer, with the proper suffix. If DISPLAY-FLAG is
8180 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
8181 clone a file-visiting buffer, or a buffer whose major mode symbol
8182 has a non-nil `no-clone' property, results in an error.
8183
8184 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
8185 current buffer with appropriate suffix. However, if a prefix
8186 argument is given, then the command prompts for NEWNAME in the
8187 minibuffer.
8188
8189 This runs the normal hook `clone-buffer-hook' in the new buffer
8190 after it has been set up properly in other respects."
8191 (interactive
8192 (progn
8193 (if buffer-file-name
8194 (error "Cannot clone a file-visiting buffer"))
8195 (if (get major-mode 'no-clone)
8196 (error "Cannot clone a buffer in %s mode" mode-name))
8197 (list (if current-prefix-arg
8198 (read-buffer "Name of new cloned buffer: " (current-buffer)))
8199 t)))
8200 (if buffer-file-name
8201 (error "Cannot clone a file-visiting buffer"))
8202 (if (get major-mode 'no-clone)
8203 (error "Cannot clone a buffer in %s mode" mode-name))
8204 (setq newname (or newname (buffer-name)))
8205 (if (string-match "<[0-9]+>\\'" newname)
8206 (setq newname (substring newname 0 (match-beginning 0))))
8207 (let ((buf (current-buffer))
8208 (ptmin (point-min))
8209 (ptmax (point-max))
8210 (pt (point))
8211 (mk (if mark-active (mark t)))
8212 (modified (buffer-modified-p))
8213 (mode major-mode)
8214 (lvars (buffer-local-variables))
8215 (process (get-buffer-process (current-buffer)))
8216 (new (generate-new-buffer (or newname (buffer-name)))))
8217 (save-restriction
8218 (widen)
8219 (with-current-buffer new
8220 (insert-buffer-substring buf)))
8221 (with-current-buffer new
8222 (narrow-to-region ptmin ptmax)
8223 (goto-char pt)
8224 (if mk (set-mark mk))
8225 (set-buffer-modified-p modified)
8226
8227 ;; Clone the old buffer's process, if any.
8228 (when process (clone-process process))
8229
8230 ;; Now set up the major mode.
8231 (funcall mode)
8232
8233 ;; Set up other local variables.
8234 (mapc (lambda (v)
8235 (condition-case () ;in case var is read-only
8236 (if (symbolp v)
8237 (makunbound v)
8238 (set (make-local-variable (car v)) (cdr v)))
8239 (error nil)))
8240 lvars)
8241
8242 ;; Run any hooks (typically set up by the major mode
8243 ;; for cloning to work properly).
8244 (run-hooks 'clone-buffer-hook))
8245 (if display-flag
8246 ;; Presumably the current buffer is shown in the selected frame, so
8247 ;; we want to display the clone elsewhere.
8248 (let ((same-window-regexps nil)
8249 (same-window-buffer-names))
8250 (pop-to-buffer new)))
8251 new))
8252
8253
8254 (defun clone-indirect-buffer (newname display-flag &optional norecord)
8255 "Create an indirect buffer that is a twin copy of the current buffer.
8256
8257 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
8258 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
8259 or if not called with a prefix arg, NEWNAME defaults to the current
8260 buffer's name. The name is modified by adding a `<N>' suffix to it
8261 or by incrementing the N in an existing suffix. Trying to clone a
8262 buffer whose major mode symbol has a non-nil `no-clone-indirect'
8263 property results in an error.
8264
8265 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
8266 This is always done when called interactively.
8267
8268 Optional third arg NORECORD non-nil means do not put this buffer at the
8269 front of the list of recently selected ones.
8270
8271 Returns the newly created indirect buffer."
8272 (interactive
8273 (progn
8274 (if (get major-mode 'no-clone-indirect)
8275 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8276 (list (if current-prefix-arg
8277 (read-buffer "Name of indirect buffer: " (current-buffer)))
8278 t)))
8279 (if (get major-mode 'no-clone-indirect)
8280 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8281 (setq newname (or newname (buffer-name)))
8282 (if (string-match "<[0-9]+>\\'" newname)
8283 (setq newname (substring newname 0 (match-beginning 0))))
8284 (let* ((name (generate-new-buffer-name newname))
8285 (buffer (make-indirect-buffer (current-buffer) name t)))
8286 (with-current-buffer buffer
8287 (run-hooks 'clone-indirect-buffer-hook))
8288 (when display-flag
8289 (pop-to-buffer buffer norecord))
8290 buffer))
8291
8292
8293 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
8294 "Like `clone-indirect-buffer' but display in another window."
8295 (interactive
8296 (progn
8297 (if (get major-mode 'no-clone-indirect)
8298 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
8299 (list (if current-prefix-arg
8300 (read-buffer "Name of indirect buffer: " (current-buffer)))
8301 t)))
8302 (let ((pop-up-windows t))
8303 (clone-indirect-buffer newname display-flag norecord)))
8304
8305 \f
8306 ;;; Handling of Backspace and Delete keys.
8307
8308 (defcustom normal-erase-is-backspace 'maybe
8309 "Set the default behavior of the Delete and Backspace keys.
8310
8311 If set to t, Delete key deletes forward and Backspace key deletes
8312 backward.
8313
8314 If set to nil, both Delete and Backspace keys delete backward.
8315
8316 If set to `maybe' (which is the default), Emacs automatically
8317 selects a behavior. On window systems, the behavior depends on
8318 the keyboard used. If the keyboard has both a Backspace key and
8319 a Delete key, and both are mapped to their usual meanings, the
8320 option's default value is set to t, so that Backspace can be used
8321 to delete backward, and Delete can be used to delete forward.
8322
8323 If not running under a window system, customizing this option
8324 accomplishes a similar effect by mapping C-h, which is usually
8325 generated by the Backspace key, to DEL, and by mapping DEL to C-d
8326 via `keyboard-translate'. The former functionality of C-h is
8327 available on the F1 key. You should probably not use this
8328 setting if you don't have both Backspace, Delete and F1 keys.
8329
8330 Setting this variable with setq doesn't take effect. Programmatically,
8331 call `normal-erase-is-backspace-mode' (which see) instead."
8332 :type '(choice (const :tag "Off" nil)
8333 (const :tag "Maybe" maybe)
8334 (other :tag "On" t))
8335 :group 'editing-basics
8336 :version "21.1"
8337 :set (lambda (symbol value)
8338 ;; The fboundp is because of a problem with :set when
8339 ;; dumping Emacs. It doesn't really matter.
8340 (if (fboundp 'normal-erase-is-backspace-mode)
8341 (normal-erase-is-backspace-mode (or value 0))
8342 (set-default symbol value))))
8343
8344 (defun normal-erase-is-backspace-setup-frame (&optional frame)
8345 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
8346 (unless frame (setq frame (selected-frame)))
8347 (with-selected-frame frame
8348 (unless (terminal-parameter nil 'normal-erase-is-backspace)
8349 (normal-erase-is-backspace-mode
8350 (if (if (eq normal-erase-is-backspace 'maybe)
8351 (and (not noninteractive)
8352 (or (memq system-type '(ms-dos windows-nt))
8353 (memq window-system '(w32 ns))
8354 (and (memq window-system '(x))
8355 (fboundp 'x-backspace-delete-keys-p)
8356 (x-backspace-delete-keys-p))
8357 ;; If the terminal Emacs is running on has erase char
8358 ;; set to ^H, use the Backspace key for deleting
8359 ;; backward, and the Delete key for deleting forward.
8360 (and (null window-system)
8361 (eq tty-erase-char ?\^H))))
8362 normal-erase-is-backspace)
8363 1 0)))))
8364
8365 (define-minor-mode normal-erase-is-backspace-mode
8366 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
8367 With a prefix argument ARG, enable this feature if ARG is
8368 positive, and disable it otherwise. If called from Lisp, enable
8369 the mode if ARG is omitted or nil.
8370
8371 On window systems, when this mode is on, Delete is mapped to C-d
8372 and Backspace is mapped to DEL; when this mode is off, both
8373 Delete and Backspace are mapped to DEL. (The remapping goes via
8374 `local-function-key-map', so binding Delete or Backspace in the
8375 global or local keymap will override that.)
8376
8377 In addition, on window systems, the bindings of C-Delete, M-Delete,
8378 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
8379 the global keymap in accordance with the functionality of Delete and
8380 Backspace. For example, if Delete is remapped to C-d, which deletes
8381 forward, C-Delete is bound to `kill-word', but if Delete is remapped
8382 to DEL, which deletes backward, C-Delete is bound to
8383 `backward-kill-word'.
8384
8385 If not running on a window system, a similar effect is accomplished by
8386 remapping C-h (normally produced by the Backspace key) and DEL via
8387 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
8388 to C-d; if it's off, the keys are not remapped.
8389
8390 When not running on a window system, and this mode is turned on, the
8391 former functionality of C-h is available on the F1 key. You should
8392 probably not turn on this mode on a text-only terminal if you don't
8393 have both Backspace, Delete and F1 keys.
8394
8395 See also `normal-erase-is-backspace'."
8396 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
8397 . (lambda (v)
8398 (setf (terminal-parameter nil 'normal-erase-is-backspace)
8399 (if v 1 0))))
8400 (let ((enabled (eq 1 (terminal-parameter
8401 nil 'normal-erase-is-backspace))))
8402
8403 (cond ((or (memq window-system '(x w32 ns pc))
8404 (memq system-type '(ms-dos windows-nt)))
8405 (let ((bindings
8406 `(([M-delete] [M-backspace])
8407 ([C-M-delete] [C-M-backspace])
8408 ([?\e C-delete] [?\e C-backspace]))))
8409
8410 (if enabled
8411 (progn
8412 (define-key local-function-key-map [delete] [deletechar])
8413 (define-key local-function-key-map [kp-delete] [deletechar])
8414 (define-key local-function-key-map [backspace] [?\C-?])
8415 (dolist (b bindings)
8416 ;; Not sure if input-decode-map is really right, but
8417 ;; keyboard-translate-table (used below) only works
8418 ;; for integer events, and key-translation-table is
8419 ;; global (like the global-map, used earlier).
8420 (define-key input-decode-map (car b) nil)
8421 (define-key input-decode-map (cadr b) nil)))
8422 (define-key local-function-key-map [delete] [?\C-?])
8423 (define-key local-function-key-map [kp-delete] [?\C-?])
8424 (define-key local-function-key-map [backspace] [?\C-?])
8425 (dolist (b bindings)
8426 (define-key input-decode-map (car b) (cadr b))
8427 (define-key input-decode-map (cadr b) (car b))))))
8428 (t
8429 (if enabled
8430 (progn
8431 (keyboard-translate ?\C-h ?\C-?)
8432 (keyboard-translate ?\C-? ?\C-d))
8433 (keyboard-translate ?\C-h ?\C-h)
8434 (keyboard-translate ?\C-? ?\C-?))))
8435
8436 (if (called-interactively-p 'interactive)
8437 (message "Delete key deletes %s"
8438 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
8439 "forward" "backward")))))
8440 \f
8441 (defvar vis-mode-saved-buffer-invisibility-spec nil
8442 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
8443
8444 (define-minor-mode read-only-mode
8445 "Change whether the current buffer is read-only.
8446 With prefix argument ARG, make the buffer read-only if ARG is
8447 positive, otherwise make it writable. If buffer is read-only
8448 and `view-read-only' is non-nil, enter view mode.
8449
8450 Do not call this from a Lisp program unless you really intend to
8451 do the same thing as the \\[read-only-mode] command, including
8452 possibly enabling or disabling View mode. Also, note that this
8453 command works by setting the variable `buffer-read-only', which
8454 does not affect read-only regions caused by text properties. To
8455 ignore read-only status in a Lisp program (whether due to text
8456 properties or buffer state), bind `inhibit-read-only' temporarily
8457 to a non-nil value."
8458 :variable buffer-read-only
8459 (cond
8460 ((and (not buffer-read-only) view-mode)
8461 (View-exit-and-edit)
8462 (make-local-variable 'view-read-only)
8463 (setq view-read-only t)) ; Must leave view mode.
8464 ((and buffer-read-only view-read-only
8465 ;; If view-mode is already active, `view-mode-enter' is a nop.
8466 (not view-mode)
8467 (not (eq (get major-mode 'mode-class) 'special)))
8468 (view-mode-enter))))
8469
8470 (define-minor-mode visible-mode
8471 "Toggle making all invisible text temporarily visible (Visible mode).
8472 With a prefix argument ARG, enable Visible mode if ARG is
8473 positive, and disable it otherwise. If called from Lisp, enable
8474 the mode if ARG is omitted or nil.
8475
8476 This mode works by saving the value of `buffer-invisibility-spec'
8477 and setting it to nil."
8478 :lighter " Vis"
8479 :group 'editing-basics
8480 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
8481 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
8482 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
8483 (when visible-mode
8484 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
8485 buffer-invisibility-spec)
8486 (setq buffer-invisibility-spec nil)))
8487 \f
8488 (defvar messages-buffer-mode-map
8489 (let ((map (make-sparse-keymap)))
8490 (set-keymap-parent map special-mode-map)
8491 (define-key map "g" nil) ; nothing to revert
8492 map))
8493
8494 (define-derived-mode messages-buffer-mode special-mode "Messages"
8495 "Major mode used in the \"*Messages*\" buffer.")
8496
8497 (defun messages-buffer ()
8498 "Return the \"*Messages*\" buffer.
8499 If it does not exist, create and it switch it to `messages-buffer-mode'."
8500 (or (get-buffer "*Messages*")
8501 (with-current-buffer (get-buffer-create "*Messages*")
8502 (messages-buffer-mode)
8503 (current-buffer))))
8504
8505 \f
8506 ;; Minibuffer prompt stuff.
8507
8508 ;;(defun minibuffer-prompt-modification (start end)
8509 ;; (error "You cannot modify the prompt"))
8510 ;;
8511 ;;
8512 ;;(defun minibuffer-prompt-insertion (start end)
8513 ;; (let ((inhibit-modification-hooks t))
8514 ;; (delete-region start end)
8515 ;; ;; Discard undo information for the text insertion itself
8516 ;; ;; and for the text deletion.above.
8517 ;; (when (consp buffer-undo-list)
8518 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
8519 ;; (message "You cannot modify the prompt")))
8520 ;;
8521 ;;
8522 ;;(setq minibuffer-prompt-properties
8523 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
8524 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
8525
8526 \f
8527 ;;;; Problematic external packages.
8528
8529 ;; rms says this should be done by specifying symbols that define
8530 ;; versions together with bad values. This is therefore not as
8531 ;; flexible as it could be. See the thread:
8532 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
8533 (defconst bad-packages-alist
8534 ;; Not sure exactly which semantic versions have problems.
8535 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
8536 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
8537 "The version of `semantic' loaded does not work in Emacs 22.
8538 It can cause constant high CPU load.
8539 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
8540 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
8541 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
8542 ;; provided the `CUA-mode' feature. Since this is no longer true,
8543 ;; we can warn the user if the `CUA-mode' feature is ever provided.
8544 (CUA-mode t nil
8545 "CUA-mode is now part of the standard GNU Emacs distribution,
8546 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
8547
8548 You have loaded an older version of CUA-mode which does not work
8549 correctly with this version of Emacs. You should remove the old
8550 version and use the one distributed with Emacs."))
8551 "Alist of packages known to cause problems in this version of Emacs.
8552 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
8553 PACKAGE is either a regular expression to match file names, or a
8554 symbol (a feature name), like for `with-eval-after-load'.
8555 SYMBOL is either the name of a string variable, or t. Upon
8556 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
8557 warning using STRING as the message.")
8558
8559 (defun bad-package-check (package)
8560 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
8561 (condition-case nil
8562 (let* ((list (assoc package bad-packages-alist))
8563 (symbol (nth 1 list)))
8564 (and list
8565 (boundp symbol)
8566 (or (eq symbol t)
8567 (and (stringp (setq symbol (eval symbol)))
8568 (string-match-p (nth 2 list) symbol)))
8569 (display-warning package (nth 3 list) :warning)))
8570 (error nil)))
8571
8572 (dolist (elem bad-packages-alist)
8573 (let ((pkg (car elem)))
8574 (with-eval-after-load pkg
8575 (bad-package-check pkg))))
8576
8577 \f
8578 ;;; Generic dispatcher commands
8579
8580 ;; Macro `define-alternatives' is used to create generic commands.
8581 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
8582 ;; that can have different alternative implementations where choosing
8583 ;; among them is exclusively a matter of user preference.
8584
8585 ;; (define-alternatives COMMAND) creates a new interactive command
8586 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
8587 ;; Typically, the user will not need to customize this variable; packages
8588 ;; wanting to add alternative implementations should use
8589 ;;
8590 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
8591
8592 (defmacro define-alternatives (command &rest customizations)
8593 "Define the new command `COMMAND'.
8594
8595 The argument `COMMAND' should be a symbol.
8596
8597 Running `M-x COMMAND RET' for the first time prompts for which
8598 alternative to use and records the selected command as a custom
8599 variable.
8600
8601 Running `C-u M-x COMMAND RET' prompts again for an alternative
8602 and overwrites the previous choice.
8603
8604 The variable `COMMAND-alternatives' contains an alist with
8605 alternative implementations of COMMAND. `define-alternatives'
8606 does not have any effect until this variable is set.
8607
8608 CUSTOMIZATIONS, if non-nil, should be composed of alternating
8609 `defcustom' keywords and values to add to the declaration of
8610 `COMMAND-alternatives' (typically :group and :version)."
8611 (let* ((command-name (symbol-name command))
8612 (varalt-name (concat command-name "-alternatives"))
8613 (varalt-sym (intern varalt-name))
8614 (varimp-sym (intern (concat command-name "--implementation"))))
8615 `(progn
8616
8617 (defcustom ,varalt-sym nil
8618 ,(format "Alist of alternative implementations for the `%s' command.
8619
8620 Each entry must be a pair (ALTNAME . ALTFUN), where:
8621 ALTNAME - The name shown at user to describe the alternative implementation.
8622 ALTFUN - The function called to implement this alternative."
8623 command-name)
8624 :type '(alist :key-type string :value-type function)
8625 ,@customizations)
8626
8627 (put ',varalt-sym 'definition-name ',command)
8628 (defvar ,varimp-sym nil "Internal use only.")
8629
8630 (defun ,command (&optional arg)
8631 ,(format "Run generic command `%s'.
8632 If used for the first time, or with interactive ARG, ask the user which
8633 implementation to use for `%s'. The variable `%s'
8634 contains the list of implementations currently supported for this command."
8635 command-name command-name varalt-name)
8636 (interactive "P")
8637 (when (or arg (null ,varimp-sym))
8638 (let ((val (completing-read
8639 ,(format-message
8640 "Select implementation for command `%s': "
8641 command-name)
8642 ,varalt-sym nil t)))
8643 (unless (string-equal val "")
8644 (when (null ,varimp-sym)
8645 (message
8646 "Use C-u M-x %s RET`to select another implementation"
8647 ,command-name)
8648 (sit-for 3))
8649 (customize-save-variable ',varimp-sym
8650 (cdr (assoc-string val ,varalt-sym))))))
8651 (if ,varimp-sym
8652 (call-interactively ,varimp-sym)
8653 (message "%s" ,(format-message
8654 "No implementation selected for command `%s'"
8655 command-name)))))))
8656
8657 \f
8658 ;;; Functions for changing capitalization that Do What I Mean
8659 (defun upcase-dwim (arg)
8660 "Upcase words in the region, if active; if not, upcase word at point.
8661 If the region is active, this function calls `upcase-region'.
8662 Otherwise, it calls `upcase-word', with prefix argument passed to it
8663 to upcase ARG words."
8664 (interactive "*p")
8665 (if (use-region-p)
8666 (upcase-region (region-beginning) (region-end))
8667 (upcase-word arg)))
8668
8669 (defun downcase-dwim (arg)
8670 "Downcase words in the region, if active; if not, downcase word at point.
8671 If the region is active, this function calls `downcase-region'.
8672 Otherwise, it calls `downcase-word', with prefix argument passed to it
8673 to downcase ARG words."
8674 (interactive "*p")
8675 (if (use-region-p)
8676 (downcase-region (region-beginning) (region-end))
8677 (downcase-word arg)))
8678
8679 (defun capitalize-dwim (arg)
8680 "Capitalize words in the region, if active; if not, capitalize word at point.
8681 If the region is active, this function calls `capitalize-region'.
8682 Otherwise, it calls `capitalize-word', with prefix argument passed to it
8683 to capitalize ARG words."
8684 (interactive "*p")
8685 (if (use-region-p)
8686 (capitalize-region (region-beginning) (region-end))
8687 (capitalize-word arg)))
8688
8689 \f
8690
8691 (provide 'simple)
8692
8693 ;;; simple.el ends here