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