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