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