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