Small check-declare fix.
[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)
2173
e5c4079c
SM
2174(defvar minibuffer-local-shell-command-map
2175 (let ((map (make-sparse-keymap)))
2176 (set-keymap-parent map minibuffer-local-map)
1bcace58 2177 (define-key map "\t" 'completion-at-point)
e5c4079c 2178 map)
1d2b0303 2179 "Keymap used for completing shell commands in minibuffer.")
e5c4079c
SM
2180
2181(defun read-shell-command (prompt &optional initial-contents hist &rest args)
2182 "Read a shell command from the minibuffer.
2183The arguments are the same as the ones of `read-from-minibuffer',
2184except READ and KEYMAP are missing and HIST defaults
2185to `shell-command-history'."
1bcace58 2186 (require 'shell)
d6601455
JL
2187 (minibuffer-with-setup-hook
2188 (lambda ()
1bcace58
SM
2189 (set (make-local-variable 'comint-delimiter-argument-list)
2190 shell-delimiter-argument-list)
2191 (set (make-local-variable 'comint-file-name-chars) shell-file-name-chars)
2192 (set (make-local-variable 'comint-file-name-quote-list)
2193 shell-file-name-quote-list)
2194 (set (make-local-variable 'comint-dynamic-complete-functions)
2195 shell-dynamic-complete-functions)
2196 (add-hook 'completion-at-point-functions
2197 'comint-completion-at-point nil 'local)
d6601455
JL
2198 (set (make-local-variable 'minibuffer-default-add-function)
2199 'minibuffer-default-add-shell-commands))
2200 (apply 'read-from-minibuffer prompt initial-contents
2201 minibuffer-local-shell-command-map
2202 nil
2203 (or hist 'shell-command-history)
2204 args)))
e5c4079c 2205
c945a962
JL
2206(defun async-shell-command (command &optional output-buffer error-buffer)
2207 "Execute string COMMAND asynchronously in background.
2208
2209Like `shell-command' but if COMMAND doesn't end in ampersand, adds `&'
2210surrounded by whitespace and executes the command asynchronously.
5ad4bef5
SM
2211The output appears in the buffer `*Async Shell Command*'.
2212
2213In Elisp, you will often be better served by calling `start-process'
2214directly, since it offers more control and does not impose the use of a
2215shell (with its need to quote arguments)."
c945a962
JL
2216 (interactive
2217 (list
2218 (read-shell-command "Async shell command: " nil nil
2219 (and buffer-file-name
2220 (file-relative-name buffer-file-name)))
2221 current-prefix-arg
2222 shell-command-default-error-buffer))
2223 (unless (string-match "&[ \t]*\\'" command)
2224 (setq command (concat command " &")))
2225 (shell-command command output-buffer error-buffer))
2226
cc039f78 2227(defun shell-command (command &optional output-buffer error-buffer)
2076c87c 2228 "Execute string COMMAND in inferior shell; display output, if any.
0b3f96d4 2229With prefix argument, insert the COMMAND's output at point.
d382f610 2230
2076c87c 2231If COMMAND ends in ampersand, execute it asynchronously.
d382f610 2232The output appears in the buffer `*Async Shell Command*'.
bcad4985 2233That buffer is in shell mode.
d382f610 2234
939ac10c
GM
2235Otherwise, COMMAND is executed synchronously. The output appears in
2236the buffer `*Shell Command Output*'. If the output is short enough to
2237display in the echo area (which is determined by the variables
2238`resize-mini-windows' and `max-mini-window-height'), it is shown
2239there, but it is nonetheless available in buffer `*Shell Command
e1e04350 2240Output*' even though that buffer is not automatically displayed.
d0d74413 2241
07f458c1 2242To specify a coding system for converting non-ASCII characters
5626c14e 2243in the shell command output, use \\[universal-coding-system-argument] \
07f458c1
RS
2244before this command.
2245
2246Noninteractive callers can specify coding systems by binding
2247`coding-system-for-read' and `coding-system-for-write'.
2248
d0d74413
RS
2249The optional second argument OUTPUT-BUFFER, if non-nil,
2250says to put the output in some other buffer.
2251If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2252If OUTPUT-BUFFER is not a buffer and not nil,
2253insert output in current buffer. (This cannot be done asynchronously.)
e7791447
CY
2254In either case, the buffer is first erased, and the output is
2255inserted after point (leaving mark after it).
cc039f78 2256
2e033693
RS
2257If the command terminates without error, but generates output,
2258and you did not specify \"insert it in the current buffer\",
2259the output can be displayed in the echo area or in its buffer.
2260If the output is short enough to display in the echo area
2261\(determined by the variable `max-mini-window-height' if
5626c14e
JB
2262`resize-mini-windows' is non-nil), it is shown there.
2263Otherwise,the buffer containing the output is displayed.
2e033693
RS
2264
2265If there is output and an error, and you did not specify \"insert it
2266in the current buffer\", a message about the error goes at the end
2267of the output.
2268
2269If there is no output, or if output is inserted in the current buffer,
2270then `*Shell Command Output*' is deleted.
2271
cc039f78
KH
2272If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2273or buffer name to which to direct the command's standard error output.
2274If it is nil, error output is mingled with regular output.
2275In an interactive call, the variable `shell-command-default-error-buffer'
5ad4bef5
SM
2276specifies the value of ERROR-BUFFER.
2277
2278In Elisp, you will often be better served by calling `call-process' or
2279`start-process' directly, since it offers more control and does not impose
2280the use of a shell (with its need to quote arguments)."
cc039f78 2281
a98a2fe8
JL
2282 (interactive
2283 (list
d6601455 2284 (read-shell-command "Shell command: " nil nil
e0987650
JL
2285 (let ((filename
2286 (cond
2287 (buffer-file-name)
2288 ((eq major-mode 'dired-mode)
2289 (dired-get-filename nil t)))))
2290 (and filename (file-relative-name filename))))
a98a2fe8
JL
2291 current-prefix-arg
2292 shell-command-default-error-buffer))
c7edd03c
KH
2293 ;; Look for a handler in case default-directory is a remote file name.
2294 (let ((handler
2295 (find-file-name-handler (directory-file-name default-directory)
2296 'shell-command)))
2297 (if handler
cc039f78 2298 (funcall handler 'shell-command command output-buffer error-buffer)
c7edd03c
KH
2299 (if (and output-buffer
2300 (not (or (bufferp output-buffer) (stringp output-buffer))))
2e033693 2301 ;; Output goes in current buffer.
cc039f78 2302 (let ((error-file
1e722f9f 2303 (if error-buffer
b005abd5 2304 (make-temp-file
171a45d9
EZ
2305 (expand-file-name "scor"
2306 (or small-temporary-file-directory
2307 temporary-file-directory)))
cc039f78
KH
2308 nil)))
2309 (barf-if-buffer-read-only)
63437623 2310 (push-mark nil t)
cc039f78
KH
2311 ;; We do not use -f for csh; we will not support broken use of
2312 ;; .cshrcs. Even the BSD csh manual says to use
2313 ;; "if ($?prompt) exit" before things which are not useful
2314 ;; non-interactively. Besides, if someone wants their other
2315 ;; aliases for shell commands then they can still have them.
1e722f9f 2316 (call-process shell-file-name nil
cc039f78
KH
2317 (if error-file
2318 (list t error-file)
2319 t)
2320 nil shell-command-switch command)
2321 (when (and error-file (file-exists-p error-file))
2322 (if (< 0 (nth 7 (file-attributes error-file)))
2323 (with-current-buffer (get-buffer-create error-buffer)
2324 (let ((pos-from-end (- (point-max) (point))))
2325 (or (bobp)
2326 (insert "\f\n"))
2327 ;; Do no formatting while reading error file,
2328 ;; because that can run a shell command, and we
2329 ;; don't want that to cause an infinite recursion.
2330 (format-insert-file error-file nil)
2331 ;; Put point after the inserted errors.
2332 (goto-char (- (point-max) pos-from-end)))
2333 (display-buffer (current-buffer))))
2334 (delete-file error-file))
2335 ;; This is like exchange-point-and-mark, but doesn't
2336 ;; activate the mark. It is cleaner to avoid activation,
2337 ;; even though the command loop would deactivate the mark
2338 ;; because we inserted text.
2339 (goto-char (prog1 (mark t)
2340 (set-marker (mark-marker) (point)
2341 (current-buffer)))))
2e033693 2342 ;; Output goes in a separate buffer.
c7edd03c
KH
2343 ;; Preserve the match data in case called from a program.
2344 (save-match-data
aab5d2c5 2345 (if (string-match "[ \t]*&[ \t]*\\'" command)
c7edd03c
KH
2346 ;; Command ending with ampersand means asynchronous.
2347 (let ((buffer (get-buffer-create
2348 (or output-buffer "*Async Shell Command*")))
2349 (directory default-directory)
2350 proc)
2351 ;; Remove the ampersand.
2352 (setq command (substring command 0 (match-beginning 0)))
2353 ;; If will kill a process, query first.
2354 (setq proc (get-buffer-process buffer))
2355 (if proc
2356 (if (yes-or-no-p "A command is running. Kill it? ")
2357 (kill-process proc)
2358 (error "Shell command in progress")))
1e96c007 2359 (with-current-buffer buffer
c7edd03c 2360 (setq buffer-read-only nil)
50f8cd96
TH
2361 ;; Setting buffer-read-only to nil doesn't suffice
2362 ;; if some text has a non-nil read-only property,
2363 ;; which comint sometimes adds for prompts.
2364 (let ((inhibit-read-only t))
2365 (erase-buffer))
c7edd03c
KH
2366 (display-buffer buffer)
2367 (setq default-directory directory)
1e722f9f 2368 (setq proc (start-process "Shell" buffer shell-file-name
c7edd03c
KH
2369 shell-command-switch command))
2370 (setq mode-line-process '(":%s"))
c2020c27 2371 (require 'shell) (shell-mode)
c7edd03c 2372 (set-process-sentinel proc 'shell-command-sentinel)
50c737e4
JL
2373 ;; Use the comint filter for proper handling of carriage motion
2374 ;; (see `comint-inhibit-carriage-motion'),.
2375 (set-process-filter proc 'comint-output-filter)
c7edd03c 2376 ))
50c737e4 2377 ;; Otherwise, command is executed synchronously.
cc039f78
KH
2378 (shell-command-on-region (point) (point) command
2379 output-buffer nil error-buffer)))))))
eaae8106 2380
f69aad2b
MB
2381(defun display-message-or-buffer (message
2382 &optional buffer-name not-this-window frame)
2383 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2384MESSAGE may be either a string or a buffer.
2385
2386A buffer is displayed using `display-buffer' if MESSAGE is too long for
939ac10c
GM
2387the maximum height of the echo area, as defined by `max-mini-window-height'
2388if `resize-mini-windows' is non-nil.
f69aad2b 2389
2a3f00bf
MB
2390Returns either the string shown in the echo area, or when a pop-up
2391buffer is used, the window used to display it.
2392
f69aad2b
MB
2393If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2394name of the buffer used to display it in the case where a pop-up buffer
2395is used, defaulting to `*Message*'. In the case where MESSAGE is a
2396string and it is displayed in the echo area, it is not specified whether
2397the contents are inserted into the buffer anyway.
2398
2399Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
2400and only used if a buffer is displayed."
39a8d88a 2401 (cond ((and (stringp message) (not (string-match "\n" message)))
f69aad2b
MB
2402 ;; Trivial case where we can use the echo area
2403 (message "%s" message))
2404 ((and (stringp message)
39a8d88a 2405 (= (string-match "\n" message) (1- (length message))))
f69aad2b
MB
2406 ;; Trivial case where we can just remove single trailing newline
2407 (message "%s" (substring message 0 (1- (length message)))))
2408 (t
2409 ;; General case
2410 (with-current-buffer
2411 (if (bufferp message)
2412 message
2413 (get-buffer-create (or buffer-name "*Message*")))
2414
2415 (unless (bufferp message)
2416 (erase-buffer)
2417 (insert message))
2418
2419 (let ((lines
2420 (if (= (buffer-size) 0)
2421 0
62ffcd76 2422 (count-screen-lines nil nil nil (minibuffer-window)))))
4f017185
RS
2423 (cond ((= lines 0))
2424 ((and (or (<= lines 1)
aab5d2c5
RS
2425 (<= lines
2426 (if resize-mini-windows
2427 (cond ((floatp max-mini-window-height)
2428 (* (frame-height)
2429 max-mini-window-height))
2430 ((integerp max-mini-window-height)
2431 max-mini-window-height)
2432 (t
2433 1))
2434 1)))
2435 ;; Don't use the echo area if the output buffer is
2436 ;; already dispayed in the selected frame.
61b80ebf 2437 (not (get-buffer-window (current-buffer))))
f69aad2b
MB
2438 ;; Echo area
2439 (goto-char (point-max))
2440 (when (bolp)
2441 (backward-char 1))
2442 (message "%s" (buffer-substring (point-min) (point))))
2443 (t
2444 ;; Buffer
2445 (goto-char (point-min))
31252c00
MB
2446 (display-buffer (current-buffer)
2447 not-this-window frame))))))))
f69aad2b
MB
2448
2449
2076c87c
JB
2450;; We have a sentinel to prevent insertion of a termination message
2451;; in the buffer itself.
2452(defun shell-command-sentinel (process signal)
bcad4985 2453 (if (memq (process-status process) '(exit signal))
1e722f9f 2454 (message "%s: %s."
bcad4985
KH
2455 (car (cdr (cdr (process-command process))))
2456 (substring signal 0 -1))))
2076c87c 2457
d0d74413 2458(defun shell-command-on-region (start end command
cce1c318 2459 &optional output-buffer replace
63619f42 2460 error-buffer display-error-buffer)
2076c87c
JB
2461 "Execute string COMMAND in inferior shell with region as input.
2462Normally display output (if any) in temp buffer `*Shell Command Output*';
a0184aeb
DL
2463Prefix arg means replace the region with it. Return the exit code of
2464COMMAND.
56c0450e 2465
07f458c1
RS
2466To specify a coding system for converting non-ASCII characters
2467in the input and output to the shell command, use \\[universal-coding-system-argument]
2468before this command. By default, the input (from the current buffer)
2469is encoded in the same coding system that will be used to save the file,
2470`buffer-file-coding-system'. If the output is going to replace the region,
2471then it is decoded from that same coding system.
2472
63619f42
RS
2473The noninteractive arguments are START, END, COMMAND,
2474OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
2475Noninteractive callers can specify coding systems by binding
2476`coding-system-for-read' and `coding-system-for-write'.
2076c87c 2477
2e033693
RS
2478If the command generates output, the output may be displayed
2479in the echo area or in a buffer.
2480If the output is short enough to display in the echo area
2481\(determined by the variable `max-mini-window-height' if
2482`resize-mini-windows' is non-nil), it is shown there. Otherwise
2483it is displayed in the buffer `*Shell Command Output*'. The output
2484is available in that buffer in both cases.
2485
2486If there is output and an error, a message about the error
2487appears at the end of the output.
2488
2489If there is no output, or if output is inserted in the current buffer,
2490then `*Shell Command Output*' is deleted.
d0d74413 2491
56c0450e
RS
2492If the optional fourth argument OUTPUT-BUFFER is non-nil,
2493that says to put the output in some other buffer.
d0d74413
RS
2494If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2495If OUTPUT-BUFFER is not a buffer and not nil,
2496insert output in the current buffer.
cce1c318
RS
2497In either case, the output is inserted after point (leaving mark after it).
2498
8923a211
RS
2499If REPLACE, the optional fifth argument, is non-nil, that means insert
2500the output in place of text from START to END, putting point and mark
2501around it.
2502
b735c991 2503If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
cce1c318 2504or buffer name to which to direct the command's standard error output.
7fd47839 2505If it is nil, error output is mingled with regular output.
63619f42
RS
2506If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2507were any errors. (This is always t, interactively.)
cc039f78
KH
2508In an interactive call, the variable `shell-command-default-error-buffer'
2509specifies the value of ERROR-BUFFER."
195ce311
RS
2510 (interactive (let (string)
2511 (unless (mark)
2512 (error "The mark is not set now, so there is no region"))
2513 ;; Do this before calling region-beginning
2514 ;; and region-end, in case subprocess output
2515 ;; relocates them while we are in the minibuffer.
e5c4079c 2516 (setq string (read-shell-command "Shell command on region: "))
2b03c506
RS
2517 ;; call-interactively recognizes region-beginning and
2518 ;; region-end specially, leaving them in the history.
2519 (list (region-beginning) (region-end)
cae49185
RS
2520 string
2521 current-prefix-arg
7fd47839 2522 current-prefix-arg
63619f42
RS
2523 shell-command-default-error-buffer
2524 t)))
cce1c318 2525 (let ((error-file
171a45d9 2526 (if error-buffer
b005abd5 2527 (make-temp-file
171a45d9
EZ
2528 (expand-file-name "scor"
2529 (or small-temporary-file-directory
2530 temporary-file-directory)))
a0184aeb
DL
2531 nil))
2532 exit-status)
7fd47839
RS
2533 (if (or replace
2534 (and output-buffer
748d6ca4 2535 (not (or (bufferp output-buffer) (stringp output-buffer)))))
7fd47839
RS
2536 ;; Replace specified region with output from command.
2537 (let ((swap (and replace (< start end))))
2538 ;; Don't muck with mark unless REPLACE says we should.
2539 (goto-char start)
30883773 2540 (and replace (push-mark (point) 'nomsg))
a0184aeb
DL
2541 (setq exit-status
2542 (call-process-region start end shell-file-name t
2543 (if error-file
2544 (list t error-file)
2545 t)
2546 nil shell-command-switch command))
e1e04350
SM
2547 ;; It is rude to delete a buffer which the command is not using.
2548 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2549 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2550 ;; (kill-buffer shell-buffer)))
7fd47839
RS
2551 ;; Don't muck with mark unless REPLACE says we should.
2552 (and replace swap (exchange-point-and-mark)))
2553 ;; No prefix argument: put the output in a temp buffer,
2554 ;; replacing its entire contents.
2555 (let ((buffer (get-buffer-create
d4bbcbb4 2556 (or output-buffer "*Shell Command Output*"))))
7fd47839
RS
2557 (unwind-protect
2558 (if (eq buffer (current-buffer))
2559 ;; If the input is the same buffer as the output,
2560 ;; delete everything but the specified region,
2561 ;; then replace that region with the output.
2562 (progn (setq buffer-read-only nil)
2563 (delete-region (max start end) (point-max))
2564 (delete-region (point-min) (min start end))
2565 (setq exit-status
2566 (call-process-region (point-min) (point-max)
1e722f9f 2567 shell-file-name t
7fd47839
RS
2568 (if error-file
2569 (list t error-file)
2570 t)
a0184aeb
DL
2571 nil shell-command-switch
2572 command)))
2573 ;; Clear the output buffer, then run the command with
2574 ;; output there.
c2e303c8 2575 (let ((directory default-directory))
7fdbcd83 2576 (with-current-buffer buffer
c2e303c8
GM
2577 (setq buffer-read-only nil)
2578 (if (not output-buffer)
2579 (setq default-directory directory))
2580 (erase-buffer)))
7fd47839
RS
2581 (setq exit-status
2582 (call-process-region start end shell-file-name nil
2583 (if error-file
2584 (list buffer error-file)
2585 buffer)
a0184aeb 2586 nil shell-command-switch command)))
2e033693 2587 ;; Report the output.
9a98fa64 2588 (with-current-buffer buffer
f1180544 2589 (setq mode-line-process
d4bbcbb4
AS
2590 (cond ((null exit-status)
2591 " - Error")
2592 ((stringp exit-status)
2593 (format " - Signal [%s]" exit-status))
2594 ((not (equal 0 exit-status))
2595 (format " - Exit [%d]" exit-status)))))
f69aad2b
MB
2596 (if (with-current-buffer buffer (> (point-max) (point-min)))
2597 ;; There's some output, display it
9a98fa64 2598 (display-message-or-buffer buffer)
f69aad2b 2599 ;; No output; error?
94ddbe6d
RS
2600 (let ((output
2601 (if (and error-file
2602 (< 0 (nth 7 (file-attributes error-file))))
2603 "some error output"
2604 "no output")))
d4bbcbb4
AS
2605 (cond ((null exit-status)
2606 (message "(Shell command failed with error)"))
2607 ((equal 0 exit-status)
2608 (message "(Shell command succeeded with %s)"
2609 output))
2610 ((stringp exit-status)
2611 (message "(Shell command killed by signal %s)"
2612 exit-status))
2613 (t
2614 (message "(Shell command failed with code %d and %s)"
2615 exit-status output))))
e1e04350
SM
2616 ;; Don't kill: there might be useful info in the undo-log.
2617 ;; (kill-buffer buffer)
2618 ))))
f69aad2b 2619
cc039f78
KH
2620 (when (and error-file (file-exists-p error-file))
2621 (if (< 0 (nth 7 (file-attributes error-file)))
2622 (with-current-buffer (get-buffer-create error-buffer)
2623 (let ((pos-from-end (- (point-max) (point))))
2624 (or (bobp)
2625 (insert "\f\n"))
2626 ;; Do no formatting while reading error file,
2627 ;; because that can run a shell command, and we
2628 ;; don't want that to cause an infinite recursion.
2629 (format-insert-file error-file nil)
2630 ;; Put point after the inserted errors.
2631 (goto-char (- (point-max) pos-from-end)))
63619f42
RS
2632 (and display-error-buffer
2633 (display-buffer (current-buffer)))))
cc039f78 2634 (delete-file error-file))
a0184aeb 2635 exit-status))
1e722f9f 2636
d589bd99
RS
2637(defun shell-command-to-string (command)
2638 "Execute shell command COMMAND and return its output as a string."
2639 (with-output-to-string
17cc9013
RS
2640 (with-current-buffer
2641 standard-output
b511b994 2642 (process-file shell-file-name nil t nil shell-command-switch command))))
0457dd55
KG
2643
2644(defun process-file (program &optional infile buffer display &rest args)
2645 "Process files synchronously in a separate process.
2646Similar to `call-process', but may invoke a file handler based on
2647`default-directory'. The current working directory of the
2648subprocess is `default-directory'.
2649
2650File names in INFILE and BUFFER are handled normally, but file
2651names in ARGS should be relative to `default-directory', as they
2652are passed to the process verbatim. \(This is a difference to
2653`call-process' which does not support file handlers for INFILE
2654and BUFFER.\)
2655
2656Some file handlers might not support all variants, for example
2657they might behave as if DISPLAY was nil, regardless of the actual
2658value passed."
2659 (let ((fh (find-file-name-handler default-directory 'process-file))
2660 lc stderr-file)
2661 (unwind-protect
2662 (if fh (apply fh 'process-file program infile buffer display args)
8de40f9f 2663 (when infile (setq lc (file-local-copy infile)))
0457dd55 2664 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
85af630d
KG
2665 (make-temp-file "emacs")))
2666 (prog1
2667 (apply 'call-process program
2668 (or lc infile)
2669 (if stderr-file (list (car buffer) stderr-file) buffer)
2670 display args)
2671 (when stderr-file (copy-file stderr-file (cadr buffer)))))
0457dd55
KG
2672 (when stderr-file (delete-file stderr-file))
2673 (when lc (delete-file lc)))))
2674
2c4f2562
MA
2675(defvar process-file-side-effects t
2676 "Whether a call of `process-file' changes remote files.
2677
2678Per default, this variable is always set to `t', meaning that a
2679call of `process-file' could potentially change any file on a
2680remote host. When set to `nil', a file handler could optimize
2681its behaviour with respect to remote file attributes caching.
2682
2683This variable should never be changed by `setq'. Instead of, it
2684shall be set only by let-binding.")
2685
7cb76caa
MA
2686(defun start-file-process (name buffer program &rest program-args)
2687 "Start a program in a subprocess. Return the process object for it.
5a5abb2c 2688
7cb76caa 2689Similar to `start-process', but may invoke a file handler based on
5a5abb2c
MA
2690`default-directory'. See Info node `(elisp)Magic File Names'.
2691
2692This handler ought to run PROGRAM, perhaps on the local host,
2693perhaps on a remote host that corresponds to `default-directory'.
2694In the latter case, the local part of `default-directory' becomes
2695the working directory of the process.
7cb76caa
MA
2696
2697PROGRAM and PROGRAM-ARGS might be file names. They are not
91f11424
MA
2698objects of file handler invocation. File handlers might not
2699support pty association, if PROGRAM is nil."
7cb76caa
MA
2700 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
2701 (if fh (apply fh 'start-file-process name buffer program program-args)
2702 (apply 'start-process name buffer program program-args))))
7d668f2c
CY
2703\f
2704;;;; Process menu
2705
2706(defvar tabulated-list-format)
2707(defvar tabulated-list-entries)
2708(defvar tabulated-list-sort-key)
2709(declare-function tabulated-list-init-header "tabulated-list" ())
2710(declare-function tabulated-list-print "tabulated-list" ())
2711
2712(defvar process-menu-query-only nil)
2713
2714(define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
2715 "Major mode for listing the processes called by Emacs."
2716 (setq tabulated-list-format [("Process" 15 t)
2717 ("Status" 7 t)
2718 ("Buffer" 15 t)
2719 ("TTY" 12 t)
2720 ("Command" 0 t)])
2721 (make-local-variable 'process-menu-query-only)
2722 (setq tabulated-list-sort-key (cons "Process" nil))
2723 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
2724 (tabulated-list-init-header))
2725
2726(defun list-processes--refresh ()
2727 "Recompute the list of processes for the Process List buffer."
2728 (setq tabulated-list-entries nil)
2729 (dolist (p (process-list))
2730 (when (or (not process-menu-query-only)
2731 (process-query-on-exit-flag p))
2732 (let* ((buf (process-buffer p))
2733 (type (process-type p))
2734 (name (process-name p))
2735 (status (symbol-name (process-status p)))
2736 (buf-label (if (buffer-live-p buf)
2737 `(,(buffer-name buf)
2738 face link
2739 help-echo ,(concat "Visit buffer `"
2740 (buffer-name buf) "'")
2741 follow-link t
2742 process-buffer ,buf
2743 action process-menu-visit-buffer)
2744 "--"))
2745 (tty (or (process-tty-name p) "--"))
2746 (cmd
2747 (if (memq type '(network serial))
2748 (let ((contact (process-contact p t)))
2749 (if (eq type 'network)
2750 (format "(%s %s)"
2751 (if (plist-get contact :type)
2752 "datagram"
2753 "network")
2754 (if (plist-get contact :server)
2755 (format "server on %s"
2756 (plist-get contact :server))
2757 (format "connection to %s"
2758 (plist-get contact :host))))
2759 (format "(serial port %s%s)"
2760 (or (plist-get contact :port) "?")
2761 (let ((speed (plist-get contact :speed)))
2762 (if speed
2763 (format " at %s b/s" speed)
2764 "")))))
2765 (mapconcat 'identity (process-command p) " "))))
2766 (push (list p (vector name status buf-label tty cmd))
2767 tabulated-list-entries)))))
2768
2769(defun process-menu-visit-buffer (button)
2770 (display-buffer (button-get button 'process-buffer)))
2771
2772(defun list-processes (&optional query-only buffer)
2773 "Display a list of all processes.
2774If optional argument QUERY-ONLY is non-nil, only processes with
2775the query-on-exit flag set are listed.
2776Any process listed as exited or signaled is actually eliminated
2777after the listing is made.
2778Optional argument BUFFER specifies a buffer to use, instead of
2779\"*Process List\".
2780The return value is always nil."
2781 (interactive)
3726838a
EZ
2782 (or (fboundp 'process-list)
2783 (error "Asynchronous subprocesses are not supported on this system"))
7d668f2c
CY
2784 (unless (bufferp buffer)
2785 (setq buffer (get-buffer-create "*Process List*")))
2786 (with-current-buffer buffer
2787 (process-menu-mode)
2788 (setq process-menu-query-only query-only)
2789 (list-processes--refresh)
2790 (tabulated-list-print))
2791 (display-buffer buffer))
2d88b556 2792\f
1b43f83f 2793(defvar universal-argument-map
69d4c3c4
KH
2794 (let ((map (make-sparse-keymap)))
2795 (define-key map [t] 'universal-argument-other-key)
b9ff190d 2796 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
69d4c3c4
KH
2797 (define-key map [switch-frame] nil)
2798 (define-key map [?\C-u] 'universal-argument-more)
2799 (define-key map [?-] 'universal-argument-minus)
2800 (define-key map [?0] 'digit-argument)
2801 (define-key map [?1] 'digit-argument)
2802 (define-key map [?2] 'digit-argument)
2803 (define-key map [?3] 'digit-argument)
2804 (define-key map [?4] 'digit-argument)
2805 (define-key map [?5] 'digit-argument)
2806 (define-key map [?6] 'digit-argument)
2807 (define-key map [?7] 'digit-argument)
2808 (define-key map [?8] 'digit-argument)
2809 (define-key map [?9] 'digit-argument)
bd7acc8d
GM
2810 (define-key map [kp-0] 'digit-argument)
2811 (define-key map [kp-1] 'digit-argument)
2812 (define-key map [kp-2] 'digit-argument)
2813 (define-key map [kp-3] 'digit-argument)
2814 (define-key map [kp-4] 'digit-argument)
2815 (define-key map [kp-5] 'digit-argument)
2816 (define-key map [kp-6] 'digit-argument)
2817 (define-key map [kp-7] 'digit-argument)
2818 (define-key map [kp-8] 'digit-argument)
2819 (define-key map [kp-9] 'digit-argument)
2820 (define-key map [kp-subtract] 'universal-argument-minus)
69d4c3c4
KH
2821 map)
2822 "Keymap used while processing \\[universal-argument].")
2823
0de84e16
RS
2824(defvar universal-argument-num-events nil
2825 "Number of argument-specifying events read by `universal-argument'.
2826`universal-argument-other-key' uses this to discard those events
2827from (this-command-keys), and reread only the final command.")
2828
6b61353c
KH
2829(defvar overriding-map-is-bound nil
2830 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2831
2832(defvar saved-overriding-map nil
2833 "The saved value of `overriding-terminal-local-map'.
2834That variable gets restored to this value on exiting \"universal
2835argument mode\".")
2836
2837(defun ensure-overriding-map-is-bound ()
2838 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2839 (unless overriding-map-is-bound
2840 (setq saved-overriding-map overriding-terminal-local-map)
2841 (setq overriding-terminal-local-map universal-argument-map)
2842 (setq overriding-map-is-bound t)))
2843
2844(defun restore-overriding-map ()
2845 "Restore `overriding-terminal-local-map' to its saved value."
2846 (setq overriding-terminal-local-map saved-overriding-map)
2847 (setq overriding-map-is-bound nil))
2848
e8d1a377
KH
2849(defun universal-argument ()
2850 "Begin a numeric argument for the following command.
2851Digits or minus sign following \\[universal-argument] make up the numeric argument.
2852\\[universal-argument] following the digits or minus sign ends the argument.
2853\\[universal-argument] without digits or minus sign provides 4 as argument.
2854Repeating \\[universal-argument] without digits or minus sign
0565d307
RS
2855 multiplies the argument by 4 each time.
2856For some commands, just \\[universal-argument] by itself serves as a flag
a697fc62
RS
2857which is different in effect from any particular numeric argument.
2858These commands include \\[set-mark-command] and \\[start-kbd-macro]."
69d4c3c4
KH
2859 (interactive)
2860 (setq prefix-arg (list 4))
0de84e16 2861 (setq universal-argument-num-events (length (this-command-keys)))
6b61353c 2862 (ensure-overriding-map-is-bound))
e8d1a377 2863
69d4c3c4
KH
2864;; A subsequent C-u means to multiply the factor by 4 if we've typed
2865;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2866(defun universal-argument-more (arg)
e8d1a377 2867 (interactive "P")
69d4c3c4
KH
2868 (if (consp arg)
2869 (setq prefix-arg (list (* 4 (car arg))))
1cd24721
RS
2870 (if (eq arg '-)
2871 (setq prefix-arg (list -4))
2872 (setq prefix-arg arg)
6b61353c 2873 (restore-overriding-map)))
0de84e16 2874 (setq universal-argument-num-events (length (this-command-keys))))
e8d1a377
KH
2875
2876(defun negative-argument (arg)
2877 "Begin a negative numeric argument for the next command.
2878\\[universal-argument] following digits or minus sign ends the argument."
2879 (interactive "P")
69d4c3c4
KH
2880 (cond ((integerp arg)
2881 (setq prefix-arg (- arg)))
2882 ((eq arg '-)
2883 (setq prefix-arg nil))
2884 (t
b9ff190d 2885 (setq prefix-arg '-)))
0de84e16 2886 (setq universal-argument-num-events (length (this-command-keys)))
6b61353c 2887 (ensure-overriding-map-is-bound))
69d4c3c4
KH
2888
2889(defun digit-argument (arg)
2890 "Part of the numeric argument for the next command.
2891\\[universal-argument] following digits or minus sign ends the argument."
2892 (interactive "P")
8989a920
GM
2893 (let* ((char (if (integerp last-command-event)
2894 last-command-event
2895 (get last-command-event 'ascii-character)))
bd7acc8d 2896 (digit (- (logand char ?\177) ?0)))
69d4c3c4
KH
2897 (cond ((integerp arg)
2898 (setq prefix-arg (+ (* arg 10)
2899 (if (< arg 0) (- digit) digit))))
2900 ((eq arg '-)
2901 ;; Treat -0 as just -, so that -01 will work.
2902 (setq prefix-arg (if (zerop digit) '- (- digit))))
2903 (t
b9ff190d 2904 (setq prefix-arg digit))))
0de84e16 2905 (setq universal-argument-num-events (length (this-command-keys)))
6b61353c 2906 (ensure-overriding-map-is-bound))
69d4c3c4
KH
2907
2908;; For backward compatibility, minus with no modifiers is an ordinary
2909;; command if digits have already been entered.
2910(defun universal-argument-minus (arg)
2911 (interactive "P")
2912 (if (integerp arg)
2913 (universal-argument-other-key arg)
2914 (negative-argument arg)))
2915
2916;; Anything else terminates the argument and is left in the queue to be
2917;; executed as a command.
2918(defun universal-argument-other-key (arg)
2919 (interactive "P")
2920 (setq prefix-arg arg)
0de84e16
RS
2921 (let* ((key (this-command-keys))
2922 (keylist (listify-key-sequence key)))
2923 (setq unread-command-events
06697cdb
RS
2924 (append (nthcdr universal-argument-num-events keylist)
2925 unread-command-events)))
f0ef2555 2926 (reset-this-command-lengths)
6b61353c 2927 (restore-overriding-map))
2d88b556 2928\f
8f92b8ad
SM
2929
2930(defvar filter-buffer-substring-functions nil
2931 "Wrapper hook around `filter-buffer-substring'.
2932The functions on this special hook are called with 4 arguments:
2933 NEXT-FUN BEG END DELETE
2934NEXT-FUN is a function of 3 arguments (BEG END DELETE)
2935that performs the default operation. The other 3 arguments are like
2936the ones passed to `filter-buffer-substring'.")
2937
7fcce20f
RS
2938(defvar buffer-substring-filters nil
2939 "List of filter functions for `filter-buffer-substring'.
2940Each function must accept a single argument, a string, and return
2941a string. The buffer substring is passed to the first function
2942in the list, and the return value of each function is passed to
2943the next. The return value of the last function is used as the
2944return value of `filter-buffer-substring'.
2945
2946If this variable is nil, no filtering is performed.")
8f92b8ad
SM
2947(make-obsolete-variable 'buffer-substring-filters
2948 'filter-buffer-substring-functions "24.1")
7fcce20f 2949
8f92b8ad 2950(defun filter-buffer-substring (beg end &optional delete)
7fcce20f 2951 "Return the buffer substring between BEG and END, after filtering.
8f92b8ad 2952The filtering is performed by `filter-buffer-substring-functions'.
7fcce20f
RS
2953
2954If DELETE is non-nil, the text between BEG and END is deleted
2955from the buffer.
2956
398c9ffb
KS
2957This function should be used instead of `buffer-substring',
2958`buffer-substring-no-properties', or `delete-and-extract-region'
2959when you want to allow filtering to take place. For example,
8f92b8ad 2960major or minor modes can use `filter-buffer-substring-functions' to
398c9ffb
KS
2961extract characters that are special to a buffer, and should not
2962be copied into other buffers."
8f92b8ad
SM
2963 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
2964 (cond
2965 ((or delete buffer-substring-filters)
2966 (save-excursion
2967 (goto-char beg)
2968 (let ((string (if delete (delete-and-extract-region beg end)
2969 (buffer-substring beg end))))
2970 (dolist (filter buffer-substring-filters)
2971 (setq string (funcall filter string)))
2972 string)))
2973 (t
2974 (buffer-substring beg end)))))
398c9ffb 2975
7fcce20f 2976
93be67de 2977;;;; Window system cut and paste hooks.
70e14c01
JB
2978
2979(defvar interprogram-cut-function nil
2980 "Function to call to make a killed region available to other programs.
2981
2982Most window systems provide some sort of facility for cutting and
9f112a3d
RS
2983pasting text between the windows of different programs.
2984This variable holds a function that Emacs calls whenever text
2985is put in the kill ring, to make the new kill available to other
70e14c01
JB
2986programs.
2987
6d7cc563
JD
2988The function takes one argument, TEXT, which is a string containing
2989the text which should be made available.")
70e14c01
JB
2990
2991(defvar interprogram-paste-function nil
2992 "Function to call to get text cut from other programs.
2993
2994Most window systems provide some sort of facility for cutting and
9f112a3d
RS
2995pasting text between the windows of different programs.
2996This variable holds a function that Emacs calls to obtain
70e14c01
JB
2997text that other programs have provided for pasting.
2998
2999The function should be called with no arguments. If the function
3000returns nil, then no other program has provided such text, and the top
3001of the Emacs kill ring should be used. If the function returns a
6b61353c
KH
3002string, then the caller of the function \(usually `current-kill')
3003should put this string in the kill ring as the latest kill.
daa37602 3004
d4cb4833 3005This function may also return a list of strings if the window
1d2b0303 3006system supports multiple selections. The first string will be
d4cb4833
GM
3007used as the pasted text, but the other will be placed in the
3008kill ring for easy access via `yank-pop'.
3009
daa37602
JB
3010Note that the function should return a string only if a program other
3011than Emacs has provided a string for pasting; if Emacs provided the
3012most recent string, the function should return nil. If it is
3013difficult to tell whether Emacs or some other program provided the
3014current string, it is probably good enough to return nil if the string
3015is equal (according to `string=') to the last text Emacs provided.")
2d88b556 3016\f
70e14c01 3017
eaae8106 3018
70e14c01 3019;;;; The kill ring data structure.
2076c87c
JB
3020
3021(defvar kill-ring nil
70e14c01
JB
3022 "List of killed text sequences.
3023Since the kill ring is supposed to interact nicely with cut-and-paste
3024facilities offered by window systems, use of this variable should
3025interact nicely with `interprogram-cut-function' and
3026`interprogram-paste-function'. The functions `kill-new',
3027`kill-append', and `current-kill' are supposed to implement this
3028interaction; you may want to use them instead of manipulating the kill
3029ring directly.")
2076c87c 3030
bffa4d92 3031(defcustom kill-ring-max 60
1d2b0303 3032 "Maximum length of kill ring before oldest elements are thrown away."
69c1dd37
RS
3033 :type 'integer
3034 :group 'killing)
2076c87c
JB
3035
3036(defvar kill-ring-yank-pointer nil
3037 "The tail of the kill ring whose car is the last thing yanked.")
3038
4ed8c7aa 3039(defcustom save-interprogram-paste-before-kill nil
e8ab3908 3040 "Save clipboard strings into kill ring before replacing them.
4ed8c7aa
SS
3041When one selects something in another program to paste it into Emacs,
3042but kills something in Emacs before actually pasting it,
3043this selection is gone unless this variable is non-nil,
3044in which case the other program's selection is saved in the `kill-ring'
3045before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
3046 :type 'boolean
3047 :group 'killing
3048 :version "23.2")
3049
ba83a64e
SS
3050(defcustom kill-do-not-save-duplicates nil
3051 "Do not add a new string to `kill-ring' when it is the same as the last one."
3052 :type 'boolean
3053 :group 'killing
3054 :version "23.2")
3055
be5936a7 3056(defun kill-new (string &optional replace yank-handler)
70e14c01 3057 "Make STRING the latest kill in the kill ring.
3e505153 3058Set `kill-ring-yank-pointer' to point to it.
f914dc91
KH
3059If `interprogram-cut-function' is non-nil, apply it to STRING.
3060Optional second argument REPLACE non-nil means that STRING will replace
be5936a7
KS
3061the front of the kill ring, rather than being added to the list.
3062
4ed8c7aa
SS
3063When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
3064are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3065STRING.
3066
2a262563
KS
3067When the yank handler has a non-nil PARAM element, the original STRING
3068argument is not used by `insert-for-yank'. However, since Lisp code
f33321ad 3069may access and use elements from the kill ring directly, the STRING
2a262563
KS
3070argument should still be a \"useful\" string for such uses."
3071 (if (> (length string) 0)
f1180544 3072 (if yank-handler
6b61353c
KH
3073 (put-text-property 0 (length string)
3074 'yank-handler yank-handler string))
2a262563 3075 (if yank-handler
f1180544 3076 (signal 'args-out-of-range
2a262563 3077 (list string "yank-handler specified for empty string"))))
0665f661
JL
3078 (unless (and kill-do-not-save-duplicates
3079 (equal string (car kill-ring)))
3080 (if (fboundp 'menu-bar-update-yank-menu)
3081 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4ed8c7aa
SS
3082 (when save-interprogram-paste-before-kill
3083 (let ((interprogram-paste (and interprogram-paste-function
3084 (funcall interprogram-paste-function))))
3085 (when interprogram-paste
0665f661
JL
3086 (dolist (s (if (listp interprogram-paste)
3087 (nreverse interprogram-paste)
3088 (list interprogram-paste)))
3089 (unless (and kill-do-not-save-duplicates
3090 (equal s (car kill-ring)))
3091 (push s kill-ring))))))
3092 (unless (and kill-do-not-save-duplicates
3093 (equal string (car kill-ring)))
3094 (if (and replace kill-ring)
3095 (setcar kill-ring string)
3096 (push string kill-ring)
3097 (if (> (length kill-ring) kill-ring-max)
3098 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
70e14c01
JB
3099 (setq kill-ring-yank-pointer kill-ring)
3100 (if interprogram-cut-function
08d4877e 3101 (funcall interprogram-cut-function string)))
9fca7811
SM
3102(set-advertised-calling-convention
3103 'kill-new '(string &optional replace) "23.3")
70e14c01 3104
be5936a7 3105(defun kill-append (string before-p &optional yank-handler)
70e14c01
JB
3106 "Append STRING to the end of the latest kill in the kill ring.
3107If BEFORE-P is non-nil, prepend STRING to the kill.
be5936a7
KS
3108If `interprogram-cut-function' is set, pass the resulting kill to it."
3109 (let* ((cur (car kill-ring)))
3110 (kill-new (if before-p (concat string cur) (concat cur string))
3111 (or (= (length cur) 0)
3112 (equal yank-handler (get-text-property 0 'yank-handler cur)))
3113 yank-handler)))
9fca7811 3114(set-advertised-calling-convention 'kill-append '(string before-p) "23.3")
70e14c01 3115
4496b02b
RS
3116(defcustom yank-pop-change-selection nil
3117 "If non-nil, rotating the kill ring changes the window system selection."
3118 :type 'boolean
3119 :group 'killing
3120 :version "23.1")
3121
70e14c01
JB
3122(defun current-kill (n &optional do-not-move)
3123 "Rotate the yanking point by N places, and then return that kill.
1d2b0303
JB
3124If N is zero, `interprogram-paste-function' is set, and calling
3125it returns a string or list of strings, then that string (or
3126list) is added to the front of the kill ring and the string (or
3127first string in the list) is returned as the latest kill.
4496b02b
RS
3128
3129If N is not zero, and if `yank-pop-change-selection' is
3130non-nil, use `interprogram-cut-function' to transfer the
3131kill at the new yank point into the window system selection.
3132
3133If optional arg DO-NOT-MOVE is non-nil, then don't actually
3134move the yanking point; just return the Nth kill forward."
3135
70e14c01
JB
3136 (let ((interprogram-paste (and (= n 0)
3137 interprogram-paste-function
3138 (funcall interprogram-paste-function))))
3139 (if interprogram-paste
3140 (progn
3141 ;; Disable the interprogram cut function when we add the new
3142 ;; text to the kill ring, so Emacs doesn't try to own the
3143 ;; selection, with identical text.
3144 (let ((interprogram-cut-function nil))
d4cb4833
GM
3145 (if (listp interprogram-paste)
3146 (mapc 'kill-new (nreverse interprogram-paste))
3147 (kill-new interprogram-paste)))
3148 (car kill-ring))
70e14c01 3149 (or kill-ring (error "Kill ring is empty"))
47096a67
PE
3150 (let ((ARGth-kill-element
3151 (nthcdr (mod (- n (length kill-ring-yank-pointer))
3152 (length kill-ring))
3153 kill-ring)))
4496b02b
RS
3154 (unless do-not-move
3155 (setq kill-ring-yank-pointer ARGth-kill-element)
3156 (when (and yank-pop-change-selection
3157 (> n 0)
3158 interprogram-cut-function)
3159 (funcall interprogram-cut-function (car ARGth-kill-element))))
70e14c01 3160 (car ARGth-kill-element)))))
c88ab9ce 3161
c88ab9ce 3162
eaae8106 3163
70e14c01 3164;;;; Commands for manipulating the kill ring.
c88ab9ce 3165
69c1dd37 3166(defcustom kill-read-only-ok nil
1d2b0303 3167 "Non-nil means don't signal an error for killing read-only text."
69c1dd37
RS
3168 :type 'boolean
3169 :group 'killing)
e6291fe1 3170
3a5da8a8
RS
3171(put 'text-read-only 'error-conditions
3172 '(text-read-only buffer-read-only error))
6d341a2a 3173(put 'text-read-only 'error-message (purecopy "Text is read-only"))
3a5da8a8 3174
be5936a7 3175(defun kill-region (beg end &optional yank-handler)
66e9b2b2
RS
3176 "Kill (\"cut\") text between point and mark.
3177This deletes the text from the buffer and saves it in the kill ring.
2076c87c 3178The command \\[yank] can retrieve it from there.
ba2b460a 3179\(If you want to save the region without killing it, use \\[kill-ring-save].)
81558867
EZ
3180
3181If you want to append the killed region to the last killed text,
3182use \\[append-next-kill] before \\[kill-region].
3183
2aa7a8bf
JB
3184If the buffer is read-only, Emacs will beep and refrain from deleting
3185the text, but put the text in the kill ring anyway. This means that
3186you can use the killing commands to copy text from a read-only buffer.
2076c87c 3187
a4aae1a5
CY
3188Lisp programs should use this function for killing text.
3189 (To delete text, use `delete-region'.)
c15dc81f 3190Supply two arguments, character positions indicating the stretch of text
2076c87c
JB
3191 to be killed.
3192Any command that calls this function is a \"kill command\".
3193If the previous command was also a kill command,
3194the text killed this time appends to the text killed last time
9fca7811 3195to make one entry in the kill ring."
214a3db0
RS
3196 ;; Pass point first, then mark, because the order matters
3197 ;; when calling kill-append.
3198 (interactive (list (point) (mark)))
f39d6be0
RS
3199 (unless (and beg end)
3200 (error "The mark is not set now, so there is no region"))
ccd19b9f 3201 (condition-case nil
7fcce20f 3202 (let ((string (filter-buffer-substring beg end t)))
a1eb02bd
SM
3203 (when string ;STRING is nil if BEG = END
3204 ;; Add that string to the kill ring, one way or another.
3205 (if (eq last-command 'kill-region)
be5936a7
KS
3206 (kill-append string (< end beg) yank-handler)
3207 (kill-new string nil yank-handler)))
8a7cda9b 3208 (when (or string (eq last-command 'kill-region))
6b61353c
KH
3209 (setq this-command 'kill-region))
3210 nil)
ccd19b9f
KH
3211 ((buffer-read-only text-read-only)
3212 ;; The code above failed because the buffer, or some of the characters
3213 ;; in the region, are read-only.
3214 ;; We should beep, in case the user just isn't aware of this.
3215 ;; However, there's no harm in putting
3216 ;; the region's text in the kill ring, anyway.
3217 (copy-region-as-kill beg end)
cb3e1b4c
RS
3218 ;; Set this-command now, so it will be set even if we get an error.
3219 (setq this-command 'kill-region)
3220 ;; This should barf, if appropriate, and give us the correct error.
ccd19b9f 3221 (if kill-read-only-ok
6b61353c 3222 (progn (message "Read only text copied to kill ring") nil)
ccd19b9f
KH
3223 ;; Signal an error if the buffer is read-only.
3224 (barf-if-buffer-read-only)
3225 ;; If the buffer isn't read-only, the text is.
3226 (signal 'text-read-only (list (current-buffer)))))))
9fca7811 3227(set-advertised-calling-convention 'kill-region '(beg end) "23.3")
2076c87c 3228
a382890a
KH
3229;; copy-region-as-kill no longer sets this-command, because it's confusing
3230;; to get two copies of the text when the user accidentally types M-w and
3231;; then corrects it with the intended C-w.
2076c87c
JB
3232(defun copy-region-as-kill (beg end)
3233 "Save the region as if killed, but don't kill it.
0e264847 3234In Transient Mark mode, deactivate the mark.
46947372 3235If `interprogram-cut-function' is non-nil, also save the text for a window
b66eb11b
RS
3236system cut and paste.
3237
3238This command's old key binding has been given to `kill-ring-save'."
2076c87c
JB
3239 (interactive "r")
3240 (if (eq last-command 'kill-region)
7fcce20f
RS
3241 (kill-append (filter-buffer-substring beg end) (< end beg))
3242 (kill-new (filter-buffer-substring beg end)))
d34c311a 3243 (setq deactivate-mark t)
2076c87c
JB
3244 nil)
3245
3246(defun kill-ring-save (beg end)
0964e562 3247 "Save the region as if killed, but don't kill it.
0e264847 3248In Transient Mark mode, deactivate the mark.
0964e562 3249If `interprogram-cut-function' is non-nil, also save the text for a window
0e264847
RS
3250system cut and paste.
3251
81558867
EZ
3252If you want to append the killed line to the last killed text,
3253use \\[append-next-kill] before \\[kill-ring-save].
3254
0e264847
RS
3255This command is similar to `copy-region-as-kill', except that it gives
3256visual feedback indicating the extent of the region being copied."
2076c87c
JB
3257 (interactive "r")
3258 (copy-region-as-kill beg end)
32226619 3259 ;; This use of called-interactively-p is correct
bbf41690 3260 ;; because the code it controls just gives the user visual feedback.
32226619 3261 (if (called-interactively-p 'interactive)
66050f10
RS
3262 (let ((other-end (if (= (point) beg) end beg))
3263 (opoint (point))
3264 ;; Inhibit quitting so we can make a quit here
3265 ;; look like a C-g typed as a command.
3266 (inhibit-quit t))
3267 (if (pos-visible-in-window-p other-end (selected-window))
d34c311a
SM
3268 ;; Swap point-and-mark quickly so as to show the region that
3269 ;; was selected. Don't do it if the region is highlighted.
3270 (unless (and (region-active-p)
977e2654 3271 (face-background 'region))
66050f10
RS
3272 ;; Swap point and mark.
3273 (set-marker (mark-marker) (point) (current-buffer))
3274 (goto-char other-end)
e4ef3e92 3275 (sit-for blink-matching-delay)
66050f10
RS
3276 ;; Swap back.
3277 (set-marker (mark-marker) other-end (current-buffer))
3278 (goto-char opoint)
3279 ;; If user quit, deactivate the mark
3280 ;; as C-g would as a command.
e4e593ae 3281 (and quit-flag mark-active
fcadf1c7 3282 (deactivate-mark)))
66050f10
RS
3283 (let* ((killed-text (current-kill 0))
3284 (message-len (min (length killed-text) 40)))
3285 (if (= (point) beg)
3286 ;; Don't say "killed"; that is misleading.
3287 (message "Saved text until \"%s\""
3288 (substring killed-text (- message-len)))
3289 (message "Saved text from \"%s\""
3290 (substring killed-text 0 message-len))))))))
2076c87c 3291
c75d4986
KH
3292(defun append-next-kill (&optional interactive)
3293 "Cause following command, if it kills, to append to previous kill.
3294The argument is used for internal purposes; do not supply one."
3295 (interactive "p")
3296 ;; We don't use (interactive-p), since that breaks kbd macros.
3297 (if interactive
2076c87c
JB
3298 (progn
3299 (setq this-command 'kill-region)
3300 (message "If the next command is a kill, it will append"))
3301 (setq last-command 'kill-region)))
cfb4f123 3302\f
93be67de 3303;; Yanking.
2076c87c 3304
cfb4f123
RS
3305;; This is actually used in subr.el but defcustom does not work there.
3306(defcustom yank-excluded-properties
be5936a7 3307 '(read-only invisible intangible field mouse-face help-echo local-map keymap
7408ee97 3308 yank-handler follow-link fontified)
3137dda8 3309 "Text properties to discard when yanking.
c6ff5a4c
LT
3310The value should be a list of text properties to discard or t,
3311which means to discard all text properties."
cfb4f123 3312 :type '(choice (const :tag "All" t) (repeat symbol))
c9f0110e 3313 :group 'killing
bf247b6e 3314 :version "22.1")
cfb4f123 3315
120de5bd 3316(defvar yank-window-start nil)
be5936a7 3317(defvar yank-undo-function nil
44f5a7b2
KS
3318 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
3319Function is called with two parameters, START and END corresponding to
3320the value of the mark and point; it is guaranteed that START <= END.
3321Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
120de5bd 3322
6b61353c 3323(defun yank-pop (&optional arg)
ff1fbe3e
RS
3324 "Replace just-yanked stretch of killed text with a different stretch.
3325This command is allowed only immediately after a `yank' or a `yank-pop'.
2076c87c 3326At such a time, the region contains a stretch of reinserted
ff1fbe3e 3327previously-killed text. `yank-pop' deletes that text and inserts in its
2076c87c
JB
3328place a different stretch of killed text.
3329
3330With no argument, the previous kill is inserted.
ff1fbe3e
RS
3331With argument N, insert the Nth previous kill.
3332If N is negative, this is a more recent kill.
2076c87c
JB
3333
3334The sequence of kills wraps around, so that after the oldest one
a0e8eaa3
EZ
3335comes the newest one.
3336
3337When this command inserts killed text into the buffer, it honors
3338`yank-excluded-properties' and `yank-handler' as described in the
3339doc string for `insert-for-yank-1', which see."
2076c87c
JB
3340 (interactive "*p")
3341 (if (not (eq last-command 'yank))
3342 (error "Previous command was not a yank"))
3343 (setq this-command 'yank)
6b61353c 3344 (unless arg (setq arg 1))
3a5da8a8
RS
3345 (let ((inhibit-read-only t)
3346 (before (< (point) (mark t))))
8254897f
KS
3347 (if before
3348 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
3349 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
be5936a7 3350 (setq yank-undo-function nil)
fd0f4056 3351 (set-marker (mark-marker) (point) (current-buffer))
cfb4f123 3352 (insert-for-yank (current-kill arg))
120de5bd
RS
3353 ;; Set the window start back where it was in the yank command,
3354 ;; if possible.
3355 (set-window-start (selected-window) yank-window-start t)
fd0f4056
RS
3356 (if before
3357 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3358 ;; It is cleaner to avoid activation, even though the command
3359 ;; loop would deactivate the mark because we inserted text.
3360 (goto-char (prog1 (mark t)
3361 (set-marker (mark-marker) (point) (current-buffer))))))
0964e562 3362 nil)
2076c87c
JB
3363
3364(defun yank (&optional arg)
f894e671 3365 "Reinsert (\"paste\") the last stretch of killed text.
2076c87c 3366More precisely, reinsert the stretch of killed text most recently
ff1fbe3e 3367killed OR yanked. Put point at end, and set mark at beginning.
d99f8496 3368With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
ff1fbe3e 3369With argument N, reinsert the Nth most recently killed stretch of killed
2076c87c 3370text.
a0e8eaa3
EZ
3371
3372When this command inserts killed text into the buffer, it honors
3373`yank-excluded-properties' and `yank-handler' as described in the
3374doc string for `insert-for-yank-1', which see.
3375
a9b9303c 3376See also the command `yank-pop' (\\[yank-pop])."
2076c87c 3377 (interactive "*P")
120de5bd 3378 (setq yank-window-start (window-start))
456c617c
RS
3379 ;; If we don't get all the way thru, make last-command indicate that
3380 ;; for the following command.
3381 (setq this-command t)
2076c87c 3382 (push-mark (point))
cfb4f123
RS
3383 (insert-for-yank (current-kill (cond
3384 ((listp arg) 0)
6b61353c 3385 ((eq arg '-) -2)
cfb4f123 3386 (t (1- arg)))))
2076c87c 3387 (if (consp arg)
fd0f4056
RS
3388 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3389 ;; It is cleaner to avoid activation, even though the command
3390 ;; loop would deactivate the mark because we inserted text.
3391 (goto-char (prog1 (mark t)
3392 (set-marker (mark-marker) (point) (current-buffer)))))
456c617c 3393 ;; If we do get all the way thru, make this-command indicate that.
be5936a7
KS
3394 (if (eq this-command t)
3395 (setq this-command 'yank))
0964e562 3396 nil)
70e14c01
JB
3397
3398(defun rotate-yank-pointer (arg)
3399 "Rotate the yanking point in the kill ring.
5626c14e 3400With ARG, rotate that many kills forward (or backward, if negative)."
70e14c01
JB
3401 (interactive "p")
3402 (current-kill arg))
2d88b556 3403\f
93be67de
KH
3404;; Some kill commands.
3405
3406;; Internal subroutine of delete-char
3407(defun kill-forward-chars (arg)
3408 (if (listp arg) (setq arg (car arg)))
3409 (if (eq arg '-) (setq arg -1))
673e5169 3410 (kill-region (point) (+ (point) arg)))
93be67de
KH
3411
3412;; Internal subroutine of backward-delete-char
3413(defun kill-backward-chars (arg)
3414 (if (listp arg) (setq arg (car arg)))
3415 (if (eq arg '-) (setq arg -1))
673e5169 3416 (kill-region (point) (- (point) arg)))
93be67de
KH
3417
3418(defcustom backward-delete-char-untabify-method 'untabify
1d2b0303 3419 "The method for untabifying when deleting backward.
1e722f9f
SS
3420Can be `untabify' -- turn a tab to many spaces, then delete one space;
3421 `hungry' -- delete all whitespace, both tabs and spaces;
3422 `all' -- delete all whitespace, including tabs, spaces and newlines;
93be67de 3423 nil -- just delete one character."
1e722f9f 3424 :type '(choice (const untabify) (const hungry) (const all) (const nil))
03167a34 3425 :version "20.3"
93be67de
KH
3426 :group 'killing)
3427
3428(defun backward-delete-char-untabify (arg &optional killp)
3429 "Delete characters backward, changing tabs into spaces.
3430The exact behavior depends on `backward-delete-char-untabify-method'.
3431Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
3432Interactively, ARG is the prefix arg (default 1)
3433and KILLP is t if a prefix arg was specified."
3434 (interactive "*p\nP")
3435 (when (eq backward-delete-char-untabify-method 'untabify)
3436 (let ((count arg))
3437 (save-excursion
3438 (while (and (> count 0) (not (bobp)))
3439 (if (= (preceding-char) ?\t)
3440 (let ((col (current-column)))
3441 (forward-char -1)
3442 (setq col (- col (current-column)))
f33321ad 3443 (insert-char ?\s col)
93be67de
KH
3444 (delete-char 1)))
3445 (forward-char -1)
3446 (setq count (1- count))))))
0b1596c6 3447 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
1e722f9f 3448 ((eq backward-delete-char-untabify-method 'all)
0b1596c6
JB
3449 " \t\n\r")))
3450 (n (if skip
3451 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
3452 (point)))))
3453 (+ arg (if (zerop wh) 0 (1- wh))))
3454 arg)))
3455 ;; Avoid warning about delete-backward-char
3456 (with-no-warnings (delete-backward-char n killp))))
93be67de
KH
3457
3458(defun zap-to-char (arg char)
5626c14e 3459 "Kill up to and including ARGth occurrence of CHAR.
93be67de
KH
3460Case is ignored if `case-fold-search' is non-nil in the current buffer.
3461Goes backward if ARG is negative; error if CHAR not found."
e761e42c 3462 (interactive "p\ncZap to char: ")
a6c39c14
EZ
3463 ;; Avoid "obsolete" warnings for translation-table-for-input.
3464 (with-no-warnings
3465 (if (char-table-p translation-table-for-input)
3466 (setq char (or (aref translation-table-for-input char) char))))
93be67de
KH
3467 (kill-region (point) (progn
3468 (search-forward (char-to-string char) nil nil arg)
3469; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
3470 (point))))
eaae8106 3471
93be67de
KH
3472;; kill-line and its subroutines.
3473
3474(defcustom kill-whole-line nil
1d2b0303 3475 "If non-nil, `kill-line' with no arg at beg of line kills the whole line."
93be67de
KH
3476 :type 'boolean
3477 :group 'killing)
3478
3479(defun kill-line (&optional arg)
3480 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
5626c14e 3481With prefix argument ARG, kill that many lines from point.
93be67de 3482Negative arguments kill lines backward.
8be7408c 3483With zero argument, kills the text before point on the current line.
93be67de
KH
3484
3485When calling from a program, nil means \"no arg\",
3486a number counts as a prefix arg.
3487
3488To kill a whole line, when point is not at the beginning, type \
602157ab 3489\\[move-beginning-of-line] \\[kill-line] \\[kill-line].
93be67de
KH
3490
3491If `kill-whole-line' is non-nil, then this command kills the whole line
3492including its terminating newline, when used at the beginning of a line
3493with no argument. As a consequence, you can always kill a whole line
602157ab 3494by typing \\[move-beginning-of-line] \\[kill-line].
d3f22784 3495
81558867
EZ
3496If you want to append the killed line to the last killed text,
3497use \\[append-next-kill] before \\[kill-line].
3498
d3f22784
EZ
3499If the buffer is read-only, Emacs will beep and refrain from deleting
3500the line, but put the line in the kill ring anyway. This means that
1a534b89
RS
3501you can use this command to copy text from a read-only buffer.
3502\(If the variable `kill-read-only-ok' is non-nil, then this won't
3503even beep.)"
e761e42c 3504 (interactive "P")
93be67de
KH
3505 (kill-region (point)
3506 ;; It is better to move point to the other end of the kill
3507 ;; before killing. That way, in a read-only buffer, point
3508 ;; moves across the text that is copied to the kill ring.
3509 ;; The choice has no effect on undo now that undo records
3510 ;; the value of point from before the command was run.
3511 (progn
3512 (if arg
3513 (forward-visible-line (prefix-numeric-value arg))
3514 (if (eobp)
3515 (signal 'end-of-buffer nil))
5560dc5d
RS
3516 (let ((end
3517 (save-excursion
3518 (end-of-visible-line) (point))))
3519 (if (or (save-excursion
6b61353c
KH
3520 ;; If trailing whitespace is visible,
3521 ;; don't treat it as nothing.
3522 (unless show-trailing-whitespace
3523 (skip-chars-forward " \t" end))
5560dc5d
RS
3524 (= (point) end))
3525 (and kill-whole-line (bolp)))
3526 (forward-visible-line 1)
3527 (goto-char end))))
93be67de
KH
3528 (point))))
3529
348de80b
KG
3530(defun kill-whole-line (&optional arg)
3531 "Kill current line.
5626c14e
JB
3532With prefix ARG, kill that many lines starting from the current line.
3533If ARG is negative, kill backward. Also kill the preceding newline.
01ba9662 3534\(This is meant to make \\[repeat] work well with negative arguments.\)
5626c14e 3535If ARG is zero, kill current line but exclude the trailing newline."
f8b0f284 3536 (interactive "p")
186133b4 3537 (or arg (setq arg 1))
6c770e38
LT
3538 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
3539 (signal 'end-of-buffer nil))
3540 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
3541 (signal 'beginning-of-buffer nil))
3542 (unless (eq last-command 'kill-region)
3543 (kill-new "")
3544 (setq last-command 'kill-region))
348de80b 3545 (cond ((zerop arg)
6c770e38
LT
3546 ;; We need to kill in two steps, because the previous command
3547 ;; could have been a kill command, in which case the text
3548 ;; before point needs to be prepended to the current kill
3549 ;; ring entry and the text after point appended. Also, we
3550 ;; need to use save-excursion to avoid copying the same text
3551 ;; twice to the kill ring in read-only buffers.
3552 (save-excursion
3553 (kill-region (point) (progn (forward-visible-line 0) (point))))
348de80b
KG
3554 (kill-region (point) (progn (end-of-visible-line) (point))))
3555 ((< arg 0)
6c770e38
LT
3556 (save-excursion
3557 (kill-region (point) (progn (end-of-visible-line) (point))))
3558 (kill-region (point)
3559 (progn (forward-visible-line (1+ arg))
3560 (unless (bobp) (backward-char))
3561 (point))))
348de80b 3562 (t
6c770e38
LT
3563 (save-excursion
3564 (kill-region (point) (progn (forward-visible-line 0) (point))))
3565 (kill-region (point)
3566 (progn (forward-visible-line arg) (point))))))
12a93712 3567
93be67de
KH
3568(defun forward-visible-line (arg)
3569 "Move forward by ARG lines, ignoring currently invisible newlines only.
3570If ARG is negative, move backward -ARG lines.
3571If ARG is zero, move to the beginning of the current line."
3572 (condition-case nil
3573 (if (> arg 0)
12a93712
RS
3574 (progn
3575 (while (> arg 0)
93be67de 3576 (or (zerop (forward-line 1))
12a93712
RS
3577 (signal 'end-of-buffer nil))
3578 ;; If the newline we just skipped is invisible,
3579 ;; don't count it.
3580 (let ((prop
3581 (get-char-property (1- (point)) 'invisible)))
3582 (if (if (eq buffer-invisibility-spec t)
3583 prop
3584 (or (memq prop buffer-invisibility-spec)
3585 (assq prop buffer-invisibility-spec)))
3586 (setq arg (1+ arg))))
3587 (setq arg (1- arg)))
3588 ;; If invisible text follows, and it is a number of complete lines,
3589 ;; skip it.
3590 (let ((opoint (point)))
3591 (while (and (not (eobp))
3592 (let ((prop
3593 (get-char-property (point) 'invisible)))
3594 (if (eq buffer-invisibility-spec t)
3595 prop
3596 (or (memq prop buffer-invisibility-spec)
3597 (assq prop buffer-invisibility-spec)))))
3598 (goto-char
3599 (if (get-text-property (point) 'invisible)
3600 (or (next-single-property-change (point) 'invisible)
3601 (point-max))
3602 (next-overlay-change (point)))))
3603 (unless (bolp)
3604 (goto-char opoint))))
93be67de 3605 (let ((first t))
f5fd8833
JB
3606 (while (or first (<= arg 0))
3607 (if first
93be67de
KH
3608 (beginning-of-line)
3609 (or (zerop (forward-line -1))
3610 (signal 'beginning-of-buffer nil)))
12a93712
RS
3611 ;; If the newline we just moved to is invisible,
3612 ;; don't count it.
3613 (unless (bobp)
3614 (let ((prop
3615 (get-char-property (1- (point)) 'invisible)))
f5fd8833
JB
3616 (unless (if (eq buffer-invisibility-spec t)
3617 prop
3618 (or (memq prop buffer-invisibility-spec)
3619 (assq prop buffer-invisibility-spec)))
3620 (setq arg (1+ arg)))))
3621 (setq first nil))
12a93712
RS
3622 ;; If invisible text follows, and it is a number of complete lines,
3623 ;; skip it.
3624 (let ((opoint (point)))
93be67de
KH
3625 (while (and (not (bobp))
3626 (let ((prop
3627 (get-char-property (1- (point)) 'invisible)))
3628 (if (eq buffer-invisibility-spec t)
3629 prop
3630 (or (memq prop buffer-invisibility-spec)
3631 (assq prop buffer-invisibility-spec)))))
3632 (goto-char
3633 (if (get-text-property (1- (point)) 'invisible)
3634 (or (previous-single-property-change (point) 'invisible)
3635 (point-min))
12a93712
RS
3636 (previous-overlay-change (point)))))
3637 (unless (bolp)
3638 (goto-char opoint)))))
93be67de
KH
3639 ((beginning-of-buffer end-of-buffer)
3640 nil)))
70e14c01 3641
93be67de
KH
3642(defun end-of-visible-line ()
3643 "Move to end of current visible line."
3644 (end-of-line)
3645 ;; If the following character is currently invisible,
3646 ;; skip all characters with that same `invisible' property value,
3647 ;; then find the next newline.
3648 (while (and (not (eobp))
5560dc5d
RS
3649 (save-excursion
3650 (skip-chars-forward "^\n")
3651 (let ((prop
3652 (get-char-property (point) 'invisible)))
3653 (if (eq buffer-invisibility-spec t)
3654 prop
3655 (or (memq prop buffer-invisibility-spec)
3656 (assq prop buffer-invisibility-spec))))))
3657 (skip-chars-forward "^\n")
93be67de
KH
3658 (if (get-text-property (point) 'invisible)
3659 (goto-char (next-single-property-change (point) 'invisible))
3660 (goto-char (next-overlay-change (point))))
3661 (end-of-line)))
2d88b556 3662\f
2076c87c
JB
3663(defun insert-buffer (buffer)
3664 "Insert after point the contents of BUFFER.
3665Puts mark after the inserted text.
6cb6e7a2
GM
3666BUFFER may be a buffer or a buffer name.
3667
3668This function is meant for the user to run interactively.
1e96c007 3669Don't call it from programs: use `insert-buffer-substring' instead!"
c3d4f949 3670 (interactive
a3e7c391
FP
3671 (list
3672 (progn
3673 (barf-if-buffer-read-only)
3674 (read-buffer "Insert buffer: "
3675 (if (eq (selected-window) (next-window (selected-window)))
3676 (other-buffer (current-buffer))
3677 (window-buffer (next-window (selected-window))))
3678 t))))
1e96c007
SM
3679 (push-mark
3680 (save-excursion
3681 (insert-buffer-substring (get-buffer buffer))
3682 (point)))
1537a263 3683 nil)
2076c87c
JB
3684
3685(defun append-to-buffer (buffer start end)
3686 "Append to specified buffer the text of the region.
3687It is inserted into that buffer before its point.
3688
3689When calling from a program, give three arguments:
3690BUFFER (or buffer name), START and END.
3691START and END specify the portion of the current buffer to be copied."
70e14c01 3692 (interactive
5d771766 3693 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
23efee2c 3694 (region-beginning) (region-end)))
85626eef
SM
3695 (let* ((oldbuf (current-buffer))
3696 (append-to (get-buffer-create buffer))
3697 (windows (get-buffer-window-list append-to t t))
3698 point)
3699 (save-excursion
3700 (with-current-buffer append-to
3701 (setq point (point))
3702 (barf-if-buffer-read-only)
3703 (insert-buffer-substring oldbuf start end)
3704 (dolist (window windows)
3705 (when (= (window-point window) point)
3706 (set-window-point window (point))))))))
2076c87c
JB
3707
3708(defun prepend-to-buffer (buffer start end)
3709 "Prepend to specified buffer the text of the region.
3710It is inserted into that buffer after its point.
3711
3712When calling from a program, give three arguments:
3713BUFFER (or buffer name), START and END.
3714START and END specify the portion of the current buffer to be copied."
3715 (interactive "BPrepend to buffer: \nr")
3716 (let ((oldbuf (current-buffer)))
7fdbcd83 3717 (with-current-buffer (get-buffer-create buffer)
74399eac 3718 (barf-if-buffer-read-only)
2076c87c
JB
3719 (save-excursion
3720 (insert-buffer-substring oldbuf start end)))))
3721
3722(defun copy-to-buffer (buffer start end)
3723 "Copy to specified buffer the text of the region.
3724It is inserted into that buffer, replacing existing text there.
3725
3726When calling from a program, give three arguments:
3727BUFFER (or buffer name), START and END.
3728START and END specify the portion of the current buffer to be copied."
3729 (interactive "BCopy to buffer: \nr")
3730 (let ((oldbuf (current-buffer)))
1b5fd09e 3731 (with-current-buffer (get-buffer-create buffer)
74399eac 3732 (barf-if-buffer-read-only)
2076c87c
JB
3733 (erase-buffer)
3734 (save-excursion
3735 (insert-buffer-substring oldbuf start end)))))
2d88b556 3736\f
62d1c1fc 3737(put 'mark-inactive 'error-conditions '(mark-inactive error))
8f43cbf3 3738(put 'mark-inactive 'error-message (purecopy "The mark is not active now"))
62d1c1fc 3739
0251bafb
RS
3740(defvar activate-mark-hook nil
3741 "Hook run when the mark becomes active.
3742It is also run at the end of a command, if the mark is active and
6cbb0bb0 3743it is possible that the region may have changed.")
0251bafb
RS
3744
3745(defvar deactivate-mark-hook nil
3746 "Hook run when the mark becomes inactive.")
3747
af39530e 3748(defun mark (&optional force)
f00239cf
RS
3749 "Return this buffer's mark value as integer, or nil if never set.
3750
3751In Transient Mark mode, this function signals an error if
3752the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3753or the argument FORCE is non-nil, it disregards whether the mark
3754is active, and returns an integer or nil in the usual way.
af39530e 3755
2076c87c
JB
3756If you are using this in an editing command, you are most likely making
3757a mistake; see the documentation of `set-mark'."
0e3a7b14 3758 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
af39530e 3759 (marker-position (mark-marker))
62d1c1fc 3760 (signal 'mark-inactive nil)))
2076c87c 3761
f9be2e35 3762(defsubst deactivate-mark (&optional force)
19d35374 3763 "Deactivate the mark by setting `mark-active' to nil.
f9be2e35
CY
3764Unless FORCE is non-nil, this function does nothing if Transient
3765Mark mode is disabled.
3766This function also runs `deactivate-mark-hook'."
3767 (when (or transient-mark-mode force)
7c23dd44
CY
3768 (when (and (if (eq select-active-regions 'only)
3769 (eq (car-safe transient-mark-mode) 'only)
3770 select-active-regions)
9852377f
CY
3771 (region-active-p)
3772 (display-selections-p))
3773 ;; The var `saved-region-selection', if non-nil, is the text in
3774 ;; the region prior to the last command modifying the buffer.
3775 ;; Set the selection to that, or to the current region.
3776 (cond (saved-region-selection
3777 (x-set-selection 'PRIMARY saved-region-selection)
3778 (setq saved-region-selection nil))
3779 ((/= (region-beginning) (region-end))
3780 (x-set-selection 'PRIMARY
3781 (buffer-substring-no-properties
1bcb9e65
CY
3782 (region-beginning)
3783 (region-end))))))
f9be2e35
CY
3784 (if (and (null force)
3785 (or (eq transient-mark-mode 'lambda)
3786 (and (eq (car-safe transient-mark-mode) 'only)
3787 (null (cdr transient-mark-mode)))))
3788 ;; When deactivating a temporary region, don't change
3789 ;; `mark-active' or run `deactivate-mark-hook'.
109cfe4e
CY
3790 (setq transient-mark-mode nil)
3791 (if (eq (car-safe transient-mark-mode) 'only)
3792 (setq transient-mark-mode (cdr transient-mark-mode)))
3793 (setq mark-active nil)
3794 (run-hooks 'deactivate-mark-hook))))
19d35374 3795
2977fc37
SM
3796(defun activate-mark ()
3797 "Activate the mark."
3798 (when (mark t)
3799 (setq mark-active t)
3800 (unless transient-mark-mode
9852377f 3801 (setq transient-mark-mode 'lambda))))
98b2fff4 3802
2076c87c
JB
3803(defun set-mark (pos)
3804 "Set this buffer's mark to POS. Don't use this function!
3805That is to say, don't use this function unless you want
3806the user to see that the mark has moved, and you want the previous
3807mark position to be lost.
3808
3809Normally, when a new mark is set, the old one should go on the stack.
f59006cb 3810This is why most applications should use `push-mark', not `set-mark'.
2076c87c 3811
ff1fbe3e 3812Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
3813purposes. The mark saves a location for the user's convenience.
3814Most editing commands should not alter the mark.
3815To remember a location for internal use in the Lisp program,
3816store it in a Lisp variable. Example:
3817
3818 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3819
fcadf1c7
RS
3820 (if pos
3821 (progn
3822 (setq mark-active t)
3823 (run-hooks 'activate-mark-hook)
3824 (set-marker (mark-marker) pos (current-buffer)))
24c22852 3825 ;; Normally we never clear mark-active except in Transient Mark mode.
f9be2e35
CY
3826 ;; But when we actually clear out the mark value too, we must
3827 ;; clear mark-active in any mode.
3828 (deactivate-mark t)
24c22852 3829 (set-marker (mark-marker) nil)))
2076c87c 3830
d03b9b31 3831(defcustom use-empty-active-region nil
6a9127b6
CY
3832 "Whether \"region-aware\" commands should act on empty regions.
3833If nil, region-aware commands treat empty regions as inactive.
3834If non-nil, region-aware commands treat the region as active as
3835long as the mark is active, even if the region is empty.
3836
58b356e9
CY
3837Region-aware commands are those that act on the region if it is
3838active and Transient Mark mode is enabled, and on the text near
3839point otherwise."
d03b9b31
RS
3840 :type 'boolean
3841 :version "23.1"
3842 :group 'editing-basics)
3843
cb3a9d33 3844(defun use-region-p ()
6a9127b6
CY
3845 "Return t if the region is active and it is appropriate to act on it.
3846This is used by commands that act specially on the region under
16f2e9fc 3847Transient Mark mode.
6a9127b6 3848
c876b263 3849The return value is t if Transient Mark mode is enabled and the
e5b826ae
CY
3850mark is active; furthermore, if `use-empty-active-region' is nil,
3851the region must not be empty. Otherwise, the return value is nil.
16f2e9fc
CY
3852
3853For some commands, it may be appropriate to ignore the value of
3854`use-empty-active-region'; in that case, use `region-active-p'."
d34c311a 3855 (and (region-active-p)
d03b9b31
RS
3856 (or use-empty-active-region (> (region-end) (region-beginning)))))
3857
02d52519 3858(defun region-active-p ()
afa39f21 3859 "Return t if Transient Mark mode is enabled and the mark is active.
6a9127b6 3860
16f2e9fc
CY
3861Some commands act specially on the region when Transient Mark
3862mode is enabled. Usually, such commands should use
3863`use-region-p' instead of this function, because `use-region-p'
3864also checks the value of `use-empty-active-region'."
02d52519
RS
3865 (and transient-mark-mode mark-active))
3866
2076c87c 3867(defvar mark-ring nil
e55e2267 3868 "The list of former marks of the current buffer, most recent first.")
2076c87c 3869(make-variable-buffer-local 'mark-ring)
e55e2267 3870(put 'mark-ring 'permanent-local t)
2076c87c 3871
69c1dd37 3872(defcustom mark-ring-max 16
1d2b0303 3873 "Maximum size of mark ring. Start discarding off end if gets this big."
69c1dd37
RS
3874 :type 'integer
3875 :group 'editing-basics)
2076c87c 3876
dc029f0b
RM
3877(defvar global-mark-ring nil
3878 "The list of saved global marks, most recent first.")
3879
69c1dd37 3880(defcustom global-mark-ring-max 16
1d2b0303 3881 "Maximum size of global mark ring. \
69c1dd37
RS
3882Start discarding off end if gets this big."
3883 :type 'integer
3884 :group 'editing-basics)
dc029f0b 3885
868c2f49 3886(defun pop-to-mark-command ()
5626c14e
JB
3887 "Jump to mark, and pop a new position for mark off the ring.
3888\(Does not affect global mark ring\)."
868c2f49
KS
3889 (interactive)
3890 (if (null (mark t))
3891 (error "No mark set in this buffer")
fb2c06a3
RS
3892 (if (= (point) (mark t))
3893 (message "Mark popped"))
868c2f49
KS
3894 (goto-char (mark t))
3895 (pop-mark)))
3896
d00ffe21 3897(defun push-mark-command (arg &optional nomsg)
868c2f49 3898 "Set mark at where point is.
5626c14e 3899If no prefix ARG and mark is already set there, just activate it.
d00ffe21 3900Display `Mark set' unless the optional second arg NOMSG is non-nil."
868c2f49
KS
3901 (interactive "P")
3902 (let ((mark (marker-position (mark-marker))))
3903 (if (or arg (null mark) (/= mark (point)))
d00ffe21 3904 (push-mark nil nomsg t)
868c2f49 3905 (setq mark-active t)
0251bafb 3906 (run-hooks 'activate-mark-hook)
d00ffe21
KS
3907 (unless nomsg
3908 (message "Mark activated")))))
868c2f49 3909
6a936796 3910(defcustom set-mark-command-repeat-pop nil
1d2b0303 3911 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
ebd2fc0d
RS
3912That means that C-u \\[set-mark-command] \\[set-mark-command]
3913will pop the mark twice, and
3914C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
3915will pop the mark three times.
3916
7b17b503 3917A value of nil means \\[set-mark-command]'s behavior does not change
ebd2fc0d 3918after C-u \\[set-mark-command]."
6a936796 3919 :type 'boolean
034ce0ec 3920 :group 'editing-basics)
6a936796 3921
125f7951
SM
3922(defcustom set-mark-default-inactive nil
3923 "If non-nil, setting the mark does not activate it.
3924This causes \\[set-mark-command] and \\[exchange-point-and-mark] to
0fc10137
JL
3925behave the same whether or not `transient-mark-mode' is enabled."
3926 :type 'boolean
3927 :group 'editing-basics
3928 :version "23.1")
125f7951 3929
2076c87c 3930(defun set-mark-command (arg)
fb2c06a3
RS
3931 "Set the mark where point is, or jump to the mark.
3932Setting the mark also alters the region, which is the text
3933between point and mark; this is the closest equivalent in
3934Emacs to what some editors call the \"selection\".
146adea3 3935
fb2c06a3
RS
3936With no prefix argument, set the mark at point, and push the
3937old mark position on local mark ring. Also push the old mark on
3938global mark ring, if the previous mark was set in another buffer.
146adea3 3939
17923ef2
CY
3940When Transient Mark Mode is off, immediately repeating this
3941command activates `transient-mark-mode' temporarily.
66ef2df9 3942
146adea3 3943With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
fb2c06a3 3944jump to the mark, and set the mark from
146adea3
EZ
3945position popped off the local mark ring \(this does not affect the global
3946mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
66ef2df9 3947mark ring \(see `pop-global-mark'\).
18c5df40 3948
2ef0a47e 3949If `set-mark-command-repeat-pop' is non-nil, repeating
146adea3 3950the \\[set-mark-command] command with no prefix argument pops the next position
2ef0a47e 3951off the local (or global) mark ring and jumps there.
66ef2df9 3952
fb2c06a3
RS
3953With \\[universal-argument] \\[universal-argument] as prefix
3954argument, unconditionally set mark where point is, even if
3955`set-mark-command-repeat-pop' is non-nil.
7cb42362 3956
ff1fbe3e 3957Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
3958purposes. See the documentation of `set-mark' for more information."
3959 (interactive "P")
109cfe4e
CY
3960 (cond ((eq transient-mark-mode 'lambda)
3961 (setq transient-mark-mode nil))
3962 ((eq (car-safe transient-mark-mode) 'only)
3963 (deactivate-mark)))
868c2f49 3964 (cond
18c5df40
KS
3965 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3966 (push-mark-command nil))
868c2f49 3967 ((not (eq this-command 'set-mark-command))
1841f9e3
KS
3968 (if arg
3969 (pop-to-mark-command)
3970 (push-mark-command t)))
6a936796
RS
3971 ((and set-mark-command-repeat-pop
3972 (eq last-command 'pop-to-mark-command))
66ef2df9
KS
3973 (setq this-command 'pop-to-mark-command)
3974 (pop-to-mark-command))
6a936796
RS
3975 ((and set-mark-command-repeat-pop
3976 (eq last-command 'pop-global-mark)
3977 (not arg))
66ef2df9
KS
3978 (setq this-command 'pop-global-mark)
3979 (pop-global-mark))
868c2f49 3980 (arg
1841f9e3 3981 (setq this-command 'pop-to-mark-command)
868c2f49 3982 (pop-to-mark-command))
2977fc37
SM
3983 ((eq last-command 'set-mark-command)
3984 (if (region-active-p)
3985 (progn
3986 (deactivate-mark)
3987 (message "Mark deactivated"))
3988 (activate-mark)
3989 (message "Mark activated")))
868c2f49 3990 (t
125f7951
SM
3991 (push-mark-command nil)
3992 (if set-mark-default-inactive (deactivate-mark)))))
2076c87c 3993
fd0f4056 3994(defun push-mark (&optional location nomsg activate)
2076c87c 3995 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
f1382a3d
RM
3996If the last global mark pushed was not in the current buffer,
3997also push LOCATION on the global mark ring.
fd0f4056 3998Display `Mark set' unless the optional second arg NOMSG is non-nil.
2076c87c 3999
ff1fbe3e 4000Novice Emacs Lisp programmers often try to use the mark for the wrong
9a1277dd
RS
4001purposes. See the documentation of `set-mark' for more information.
4002
de9606f0 4003In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
1a0d0b6a 4004 (unless (null (mark t))
2076c87c 4005 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
1a0d0b6a
JPW
4006 (when (> (length mark-ring) mark-ring-max)
4007 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
4008 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
9a1277dd 4009 (set-marker (mark-marker) (or location (point)) (current-buffer))
dc029f0b 4010 ;; Now push the mark on the global mark ring.
f1382a3d 4011 (if (and global-mark-ring
e08d3f7c 4012 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
f1382a3d
RM
4013 ;; The last global mark pushed was in this same buffer.
4014 ;; Don't push another one.
4015 nil
4016 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
1a0d0b6a
JPW
4017 (when (> (length global-mark-ring) global-mark-ring-max)
4018 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
4019 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
efcf38c7 4020 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
2076c87c 4021 (message "Mark set"))
8cdc660f
RS
4022 (if (or activate (not transient-mark-mode))
4023 (set-mark (mark t)))
2076c87c
JB
4024 nil)
4025
4026(defun pop-mark ()
4027 "Pop off mark ring into the buffer's actual mark.
4028Does not set point. Does nothing if mark ring is empty."
1a0d0b6a
JPW
4029 (when mark-ring
4030 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
4031 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
1a0d0b6a
JPW
4032 (move-marker (car mark-ring) nil)
4033 (if (null (mark t)) (ding))
0137bae6
JL
4034 (setq mark-ring (cdr mark-ring)))
4035 (deactivate-mark))
2076c87c 4036
c613687b
SM
4037(define-obsolete-function-alias
4038 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
868c2f49 4039(defun exchange-point-and-mark (&optional arg)
af39530e
RS
4040 "Put the mark where point is now, and point where the mark is now.
4041This command works even when the mark is not active,
868c2f49 4042and it reactivates the mark.
109cfe4e 4043
5626c14e 4044If Transient Mark mode is on, a prefix ARG deactivates the mark
109cfe4e 4045if it is active, and otherwise avoids reactivating it. If
5626c14e 4046Transient Mark mode is off, a prefix ARG enables Transient Mark
109cfe4e 4047mode temporarily."
868c2f49 4048 (interactive "P")
109cfe4e
CY
4049 (let ((omark (mark t))
4050 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
2977fc37
SM
4051 (if (null omark)
4052 (error "No mark set in this buffer"))
109cfe4e 4053 (deactivate-mark)
2977fc37
SM
4054 (set-mark (point))
4055 (goto-char omark)
125f7951 4056 (if set-mark-default-inactive (deactivate-mark))
109cfe4e
CY
4057 (cond (temp-highlight
4058 (setq transient-mark-mode (cons 'only transient-mark-mode)))
4059 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
4060 (not (or arg (region-active-p))))
4061 (deactivate-mark))
4062 (t (activate-mark)))
2977fc37 4063 nil))
e23c2c21 4064
11ff3b67 4065(defcustom shift-select-mode t
84db11d6
SM
4066 "When non-nil, shifted motion keys activate the mark momentarily.
4067
4068While the mark is activated in this way, any shift-translated point
4069motion key extends the region, and if Transient Mark mode was off, it
4070is temporarily turned on. Furthermore, the mark will be deactivated
4071by any subsequent point motion key that was not shift-translated, or
4072by any action that normally deactivates the mark in Transient Mark mode.
4073
4074See `this-command-keys-shift-translated' for the meaning of
11ff3b67
AS
4075shift-translation."
4076 :type 'boolean
4077 :group 'editing-basics)
84db11d6
SM
4078
4079(defun handle-shift-selection ()
337c561c
CY
4080 "Activate/deactivate mark depending on invocation thru shift translation.
4081This function is called by `call-interactively' when a command
4082with a `^' character in its `interactive' spec is invoked, before
4083running the command itself.
4084
4085If `shift-select-mode' is enabled and the command was invoked
4086through shift translation, set the mark and activate the region
4087temporarily, unless it was already set in this way. See
4088`this-command-keys-shift-translated' for the meaning of shift
4089translation.
4090
4091Otherwise, if the region has been activated temporarily,
4092deactivate it, and restore the variable `transient-mark-mode' to
4093its earlier value."
84db11d6 4094 (cond ((and shift-select-mode this-command-keys-shift-translated)
9852377f
CY
4095 (unless (and mark-active
4096 (eq (car-safe transient-mark-mode) 'only))
91023c68 4097 (setq transient-mark-mode
84db11d6
SM
4098 (cons 'only
4099 (unless (eq transient-mark-mode 'lambda)
4100 transient-mark-mode)))
4101 (push-mark nil nil t)))
4102 ((eq (car-safe transient-mark-mode) 'only)
4103 (setq transient-mark-mode (cdr transient-mark-mode))
4104 (deactivate-mark))))
109cfe4e 4105
6710df48 4106(define-minor-mode transient-mark-mode
e23c2c21 4107 "Toggle Transient Mark mode.
1d2b0303 4108With ARG, turn Transient Mark mode on if ARG is positive, off otherwise.
e23c2c21 4109
5dd1220d
RS
4110In Transient Mark mode, when the mark is active, the region is highlighted.
4111Changing the buffer \"deactivates\" the mark.
4112So do certain other operations that set the mark
4113but whose main purpose is something else--for example,
cfa70244
EZ
4114incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
4115
8e843bc4
EZ
4116You can also deactivate the mark by typing \\[keyboard-quit] or
4117\\[keyboard-escape-quit].
1465c66b 4118
cfa70244
EZ
4119Many commands change their behavior when Transient Mark mode is in effect
4120and the mark is active, by acting on the region instead of their usual
4c5f7215 4121default part of the buffer's text. Examples of such commands include
705a5933
JL
4122\\[comment-dwim], \\[flush-lines], \\[keep-lines], \
4123\\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
4124Invoke \\[apropos-documentation] and type \"transient\" or
4125\"mark.*active\" at the prompt, to see the documentation of
4126commands which are sensitive to the Transient Mark mode."
43d16385 4127 :global t
9d794026
GM
4128 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
4129 :variable transient-mark-mode)
109cfe4e 4130
d0c4882d
RS
4131(defvar widen-automatically t
4132 "Non-nil means it is ok for commands to call `widen' when they want to.
4133Some commands will do this in order to go to positions outside
4134the current accessible part of the buffer.
4135
4136If `widen-automatically' is nil, these commands will do something else
4137as a fallback, and won't change the buffer bounds.")
4138
38111a5a
SM
4139(defvar non-essential nil
4140 "Whether the currently executing code is performing an essential task.
4141This variable should be non-nil only when running code which should not
4142disturb the user. E.g. it can be used to prevent Tramp from prompting the
4143user for a password when we are simply scanning a set of files in the
4144background or displaying possible completions before the user even asked
4145for it.")
4146
dc029f0b
RM
4147(defun pop-global-mark ()
4148 "Pop off global mark ring and jump to the top location."
4149 (interactive)
52b6d445
RS
4150 ;; Pop entries which refer to non-existent buffers.
4151 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
4152 (setq global-mark-ring (cdr global-mark-ring)))
dc029f0b
RM
4153 (or global-mark-ring
4154 (error "No global mark set"))
4155 (let* ((marker (car global-mark-ring))
4156 (buffer (marker-buffer marker))
4157 (position (marker-position marker)))
34c31301
RS
4158 (setq global-mark-ring (nconc (cdr global-mark-ring)
4159 (list (car global-mark-ring))))
dc029f0b
RM
4160 (set-buffer buffer)
4161 (or (and (>= position (point-min))
4162 (<= position (point-max)))
d0c4882d 4163 (if widen-automatically
60aee8b2
RS
4164 (widen)
4165 (error "Global mark position is outside accessible part of buffer")))
dc029f0b
RM
4166 (goto-char position)
4167 (switch-to-buffer buffer)))
2d88b556 4168\f
95791033 4169(defcustom next-line-add-newlines nil
1d2b0303 4170 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
69c1dd37 4171 :type 'boolean
e1d6e383 4172 :version "21.1"
69c1dd37 4173 :group 'editing-basics)
38ebcf29 4174
295f6616 4175(defun next-line (&optional arg try-vscroll)
2076c87c 4176 "Move cursor vertically down ARG lines.
295f6616 4177Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
2076c87c
JB
4178If there is no character in the target line exactly under the current column,
4179the cursor is positioned after the character in that line which spans this
4180column, or at the end of the line if it is not long enough.
38ebcf29 4181If there is no line in the buffer after this one, behavior depends on the
1a2c3941
RS
4182value of `next-line-add-newlines'. If non-nil, it inserts a newline character
4183to create a line, and moves the cursor to that line. Otherwise it moves the
e47d38f6 4184cursor to the end of the buffer.
2076c87c 4185
53a22af4
CY
4186If the variable `line-move-visual' is non-nil, this command moves
4187by display lines. Otherwise, it moves by buffer lines, without
4188taking variable-width characters or continued lines into account.
4189
2076c87c 4190The command \\[set-goal-column] can be used to create
85969cb1
RS
4191a semipermanent goal column for this command.
4192Then instead of trying to move exactly vertically (or as close as possible),
4193this command moves to the specified goal column (or as close as possible).
4194The goal column is stored in the variable `goal-column', which is nil
4195when there is no goal column.
2076c87c
JB
4196
4197If you are thinking of using this in a Lisp program, consider
4198using `forward-line' instead. It is usually easier to use
4199and more reliable (no dependence on goal column, etc.)."
109cfe4e 4200 (interactive "^p\np")
6b61353c 4201 (or arg (setq arg 1))
028922cf 4202 (if (and next-line-add-newlines (= arg 1))
207d7545
GM
4203 (if (save-excursion (end-of-line) (eobp))
4204 ;; When adding a newline, don't expand an abbrev.
4205 (let ((abbrev-mode nil))
24886813 4206 (end-of-line)
15575807 4207 (insert (if use-hard-newlines hard-newline "\n")))
295f6616 4208 (line-move arg nil nil try-vscroll))
32226619 4209 (if (called-interactively-p 'interactive)
1cd095c6 4210 (condition-case err
295f6616 4211 (line-move arg nil nil try-vscroll)
1cd095c6
JL
4212 ((beginning-of-buffer end-of-buffer)
4213 (signal (car err) (cdr err))))
295f6616 4214 (line-move arg nil nil try-vscroll)))
2076c87c
JB
4215 nil)
4216
295f6616 4217(defun previous-line (&optional arg try-vscroll)
2076c87c 4218 "Move cursor vertically up ARG lines.
295f6616 4219Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
2076c87c
JB
4220If there is no character in the target line exactly over the current column,
4221the cursor is positioned after the character in that line which spans this
4222column, or at the end of the line if it is not long enough.
4223
53a22af4
CY
4224If the variable `line-move-visual' is non-nil, this command moves
4225by display lines. Otherwise, it moves by buffer lines, without
4226taking variable-width characters or continued lines into account.
4227
2076c87c 4228The command \\[set-goal-column] can be used to create
85969cb1
RS
4229a semipermanent goal column for this command.
4230Then instead of trying to move exactly vertically (or as close as possible),
4231this command moves to the specified goal column (or as close as possible).
4232The goal column is stored in the variable `goal-column', which is nil
4233when there is no goal column.
2076c87c
JB
4234
4235If you are thinking of using this in a Lisp program, consider using
c2e8a012 4236`forward-line' with a negative argument instead. It is usually easier
2076c87c 4237to use and more reliable (no dependence on goal column, etc.)."
109cfe4e 4238 (interactive "^p\np")
6b61353c 4239 (or arg (setq arg 1))
32226619 4240 (if (called-interactively-p 'interactive)
1cd095c6 4241 (condition-case err
295f6616 4242 (line-move (- arg) nil nil try-vscroll)
1cd095c6
JL
4243 ((beginning-of-buffer end-of-buffer)
4244 (signal (car err) (cdr err))))
295f6616 4245 (line-move (- arg) nil nil try-vscroll))
2076c87c 4246 nil)
eaae8106 4247
69c1dd37 4248(defcustom track-eol nil
1d2b0303 4249 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
2076c87c 4250This means moving to the end of each line moved onto.
4efebb82
CY
4251The beginning of a blank line does not count as the end of a line.
4252This has no effect when `line-move-visual' is non-nil."
69c1dd37
RS
4253 :type 'boolean
4254 :group 'editing-basics)
4255
4256(defcustom goal-column nil
1d2b0303 4257 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
69c1dd37
RS
4258 :type '(choice integer
4259 (const :tag "None" nil))
4260 :group 'editing-basics)
912c6728 4261(make-variable-buffer-local 'goal-column)
2076c87c
JB
4262
4263(defvar temporary-goal-column 0
4264 "Current goal column for vertical motion.
4efebb82 4265It is the column where point was at the start of the current run
774409a1
CY
4266of vertical motion commands.
4267
4268When moving by visual lines via `line-move-visual', it is a cons
4269cell (COL . HSCROLL), where COL is the x-position, in pixels,
4270divided by the default column width, and HSCROLL is the number of
4271columns by which window is scrolled from left margin.
4272
4273When the `track-eol' feature is doing its job, the value is
4efebb82 4274`most-positive-fixnum'.")
2076c87c 4275
bbf41690 4276(defcustom line-move-ignore-invisible t
1d2b0303 4277 "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
69c1dd37
RS
4278Outline mode sets this."
4279 :type 'boolean
4280 :group 'editing-basics)
098fc1fb 4281
a2cf21a2 4282(defcustom line-move-visual t
4efebb82
CY
4283 "When non-nil, `line-move' moves point by visual lines.
4284This movement is based on where the cursor is displayed on the
4285screen, instead of relying on buffer contents alone. It takes
66e0718b
CY
4286into account variable-width characters and line continuation.
4287If nil, `line-move' moves point by logical lines."
a2cf21a2 4288 :type 'boolean
66e0718b
CY
4289 :group 'editing-basics
4290 :version "23.1")
4efebb82 4291
b704b1f0
KS
4292;; Returns non-nil if partial move was done.
4293(defun line-move-partial (arg noerror to-end)
4294 (if (< arg 0)
4295 ;; Move backward (up).
4296 ;; If already vscrolled, reduce vscroll
4297 (let ((vs (window-vscroll nil t)))
4298 (when (> vs (frame-char-height))
4299 (set-window-vscroll nil (- vs (frame-char-height)) t)))
4300
4301 ;; Move forward (down).
e437f99a
KS
4302 (let* ((lh (window-line-height -1))
4303 (vpos (nth 1 lh))
4304 (ypos (nth 2 lh))
4305 (rbot (nth 3 lh))
3137dda8 4306 py vs)
e437f99a
KS
4307 (when (or (null lh)
4308 (>= rbot (frame-char-height))
4309 (<= ypos (- (frame-char-height))))
4310 (unless lh
0e7a5039
KS
4311 (let ((wend (pos-visible-in-window-p t nil t)))
4312 (setq rbot (nth 3 wend)
4313 vpos (nth 5 wend))))
e437f99a
KS
4314 (cond
4315 ;; If last line of window is fully visible, move forward.
4316 ((or (null rbot) (= rbot 0))
4317 nil)
4318 ;; If cursor is not in the bottom scroll margin, move forward.
4319 ((and (> vpos 0)
95f5a37f
KS
4320 (< (setq py
4321 (or (nth 1 (window-line-height))
4322 (let ((ppos (posn-at-point)))
4323 (cdr (or (posn-actual-col-row ppos)
4324 (posn-col-row ppos))))))
e437f99a
KS
4325 (min (- (window-text-height) scroll-margin 1) (1- vpos))))
4326 nil)
4327 ;; When already vscrolled, we vscroll some more if we can,
4328 ;; or clear vscroll and move forward at end of tall image.
4329 ((> (setq vs (window-vscroll nil t)) 0)
4330 (when (> rbot 0)
4331 (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
4332 ;; If cursor just entered the bottom scroll margin, move forward,
4333 ;; but also vscroll one line so redisplay wont recenter.
4334 ((and (> vpos 0)
4335 (= py (min (- (window-text-height) scroll-margin 1)
4336 (1- vpos))))
4337 (set-window-vscroll nil (frame-char-height) t)
4338 (line-move-1 arg noerror to-end)
4339 t)
4340 ;; If there are lines above the last line, scroll-up one line.
4341 ((> vpos 0)
4342 (scroll-up 1)
4343 t)
4344 ;; Finally, start vscroll.
4345 (t
4346 (set-window-vscroll nil (frame-char-height) t)))))))
b704b1f0
KS
4347
4348
03ceda9e
RS
4349;; This is like line-move-1 except that it also performs
4350;; vertical scrolling of tall images if appropriate.
4351;; That is not really a clean thing to do, since it mixes
4352;; scrolling with cursor motion. But so far we don't have
4353;; a cleaner solution to the problem of making C-n do something
4354;; useful given a tall image.
ed02c1db 4355(defun line-move (arg &optional noerror to-end try-vscroll)
b704b1f0
KS
4356 (unless (and auto-window-vscroll try-vscroll
4357 ;; Only vscroll for single line moves
4358 (= (abs arg) 1)
4359 ;; But don't vscroll in a keyboard macro.
4360 (not defining-kbd-macro)
4361 (not executing-kbd-macro)
4362 (line-move-partial arg noerror to-end))
4363 (set-window-vscroll nil 0 t)
4efebb82
CY
4364 (if line-move-visual
4365 (line-move-visual arg noerror)
4366 (line-move-1 arg noerror to-end))))
4367
4368;; Display-based alternative to line-move-1.
4369;; Arg says how many lines to move. The value is t if we can move the
4370;; specified number of lines.
4371(defun line-move-visual (arg &optional noerror)
34be836c 4372 (let ((opoint (point))
774409a1 4373 (hscroll (window-hscroll))
34be836c 4374 target-hscroll)
774409a1
CY
4375 ;; Check if the previous command was a line-motion command, or if
4376 ;; we were called from some other command.
34be836c
CY
4377 (if (and (consp temporary-goal-column)
4378 (memq last-command `(next-line previous-line ,this-command)))
4379 ;; If so, there's no need to reset `temporary-goal-column',
4380 ;; but we may need to hscroll.
4381 (if (or (/= (cdr temporary-goal-column) hscroll)
4382 (> (cdr temporary-goal-column) 0))
4383 (setq target-hscroll (cdr temporary-goal-column)))
4384 ;; Otherwise, we should reset `temporary-goal-column'.
4385 (let ((posn (posn-at-point)))
4386 (cond
4387 ;; Handle the `overflow-newline-into-fringe' case:
4388 ((eq (nth 1 posn) 'right-fringe)
4389 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
4390 ((car (posn-x-y posn))
4391 (setq temporary-goal-column
4392 (cons (/ (float (car (posn-x-y posn)))
4393 (frame-char-width)) hscroll))))))
4394 (if target-hscroll
4395 (set-window-hscroll (selected-window) target-hscroll))
624a662f 4396 (or (and (= (vertical-motion
774409a1
CY
4397 (cons (or goal-column
4398 (if (consp temporary-goal-column)
5a66ed0f 4399 (car temporary-goal-column)
774409a1
CY
4400 temporary-goal-column))
4401 arg))
624a662f
CY
4402 arg)
4403 (or (>= arg 0)
4404 (/= (point) opoint)
4405 ;; If the goal column lies on a display string,
4406 ;; `vertical-motion' advances the cursor to the end
4407 ;; of the string. For arg < 0, this can cause the
4408 ;; cursor to get stuck. (Bug#3020).
4409 (= (vertical-motion arg) arg)))
4410 (unless noerror
4411 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
4412 nil)))))
16c2f92f 4413
8c745744
RS
4414;; This is the guts of next-line and previous-line.
4415;; Arg says how many lines to move.
bbf41690 4416;; The value is t if we can move the specified number of lines.
06b60517 4417(defun line-move-1 (arg &optional noerror _to-end)
2596511d
RS
4418 ;; Don't run any point-motion hooks, and disregard intangibility,
4419 ;; for intermediate positions.
4420 (let ((inhibit-point-motion-hooks t)
4421 (opoint (point))
fef11f15 4422 (orig-arg arg))
774409a1
CY
4423 (if (consp temporary-goal-column)
4424 (setq temporary-goal-column (+ (car temporary-goal-column)
4425 (cdr temporary-goal-column))))
2596511d
RS
4426 (unwind-protect
4427 (progn
41d22ee0 4428 (if (not (memq last-command '(next-line previous-line)))
2596511d
RS
4429 (setq temporary-goal-column
4430 (if (and track-eol (eolp)
4431 ;; Don't count beg of empty line as end of line
4432 ;; unless we just did explicit end-of-line.
ab9623c2 4433 (or (not (bolp)) (eq last-command 'move-end-of-line)))
3137dda8 4434 most-positive-fixnum
2596511d 4435 (current-column))))
bbf41690 4436
3137dda8
SM
4437 (if (not (or (integerp selective-display)
4438 line-move-ignore-invisible))
2596511d 4439 ;; Use just newline characters.
e9cd25fe 4440 ;; Set ARG to 0 if we move as many lines as requested.
2596511d
RS
4441 (or (if (> arg 0)
4442 (progn (if (> arg 1) (forward-line (1- arg)))
4443 ;; This way of moving forward ARG lines
4444 ;; verifies that we have a newline after the last one.
4445 ;; It doesn't get confused by intangible text.
4446 (end-of-line)
e9cd25fe
RS
4447 (if (zerop (forward-line 1))
4448 (setq arg 0)))
2596511d 4449 (and (zerop (forward-line arg))
e9cd25fe
RS
4450 (bolp)
4451 (setq arg 0)))
bbf41690
RS
4452 (unless noerror
4453 (signal (if (< arg 0)
4454 'beginning-of-buffer
4455 'end-of-buffer)
4456 nil)))
2596511d 4457 ;; Move by arg lines, but ignore invisible ones.
07889873 4458 (let (done)
bbf41690
RS
4459 (while (and (> arg 0) (not done))
4460 ;; If the following character is currently invisible,
4461 ;; skip all characters with that same `invisible' property value.
c65e6942 4462 (while (and (not (eobp)) (invisible-p (point)))
bbf41690 4463 (goto-char (next-char-property-change (point))))
fef11f15
CY
4464 ;; Move a line.
4465 ;; We don't use `end-of-line', since we want to escape
40b1a3a9 4466 ;; from field boundaries occurring exactly at point.
07889873
CY
4467 (goto-char (constrain-to-field
4468 (let ((inhibit-field-text-motion t))
4469 (line-end-position))
4470 (point) t t
4471 'inhibit-line-move-field-capture))
e9ab825f 4472 ;; If there's no invisibility here, move over the newline.
3e43ae87
KS
4473 (cond
4474 ((eobp)
4475 (if (not noerror)
4476 (signal 'end-of-buffer nil)
4477 (setq done t)))
4478 ((and (> arg 1) ;; Use vertical-motion for last move
4479 (not (integerp selective-display))
c65e6942 4480 (not (invisible-p (point))))
3e43ae87
KS
4481 ;; We avoid vertical-motion when possible
4482 ;; because that has to fontify.
4483 (forward-line 1))
4484 ;; Otherwise move a more sophisticated way.
4485 ((zerop (vertical-motion 1))
4486 (if (not noerror)
4487 (signal 'end-of-buffer nil)
4488 (setq done t))))
bbf41690
RS
4489 (unless done
4490 (setq arg (1- arg))))
22c8bff1 4491 ;; The logic of this is the same as the loop above,
e9ab825f 4492 ;; it just goes in the other direction.
bbf41690 4493 (while (and (< arg 0) (not done))
ac6701ea
CY
4494 ;; For completely consistency with the forward-motion
4495 ;; case, we should call beginning-of-line here.
4496 ;; However, if point is inside a field and on a
4497 ;; continued line, the call to (vertical-motion -1)
4498 ;; below won't move us back far enough; then we return
4499 ;; to the same column in line-move-finish, and point
4500 ;; gets stuck -- cyd
4501 (forward-line 0)
3e43ae87
KS
4502 (cond
4503 ((bobp)
4504 (if (not noerror)
4505 (signal 'beginning-of-buffer nil)
4506 (setq done t)))
4507 ((and (< arg -1) ;; Use vertical-motion for last move
4508 (not (integerp selective-display))
c65e6942 4509 (not (invisible-p (1- (point)))))
3e43ae87
KS
4510 (forward-line -1))
4511 ((zerop (vertical-motion -1))
4512 (if (not noerror)
4513 (signal 'beginning-of-buffer nil)
4514 (setq done t))))
bbf41690
RS
4515 (unless done
4516 (setq arg (1+ arg))
4517 (while (and ;; Don't move over previous invis lines
4518 ;; if our target is the middle of this line.
4519 (or (zerop (or goal-column temporary-goal-column))
4520 (< arg 0))
c65e6942 4521 (not (bobp)) (invisible-p (1- (point))))
bbf41690
RS
4522 (goto-char (previous-char-property-change (point))))))))
4523 ;; This is the value the function returns.
4524 (= arg 0))
af894fc9 4525
e9cd25fe 4526 (cond ((> arg 0)
2a1e0c92
CY
4527 ;; If we did not move down as far as desired, at least go
4528 ;; to end of line. Be sure to call point-entered and
4529 ;; point-left-hooks.
4530 (let* ((npoint (prog1 (line-end-position)
4531 (goto-char opoint)))
4532 (inhibit-point-motion-hooks nil))
4533 (goto-char npoint)))
e9cd25fe 4534 ((< arg 0)
f9872a6b
JL
4535 ;; If we did not move up as far as desired,
4536 ;; at least go to beginning of line.
2a1e0c92
CY
4537 (let* ((npoint (prog1 (line-beginning-position)
4538 (goto-char opoint)))
4539 (inhibit-point-motion-hooks nil))
4540 (goto-char npoint)))
e9cd25fe 4541 (t
20782abb 4542 (line-move-finish (or goal-column temporary-goal-column)
fef11f15 4543 opoint (> orig-arg 0)))))))
2076c87c 4544
20782abb 4545(defun line-move-finish (column opoint forward)
af894fc9
RS
4546 (let ((repeat t))
4547 (while repeat
4548 ;; Set REPEAT to t to repeat the whole thing.
4549 (setq repeat nil)
4550
1f980920 4551 (let (new
963355a4 4552 (old (point))
5ed619e0 4553 (line-beg (line-beginning-position))
1f980920
RS
4554 (line-end
4555 ;; Compute the end of the line
20782abb 4556 ;; ignoring effectively invisible newlines.
bbf41690 4557 (save-excursion
a5b4a6a0
RS
4558 ;; Like end-of-line but ignores fields.
4559 (skip-chars-forward "^\n")
c65e6942 4560 (while (and (not (eobp)) (invisible-p (point)))
20782abb 4561 (goto-char (next-char-property-change (point)))
a5b4a6a0 4562 (skip-chars-forward "^\n"))
bbf41690 4563 (point))))
1f980920
RS
4564
4565 ;; Move to the desired column.
54b99340 4566 (line-move-to-column (truncate column))
963355a4
CY
4567
4568 ;; Corner case: suppose we start out in a field boundary in
4569 ;; the middle of a continued line. When we get to
4570 ;; line-move-finish, point is at the start of a new *screen*
4571 ;; line but the same text line; then line-move-to-column would
4572 ;; move us backwards. Test using C-n with point on the "x" in
4573 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
4574 (and forward
4575 (< (point) old)
4576 (goto-char old))
4577
1f980920 4578 (setq new (point))
af894fc9
RS
4579
4580 ;; Process intangibility within a line.
594a1605
CY
4581 ;; With inhibit-point-motion-hooks bound to nil, a call to
4582 ;; goto-char moves point past intangible text.
4583
4584 ;; However, inhibit-point-motion-hooks controls both the
4585 ;; intangibility and the point-entered/point-left hooks. The
4586 ;; following hack avoids calling the point-* hooks
4587 ;; unnecessarily. Note that we move *forward* past intangible
4588 ;; text when the initial and final points are the same.
d584e29d 4589 (goto-char new)
af894fc9
RS
4590 (let ((inhibit-point-motion-hooks nil))
4591 (goto-char new)
4592
4593 ;; If intangibility moves us to a different (later) place
4594 ;; in the same line, use that as the destination.
4595 (if (<= (point) line-end)
1f980920
RS
4596 (setq new (point))
4597 ;; If that position is "too late",
4598 ;; try the previous allowable position.
4599 ;; See if it is ok.
4600 (backward-char)
20782abb
RS
4601 (if (if forward
4602 ;; If going forward, don't accept the previous
4603 ;; allowable position if it is before the target line.
f1e2a033 4604 (< line-beg (point))
20782abb
RS
4605 ;; If going backward, don't accept the previous
4606 ;; allowable position if it is still after the target line.
4607 (<= (point) line-end))
1f980920
RS
4608 (setq new (point))
4609 ;; As a last resort, use the end of the line.
4610 (setq new line-end))))
af894fc9
RS
4611
4612 ;; Now move to the updated destination, processing fields
4613 ;; as well as intangibility.
4614 (goto-char opoint)
4615 (let ((inhibit-point-motion-hooks nil))
4616 (goto-char
e94e78cc
CY
4617 ;; Ignore field boundaries if the initial and final
4618 ;; positions have the same `field' property, even if the
4619 ;; fields are non-contiguous. This seems to be "nicer"
4620 ;; behavior in many situations.
4621 (if (eq (get-char-property new 'field)
4622 (get-char-property opoint 'field))
4623 new
4624 (constrain-to-field new opoint t t
4625 'inhibit-line-move-field-capture))))
af894fc9 4626
1f980920 4627 ;; If all this moved us to a different line,
af894fc9
RS
4628 ;; retry everything within that new line.
4629 (when (or (< (point) line-beg) (> (point) line-end))
4630 ;; Repeat the intangibility and field processing.
4631 (setq repeat t))))))
4632
4633(defun line-move-to-column (col)
4634 "Try to find column COL, considering invisibility.
4635This function works only in certain cases,
4636because what we really need is for `move-to-column'
4637and `current-column' to be able to ignore invisible text."
a615252b
RS
4638 (if (zerop col)
4639 (beginning-of-line)
095f9ae4 4640 (move-to-column col))
af894fc9
RS
4641
4642 (when (and line-move-ignore-invisible
c65e6942 4643 (not (bolp)) (invisible-p (1- (point))))
af894fc9
RS
4644 (let ((normal-location (point))
4645 (normal-column (current-column)))
4646 ;; If the following character is currently invisible,
4647 ;; skip all characters with that same `invisible' property value.
4648 (while (and (not (eobp))
c65e6942 4649 (invisible-p (point)))
af894fc9
RS
4650 (goto-char (next-char-property-change (point))))
4651 ;; Have we advanced to a larger column position?
4652 (if (> (current-column) normal-column)
4653 ;; We have made some progress towards the desired column.
4654 ;; See if we can make any further progress.
4655 (line-move-to-column (+ (current-column) (- col normal-column)))
4656 ;; Otherwise, go to the place we originally found
4657 ;; and move back over invisible text.
4658 ;; that will get us to the same place on the screen
4659 ;; but with a more reasonable buffer position.
4660 (goto-char normal-location)
5ed619e0 4661 (let ((line-beg (line-beginning-position)))
c65e6942 4662 (while (and (not (bolp)) (invisible-p (1- (point))))
af894fc9
RS
4663 (goto-char (previous-char-property-change (point) line-beg))))))))
4664
bbf41690 4665(defun move-end-of-line (arg)
f00239cf 4666 "Move point to end of current line as displayed.
bbf41690
RS
4667With argument ARG not nil or 1, move forward ARG - 1 lines first.
4668If point reaches the beginning or end of buffer, it stops there.
fdb77e6f
CY
4669
4670To ignore the effects of the `intangible' text or overlay
4671property, bind `inhibit-point-motion-hooks' to t.
4672If there is an image in the current line, this function
4673disregards newlines that are part of the text on which the image
4674rests."
109cfe4e 4675 (interactive "^p")
bbf41690
RS
4676 (or arg (setq arg 1))
4677 (let (done)
4678 (while (not done)
4679 (let ((newpos
4680 (save-excursion
4efebb82
CY
4681 (let ((goal-column 0)
4682 (line-move-visual nil))
bbf41690 4683 (and (line-move arg t)
3f2e7735
EZ
4684 ;; With bidi reordering, we may not be at bol,
4685 ;; so make sure we are.
4686 (skip-chars-backward "^\n")
bbf41690
RS
4687 (not (bobp))
4688 (progn
c65e6942 4689 (while (and (not (bobp)) (invisible-p (1- (point))))
3137dda8
SM
4690 (goto-char (previous-single-char-property-change
4691 (point) 'invisible)))
bbf41690
RS
4692 (backward-char 1)))
4693 (point)))))
4694 (goto-char newpos)
4695 (if (and (> (point) newpos)
4696 (eq (preceding-char) ?\n))
4697 (backward-char 1)
4698 (if (and (> (point) newpos) (not (eobp))
4699 (not (eq (following-char) ?\n)))
4efebb82
CY
4700 ;; If we skipped something intangible and now we're not
4701 ;; really at eol, keep going.
bbf41690
RS
4702 (setq arg 1)
4703 (setq done t)))))))
4704
0cbb497c 4705(defun move-beginning-of-line (arg)
f00239cf
RS
4706 "Move point to beginning of current line as displayed.
4707\(If there's an image in the line, this disregards newlines
4708which are part of the text that the image rests on.)
4709
0cbb497c
KS
4710With argument ARG not nil or 1, move forward ARG - 1 lines first.
4711If point reaches the beginning or end of buffer, it stops there.
f00239cf 4712To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
109cfe4e 4713 (interactive "^p")
0cbb497c 4714 (or arg (setq arg 1))
398c9ffb 4715
ad47c4a0 4716 (let ((orig (point))
3137dda8 4717 first-vis first-vis-field-value)
1fffd65f
RS
4718
4719 ;; Move by lines, if ARG is not 1 (the default).
4720 (if (/= arg 1)
4efebb82
CY
4721 (let ((line-move-visual nil))
4722 (line-move (1- arg) t)))
1fffd65f
RS
4723
4724 ;; Move to beginning-of-line, ignoring fields and invisibles.
4725 (skip-chars-backward "^\n")
c65e6942 4726 (while (and (not (bobp)) (invisible-p (1- (point))))
621a4cc8 4727 (goto-char (previous-char-property-change (point)))
1fffd65f 4728 (skip-chars-backward "^\n"))
ad47c4a0
RS
4729
4730 ;; Now find first visible char in the line
c65e6942 4731 (while (and (not (eobp)) (invisible-p (point)))
ad47c4a0
RS
4732 (goto-char (next-char-property-change (point))))
4733 (setq first-vis (point))
4734
4735 ;; See if fields would stop us from reaching FIRST-VIS.
4736 (setq first-vis-field-value
4737 (constrain-to-field first-vis orig (/= arg 1) t nil))
4738
4739 (goto-char (if (/= first-vis-field-value first-vis)
4740 ;; If yes, obey them.
4741 first-vis-field-value
4742 ;; Otherwise, move to START with attention to fields.
4743 ;; (It is possible that fields never matter in this case.)
4744 (constrain-to-field (point) orig
4745 (/= arg 1) t nil)))))
0cbb497c
KS
4746
4747
85be9ec4
SM
4748;; Many people have said they rarely use this feature, and often type
4749;; it by accident. Maybe it shouldn't even be on a key.
d5ab2033 4750(put 'set-goal-column 'disabled t)
2076c87c
JB
4751
4752(defun set-goal-column (arg)
4753 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
4754Those commands will move to this position in the line moved to
4755rather than trying to keep the same horizontal position.
5626c14e 4756With a non-nil argument ARG, clears out the goal column
912c6728
RS
4757so that \\[next-line] and \\[previous-line] resume vertical motion.
4758The goal column is stored in the variable `goal-column'."
2076c87c
JB
4759 (interactive "P")
4760 (if arg
4761 (progn
4762 (setq goal-column nil)
4763 (message "No goal column"))
4764 (setq goal-column (current-column))
8a26c165
DG
4765 ;; The older method below can be erroneous if `set-goal-column' is bound
4766 ;; to a sequence containing %
4767 ;;(message (substitute-command-keys
4768 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
4769 ;;goal-column)
4770 (message "%s"
63219d53 4771 (concat
8a26c165
DG
4772 (format "Goal column %d " goal-column)
4773 (substitute-command-keys
4774 "(use \\[set-goal-column] with an arg to unset it)")))
63219d53 4775
8a26c165 4776 )
2076c87c 4777 nil)
2d88b556 4778\f
a2cf21a2
CY
4779;;; Editing based on visual lines, as opposed to logical lines.
4780
4781(defun end-of-visual-line (&optional n)
4782 "Move point to end of current visual line.
4783With argument N not nil or 1, move forward N - 1 visual lines first.
4784If point reaches the beginning or end of buffer, it stops there.
4785To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4786 (interactive "^p")
4787 (or n (setq n 1))
4788 (if (/= n 1)
4789 (let ((line-move-visual t))
4790 (line-move (1- n) t)))
ef187c24
CY
4791 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
4792 ;; constrain to field boundaries, so we don't either.
a2cf21a2
CY
4793 (vertical-motion (cons (window-width) 0)))
4794
4795(defun beginning-of-visual-line (&optional n)
4796 "Move point to beginning of current visual line.
4797With argument N not nil or 1, move forward N - 1 visual lines first.
4798If point reaches the beginning or end of buffer, it stops there.
4799To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4800 (interactive "^p")
4801 (or n (setq n 1))
ef187c24
CY
4802 (let ((opoint (point)))
4803 (if (/= n 1)
4804 (let ((line-move-visual t))
4805 (line-move (1- n) t)))
4806 (vertical-motion 0)
4807 ;; Constrain to field boundaries, like `move-beginning-of-line'.
4808 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
a2cf21a2
CY
4809
4810(defun kill-visual-line (&optional arg)
4811 "Kill the rest of the visual line.
ad4c1f62
CY
4812With prefix argument ARG, kill that many visual lines from point.
4813If ARG is negative, kill visual lines backward.
4814If ARG is zero, kill the text before point on the current visual
4815line.
a2cf21a2
CY
4816
4817If you want to append the killed line to the last killed text,
4818use \\[append-next-kill] before \\[kill-line].
4819
4820If the buffer is read-only, Emacs will beep and refrain from deleting
4821the line, but put the line in the kill ring anyway. This means that
4822you can use this command to copy text from a read-only buffer.
4823\(If the variable `kill-read-only-ok' is non-nil, then this won't
4824even beep.)"
4825 (interactive "P")
ad4c1f62
CY
4826 ;; Like in `kill-line', it's better to move point to the other end
4827 ;; of the kill before killing.
2066b4fe
CY
4828 (let ((opoint (point))
4829 (kill-whole-line (and kill-whole-line (bolp))))
a2cf21a2
CY
4830 (if arg
4831 (vertical-motion (prefix-numeric-value arg))
ad4c1f62
CY
4832 (end-of-visual-line 1)
4833 (if (= (point) opoint)
4834 (vertical-motion 1)
4835 ;; Skip any trailing whitespace at the end of the visual line.
4836 ;; We used to do this only if `show-trailing-whitespace' is
4837 ;; nil, but that's wrong; the correct thing would be to check
4838 ;; whether the trailing whitespace is highlighted. But, it's
4839 ;; OK to just do this unconditionally.
4840 (skip-chars-forward " \t")))
2066b4fe
CY
4841 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
4842 (1+ (point))
4843 (point)))))
a2cf21a2
CY
4844
4845(defun next-logical-line (&optional arg try-vscroll)
4846 "Move cursor vertically down ARG lines.
1d2b0303 4847This is identical to `next-line', except that it always moves
a2cf21a2
CY
4848by logical lines instead of visual lines, ignoring the value of
4849the variable `line-move-visual'."
4850 (interactive "^p\np")
4851 (let ((line-move-visual nil))
4852 (with-no-warnings
4853 (next-line arg try-vscroll))))
4854
4855(defun previous-logical-line (&optional arg try-vscroll)
4856 "Move cursor vertically up ARG lines.
4857This is identical to `previous-line', except that it always moves
4858by logical lines instead of visual lines, ignoring the value of
4859the variable `line-move-visual'."
4860 (interactive "^p\np")
4861 (let ((line-move-visual nil))
4862 (with-no-warnings
4863 (previous-line arg try-vscroll))))
4864
4dec5cff
CY
4865(defgroup visual-line nil
4866 "Editing based on visual lines."
4867 :group 'convenience
4868 :version "23.1")
4869
a2cf21a2
CY
4870(defvar visual-line-mode-map
4871 (let ((map (make-sparse-keymap)))
4872 (define-key map [remap kill-line] 'kill-visual-line)
4873 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
4874 (define-key map [remap move-end-of-line] 'end-of-visual-line)
b316b2b8
CY
4875 ;; These keybindings interfere with xterm function keys. Are
4876 ;; there any other suitable bindings?
4877 ;; (define-key map "\M-[" 'previous-logical-line)
4878 ;; (define-key map "\M-]" 'next-logical-line)
a2cf21a2
CY
4879 map))
4880
4dec5cff
CY
4881(defcustom visual-line-fringe-indicators '(nil nil)
4882 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
4883The value should be a list of the form (LEFT RIGHT), where LEFT
4884and RIGHT are symbols representing the bitmaps to display, to
4885indicate wrapped lines, in the left and right fringes respectively.
4886See also `fringe-indicator-alist'.
4887The default is not to display fringe indicators for wrapped lines.
4888This variable does not affect fringe indicators displayed for
4889other purposes."
4890 :type '(list (choice (const :tag "Hide left indicator" nil)
4891 (const :tag "Left curly arrow" left-curly-arrow)
4892 (symbol :tag "Other bitmap"))
4893 (choice (const :tag "Hide right indicator" nil)
4894 (const :tag "Right curly arrow" right-curly-arrow)
4895 (symbol :tag "Other bitmap")))
4896 :set (lambda (symbol value)
4897 (dolist (buf (buffer-list))
4898 (with-current-buffer buf
4899 (when (and (boundp 'visual-line-mode)
4900 (symbol-value 'visual-line-mode))
4901 (setq fringe-indicator-alist
4902 (cons (cons 'continuation value)
4903 (assq-delete-all
4904 'continuation
4905 (copy-tree fringe-indicator-alist)))))))
4906 (set-default symbol value)))
4907
748e001a
CY
4908(defvar visual-line--saved-state nil)
4909
a2cf21a2 4910(define-minor-mode visual-line-mode
b677cb96
CY
4911 "Redefine simple editing commands to act on visual lines, not logical lines.
4912This also turns on `word-wrap' in the buffer."
a2cf21a2 4913 :keymap visual-line-mode-map
4dec5cff 4914 :group 'visual-line
ea92f9f3 4915 :lighter " Wrap"
a2cf21a2
CY
4916 (if visual-line-mode
4917 (progn
748e001a
CY
4918 (set (make-local-variable 'visual-line--saved-state) nil)
4919 ;; Save the local values of some variables, to be restored if
4920 ;; visual-line-mode is turned off.
4921 (dolist (var '(line-move-visual truncate-lines
4922 truncate-partial-width-windows
4923 word-wrap fringe-indicator-alist))
4924 (if (local-variable-p var)
37820ea9 4925 (push (cons var (symbol-value var))
748e001a 4926 visual-line--saved-state)))
a2cf21a2 4927 (set (make-local-variable 'line-move-visual) t)
c58140f4
CY
4928 (set (make-local-variable 'truncate-partial-width-windows) nil)
4929 (setq truncate-lines nil
4930 word-wrap t
4931 fringe-indicator-alist
4dec5cff
CY
4932 (cons (cons 'continuation visual-line-fringe-indicators)
4933 fringe-indicator-alist)))
a2cf21a2 4934 (kill-local-variable 'line-move-visual)
4dec5cff 4935 (kill-local-variable 'word-wrap)
c58140f4
CY
4936 (kill-local-variable 'truncate-lines)
4937 (kill-local-variable 'truncate-partial-width-windows)
748e001a
CY
4938 (kill-local-variable 'fringe-indicator-alist)
4939 (dolist (saved visual-line--saved-state)
4940 (set (make-local-variable (car saved)) (cdr saved)))
4941 (kill-local-variable 'visual-line--saved-state)))
a2cf21a2
CY
4942
4943(defun turn-on-visual-line-mode ()
4944 (visual-line-mode 1))
4945
4946(define-globalized-minor-mode global-visual-line-mode
4947 visual-line-mode turn-on-visual-line-mode
4948 :lighter " vl")
5a97d2da 4949
2d88b556 4950\f
2076c87c
JB
4951(defun transpose-chars (arg)
4952 "Interchange characters around point, moving forward one character.
4953With prefix arg ARG, effect is to take character before point
4954and drag it forward past ARG other characters (backward if ARG negative).
4955If no argument and at end of line, the previous two chars are exchanged."
4956 (interactive "*P")
4957 (and (null arg) (eolp) (forward-char -1))
4958 (transpose-subr 'forward-char (prefix-numeric-value arg)))
4959
4960(defun transpose-words (arg)
4961 "Interchange words around point, leaving point at end of them.
4962With prefix arg ARG, effect is to take word before or around point
4963and drag it forward past ARG other words (backward if ARG negative).
4964If ARG is zero, the words around or after point and around or after mark
4965are interchanged."
41d22ee0 4966 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
2076c87c
JB
4967 (interactive "*p")
4968 (transpose-subr 'forward-word arg))
4969
4970(defun transpose-sexps (arg)
4971 "Like \\[transpose-words] but applies to sexps.
4972Does not work on a sexp that point is in the middle of
4973if it is a list or string."
4974 (interactive "*p")
41d22ee0
SM
4975 (transpose-subr
4976 (lambda (arg)
4977 ;; Here we should try to simulate the behavior of
4978 ;; (cons (progn (forward-sexp x) (point))
4979 ;; (progn (forward-sexp (- x)) (point)))
4980 ;; Except that we don't want to rely on the second forward-sexp
4981 ;; putting us back to where we want to be, since forward-sexp-function
4982 ;; might do funny things like infix-precedence.
4983 (if (if (> arg 0)
4984 (looking-at "\\sw\\|\\s_")
4985 (and (not (bobp))
4986 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
4987 ;; Jumping over a symbol. We might be inside it, mind you.
4988 (progn (funcall (if (> arg 0)
4989 'skip-syntax-backward 'skip-syntax-forward)
4990 "w_")
4991 (cons (save-excursion (forward-sexp arg) (point)) (point)))
4992 ;; Otherwise, we're between sexps. Take a step back before jumping
4993 ;; to make sure we'll obey the same precedence no matter which direction
4994 ;; we're going.
4995 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
4996 (cons (save-excursion (forward-sexp arg) (point))
4997 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
4998 (not (zerop (funcall (if (> arg 0)
4999 'skip-syntax-forward
5000 'skip-syntax-backward)
5001 ".")))))
5002 (point)))))
5003 arg 'special))
2076c87c
JB
5004
5005(defun transpose-lines (arg)
5006 "Exchange current line and previous line, leaving point after both.
5007With argument ARG, takes previous line and moves it past ARG lines.
5008With argument 0, interchanges line point is in with line mark is in."
5009 (interactive "*p")
5010 (transpose-subr (function
5011 (lambda (arg)
d3f4ef3f 5012 (if (> arg 0)
2076c87c 5013 (progn
d3f4ef3f
AS
5014 ;; Move forward over ARG lines,
5015 ;; but create newlines if necessary.
5016 (setq arg (forward-line arg))
5017 (if (/= (preceding-char) ?\n)
5018 (setq arg (1+ arg)))
5019 (if (> arg 0)
5020 (newline arg)))
2076c87c
JB
5021 (forward-line arg))))
5022 arg))
5023
36020642
GM
5024;; FIXME seems to leave point BEFORE the current object when ARG = 0,
5025;; which seems inconsistent with the ARG /= 0 case.
5026;; FIXME document SPECIAL.
e1e04350 5027(defun transpose-subr (mover arg &optional special)
36020642
GM
5028 "Subroutine to do the work of transposing objects.
5029Works for lines, sentences, paragraphs, etc. MOVER is a function that
5030moves forward by units of the given object (e.g. forward-sentence,
5031forward-paragraph). If ARG is zero, exchanges the current object
5032with the one containing mark. If ARG is an integer, moves the
5033current object past ARG following (if ARG is positive) or
5034preceding (if ARG is negative) objects, leaving point after the
5035current object."
e1e04350
SM
5036 (let ((aux (if special mover
5037 (lambda (x)
5038 (cons (progn (funcall mover x) (point))
5039 (progn (funcall mover (- x)) (point))))))
5040 pos1 pos2)
5041 (cond
5042 ((= arg 0)
5043 (save-excursion
5044 (setq pos1 (funcall aux 1))
41849bf9 5045 (goto-char (or (mark) (error "No mark set in this buffer")))
e1e04350
SM
5046 (setq pos2 (funcall aux 1))
5047 (transpose-subr-1 pos1 pos2))
5048 (exchange-point-and-mark))
5049 ((> arg 0)
5050 (setq pos1 (funcall aux -1))
5051 (setq pos2 (funcall aux arg))
5052 (transpose-subr-1 pos1 pos2)
5053 (goto-char (car pos2)))
5054 (t
5055 (setq pos1 (funcall aux -1))
5056 (goto-char (car pos1))
5057 (setq pos2 (funcall aux arg))
5058 (transpose-subr-1 pos1 pos2)))))
5059
5060(defun transpose-subr-1 (pos1 pos2)
5061 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
5062 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
5063 (when (> (car pos1) (car pos2))
5064 (let ((swap pos1))
5065 (setq pos1 pos2 pos2 swap)))
5066 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
dc7d7552
RS
5067 (atomic-change-group
5068 (let (word2)
1e96c007
SM
5069 ;; FIXME: We first delete the two pieces of text, so markers that
5070 ;; used to point to after the text end up pointing to before it :-(
dc7d7552
RS
5071 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
5072 (goto-char (car pos2))
5073 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
5074 (goto-char (car pos1))
5075 (insert word2))))
2d88b556 5076\f
6b61353c 5077(defun backward-word (&optional arg)
b7e91b0c 5078 "Move backward until encountering the beginning of a word.
5626c14e 5079With argument ARG, do this that many times."
109cfe4e 5080 (interactive "^p")
6b61353c 5081 (forward-word (- (or arg 1))))
2076c87c 5082
a1a801de 5083(defun mark-word (&optional arg allow-extend)
705a5933
JL
5084 "Set mark ARG words away from point.
5085The place mark goes is the same place \\[forward-word] would
5086move to with the same argument.
a1a801de 5087Interactively, if this command is repeated
771069f8 5088or (in Transient Mark mode) if the mark is active,
705a5933 5089it marks the next ARG words after the ones already marked."
a1a801de
RS
5090 (interactive "P\np")
5091 (cond ((and allow-extend
5092 (or (and (eq last-command this-command) (mark t))
d34c311a 5093 (region-active-p)))
705a5933
JL
5094 (setq arg (if arg (prefix-numeric-value arg)
5095 (if (< (mark) (point)) -1 1)))
cad113ae
KG
5096 (set-mark
5097 (save-excursion
5098 (goto-char (mark))
5099 (forward-word arg)
5100 (point))))
5101 (t
5102 (push-mark
5103 (save-excursion
705a5933 5104 (forward-word (prefix-numeric-value arg))
cad113ae
KG
5105 (point))
5106 nil t))))
2076c87c
JB
5107
5108(defun kill-word (arg)
5109 "Kill characters forward until encountering the end of a word.
5626c14e 5110With argument ARG, do this that many times."
e761e42c 5111 (interactive "p")
89ee2bf6 5112 (kill-region (point) (progn (forward-word arg) (point))))
2076c87c
JB
5113
5114(defun backward-kill-word (arg)
654ec269 5115 "Kill characters backward until encountering the beginning of a word.
5626c14e 5116With argument ARG, do this that many times."
e761e42c 5117 (interactive "p")
2076c87c 5118 (kill-word (- arg)))
d7c64071 5119
0f7df535
RS
5120(defun current-word (&optional strict really-word)
5121 "Return the symbol or word that point is on (or a nearby one) as a string.
5122The return value includes no text properties.
1e8c5ac4 5123If optional arg STRICT is non-nil, return nil unless point is within
0fa19a57
RS
5124or adjacent to a symbol or word. In all cases the value can be nil
5125if there is no word nearby.
0f7df535
RS
5126The function, belying its name, normally finds a symbol.
5127If optional arg REALLY-WORD is non-nil, it finds just a word."
d7c64071 5128 (save-excursion
0f7df535 5129 (let* ((oldpoint (point)) (start (point)) (end (point))
81d17173 5130 (syntaxes (if really-word "w" "w_"))
0f7df535
RS
5131 (not-syntaxes (concat "^" syntaxes)))
5132 (skip-syntax-backward syntaxes) (setq start (point))
d7c64071 5133 (goto-char oldpoint)
0f7df535
RS
5134 (skip-syntax-forward syntaxes) (setq end (point))
5135 (when (and (eq start oldpoint) (eq end oldpoint)
5136 ;; Point is neither within nor adjacent to a word.
5137 (not strict))
5138 ;; Look for preceding word in same line.
9b026d9f 5139 (skip-syntax-backward not-syntaxes (line-beginning-position))
0f7df535
RS
5140 (if (bolp)
5141 ;; No preceding word in same line.
5142 ;; Look for following word in same line.
5143 (progn
9b026d9f 5144 (skip-syntax-forward not-syntaxes (line-end-position))
0f7df535
RS
5145 (setq start (point))
5146 (skip-syntax-forward syntaxes)
5147 (setq end (point)))
5148 (setq end (point))
5149 (skip-syntax-backward syntaxes)
5150 (setq start (point))))
5151 ;; If we found something nonempty, return it as a string.
5152 (unless (= start end)
020db25f 5153 (buffer-substring-no-properties start end)))))
2d88b556 5154\f
69c1dd37 5155(defcustom fill-prefix nil
1d2b0303 5156 "String for filling to insert at front of new line, or nil for none."
69c1dd37
RS
5157 :type '(choice (const :tag "None" nil)
5158 string)
5159 :group 'fill)
2076c87c 5160(make-variable-buffer-local 'fill-prefix)
f31b1257 5161(put 'fill-prefix 'safe-local-variable 'string-or-null-p)
2076c87c 5162
69c1dd37 5163(defcustom auto-fill-inhibit-regexp nil
1d2b0303 5164 "Regexp to match lines which should not be auto-filled."
69c1dd37
RS
5165 :type '(choice (const :tag "None" nil)
5166 regexp)
5167 :group 'fill)
2076c87c
JB
5168
5169(defun do-auto-fill ()
ce558208
GM
5170 "The default value for `normal-auto-fill-function'.
5171This is the default auto-fill function, some major modes use a different one.
5172Returns t if it really did any work."
621a3f62 5173 (let (fc justify give-up
a0170800 5174 (fill-prefix fill-prefix))
c18465c4 5175 (if (or (not (setq justify (current-justification)))
8f066a20
RS
5176 (null (setq fc (current-fill-column)))
5177 (and (eq justify 'left)
5178 (<= (current-column) fc))
621a3f62
SM
5179 (and auto-fill-inhibit-regexp
5180 (save-excursion (beginning-of-line)
eed5698b
RS
5181 (looking-at auto-fill-inhibit-regexp))))
5182 nil ;; Auto-filling not required
3db1e3b5
BG
5183 (if (memq justify '(full center right))
5184 (save-excursion (unjustify-current-line)))
a0170800
RS
5185
5186 ;; Choose a fill-prefix automatically.
e1e04350
SM
5187 (when (and adaptive-fill-mode
5188 (or (null fill-prefix) (string= fill-prefix "")))
5189 (let ((prefix
5190 (fill-context-prefix
5191 (save-excursion (backward-paragraph 1) (point))
5192 (save-excursion (forward-paragraph 1) (point)))))
5193 (and prefix (not (equal prefix ""))
5194 ;; Use auto-indentation rather than a guessed empty prefix.
0e53a373 5195 (not (and fill-indent-according-to-mode
d99f8496 5196 (string-match "\\`[ \t]*\\'" prefix)))
e1e04350 5197 (setq fill-prefix prefix))))
f1180544 5198
eed5698b 5199 (while (and (not give-up) (> (current-column) fc))
e47d38f6 5200 ;; Determine where to split the line.
db893d00
RS
5201 (let* (after-prefix
5202 (fill-point
621a3f62
SM
5203 (save-excursion
5204 (beginning-of-line)
5205 (setq after-prefix (point))
5206 (and fill-prefix
5207 (looking-at (regexp-quote fill-prefix))
5208 (setq after-prefix (match-end 0)))
5209 (move-to-column (1+ fc))
5210 (fill-move-to-break-point after-prefix)
5211 (point))))
db893d00
RS
5212
5213 ;; See whether the place we found is any good.
e47d38f6
RS
5214 (if (save-excursion
5215 (goto-char fill-point)
41d22ee0
SM
5216 (or (bolp)
5217 ;; There is no use breaking at end of line.
5218 (save-excursion (skip-chars-forward " ") (eolp))
5219 ;; It is futile to split at the end of the prefix
5220 ;; since we would just insert the prefix again.
5221 (and after-prefix (<= (point) after-prefix))
5222 ;; Don't split right after a comment starter
5223 ;; since we would just make another comment starter.
5224 (and comment-start-skip
5225 (let ((limit (point)))
5226 (beginning-of-line)
5227 (and (re-search-forward comment-start-skip
5228 limit t)
5229 (eq (point) limit))))))
5230 ;; No good place to break => stop trying.
5231 (setq give-up t)
5232 ;; Ok, we have a useful place to break the line. Do it.
5233 (let ((prev-column (current-column)))
5234 ;; If point is at the fill-point, do not `save-excursion'.
5235 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
5236 ;; point will end up before it rather than after it.
5237 (if (save-excursion
5238 (skip-chars-backward " \t")
5239 (= (point) fill-point))
0b727f9d 5240 (default-indent-new-line t)
41d22ee0
SM
5241 (save-excursion
5242 (goto-char fill-point)
0b727f9d 5243 (default-indent-new-line t)))
41d22ee0
SM
5244 ;; Now do justification, if required
5245 (if (not (eq justify 'left))
e47d38f6 5246 (save-excursion
e1e04350
SM
5247 (end-of-line 0)
5248 (justify-current-line justify nil t)))
41d22ee0
SM
5249 ;; If making the new line didn't reduce the hpos of
5250 ;; the end of the line, then give up now;
5251 ;; trying again will not help.
5252 (if (>= (current-column) prev-column)
5253 (setq give-up t))))))
24ebf92e 5254 ;; Justify last line.
e2504204 5255 (justify-current-line justify t t)
1e722f9f 5256 t)))
2076c87c 5257
0b727f9d
RS
5258(defvar comment-line-break-function 'comment-indent-new-line
5259 "*Mode-specific function which line breaks and continues a comment.
5260This function is called during auto-filling when a comment syntax
5261is defined.
5262The function should take a single optional argument, which is a flag
5263indicating whether it should use soft newlines.")
5264
5265(defun default-indent-new-line (&optional soft)
5266 "Break line at point and indent.
5267If a comment syntax is defined, call `comment-indent-new-line'.
5268
5269The inserted newline is marked hard if variable `use-hard-newlines' is true,
5270unless optional argument SOFT is non-nil."
5271 (interactive)
5272 (if comment-start
5273 (funcall comment-line-break-function soft)
5274 ;; Insert the newline before removing empty space so that markers
5275 ;; get preserved better.
5276 (if soft (insert-and-inherit ?\n) (newline 1))
5277 (save-excursion (forward-char -1) (delete-horizontal-space))
5278 (delete-horizontal-space)
5279
5280 (if (and fill-prefix (not adaptive-fill-mode))
5281 ;; Blindly trust a non-adaptive fill-prefix.
5282 (progn
5283 (indent-to-left-margin)
5284 (insert-before-markers-and-inherit fill-prefix))
5285
5286 (cond
5287 ;; If there's an adaptive prefix, use it unless we're inside
5288 ;; a comment and the prefix is not a comment starter.
5289 (fill-prefix
5290 (indent-to-left-margin)
5291 (insert-and-inherit fill-prefix))
5292 ;; If we're not inside a comment, just try to indent.
5293 (t (indent-according-to-mode))))))
5294
24ebf92e
RS
5295(defvar normal-auto-fill-function 'do-auto-fill
5296 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
5297Some major modes set this.")
5298
c75505b4 5299(put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
74ab01ff
SM
5300;; `functions' and `hooks' are usually unsafe to set, but setting
5301;; auto-fill-function to nil in a file-local setting is safe and
5302;; can be useful to prevent auto-filling.
5303(put 'auto-fill-function 'safe-local-variable 'null)
d99f8496
SM
5304;; FIXME: turn into a proper minor mode.
5305;; Add a global minor mode version of it.
80ac5d4d 5306(define-minor-mode auto-fill-mode
24ebf92e 5307 "Toggle Auto Fill mode.
1d2b0303 5308With ARG, turn Auto Fill mode on if and only if ARG is positive.
24ebf92e
RS
5309In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
5310automatically breaks the line at a previous space.
5311
5312The value of `normal-auto-fill-function' specifies the function to use
5313for `auto-fill-function' when turning Auto Fill mode on."
80ac5d4d 5314 :variable (eq auto-fill-function normal-auto-fill-function))
d7465b15
RS
5315
5316;; This holds a document string used to document auto-fill-mode.
5317(defun auto-fill-function ()
5318 "Automatically break line at a previous space, in insertion of text."
5319 nil)
5320
5321(defun turn-on-auto-fill ()
5322 "Unconditionally turn on Auto Fill mode."
5323 (auto-fill-mode 1))
3a99c819
GM
5324
5325(defun turn-off-auto-fill ()
5326 "Unconditionally turn off Auto Fill mode."
5327 (auto-fill-mode -1))
5328
7cbf1dc1 5329(custom-add-option 'text-mode-hook 'turn-on-auto-fill)
d7465b15
RS
5330
5331(defun set-fill-column (arg)
4cc0ea11 5332 "Set `fill-column' to specified argument.
923efb99 5333Use \\[universal-argument] followed by a number to specify a column.
4cc0ea11 5334Just \\[universal-argument] as argument means to use the current column."
7c373357
SM
5335 (interactive
5336 (list (or current-prefix-arg
5337 ;; We used to use current-column silently, but C-x f is too easily
5338 ;; typed as a typo for C-x C-f, so we turned it into an error and
5339 ;; now an interactive prompt.
5340 (read-number "Set fill-column to: " (current-column)))))
f4520363
RS
5341 (if (consp arg)
5342 (setq arg (current-column)))
5343 (if (not (integerp arg))
5344 ;; Disallow missing argument; it's probably a typo for C-x C-f.
f33321ad 5345 (error "set-fill-column requires an explicit argument")
f4520363
RS
5346 (message "Fill column set to %d (was %d)" arg fill-column)
5347 (setq fill-column arg)))
2d88b556 5348\f
2076c87c 5349(defun set-selective-display (arg)
ff1fbe3e
RS
5350 "Set `selective-display' to ARG; clear it if no arg.
5351When the value of `selective-display' is a number > 0,
5352lines whose indentation is >= that value are not displayed.
5353The variable `selective-display' has a separate value for each buffer."
2076c87c
JB
5354 (interactive "P")
5355 (if (eq selective-display t)
5356 (error "selective-display already in use for marked lines"))
c88ab9ce
ER
5357 (let ((current-vpos
5358 (save-restriction
5359 (narrow-to-region (point-min) (point))
5360 (goto-char (window-start))
5361 (vertical-motion (window-height)))))
5362 (setq selective-display
5363 (and arg (prefix-numeric-value arg)))
5364 (recenter current-vpos))
2076c87c
JB
5365 (set-window-start (selected-window) (window-start (selected-window)))
5366 (princ "selective-display set to " t)
5367 (prin1 selective-display t)
5368 (princ "." t))
5369
40a64816 5370(defvaralias 'indicate-unused-lines 'indicate-empty-lines)
40a64816 5371
b3228584 5372(defun toggle-truncate-lines (&optional arg)
215f50ce 5373 "Toggle whether to fold or truncate long lines for the current buffer.
4837b516 5374With prefix argument ARG, truncate long lines if ARG is positive,
1d2b0303
JB
5375otherwise don't truncate them. Note that in side-by-side windows,
5376this command has no effect if `truncate-partial-width-windows'
627bb5dc 5377is non-nil."
0bb64d76
PA
5378 (interactive "P")
5379 (setq truncate-lines
5380 (if (null arg)
5381 (not truncate-lines)
46cdfe8f
RS
5382 (> (prefix-numeric-value arg) 0)))
5383 (force-mode-line-update)
4f017185
RS
5384 (unless truncate-lines
5385 (let ((buffer (current-buffer)))
5386 (walk-windows (lambda (window)
5387 (if (eq buffer (window-buffer window))
5388 (set-window-hscroll window 0)))
5389 nil t)))
46cdfe8f
RS
5390 (message "Truncate long lines %s"
5391 (if truncate-lines "enabled" "disabled")))
0bb64d76 5392
c899b3db
JL
5393(defun toggle-word-wrap (&optional arg)
5394 "Toggle whether to use word-wrapping for continuation lines.
5395With prefix argument ARG, wrap continuation lines at word boundaries
5396if ARG is positive, otherwise wrap them at the right screen edge.
5397This command toggles the value of `word-wrap'. It has no effect
5398if long lines are truncated."
5399 (interactive "P")
5400 (setq word-wrap
5401 (if (null arg)
5402 (not word-wrap)
5403 (> (prefix-numeric-value arg) 0)))
5404 (force-mode-line-update)
5405 (message "Word wrapping %s"
5406 (if word-wrap "enabled" "disabled")))
5407
ca0a881a 5408(defvar overwrite-mode-textual (purecopy " Ovwrt")
b6a22db0 5409 "The string displayed in the mode line when in overwrite mode.")
ca0a881a 5410(defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
b6a22db0
JB
5411 "The string displayed in the mode line when in binary overwrite mode.")
5412
80ac5d4d 5413(define-minor-mode overwrite-mode
2076c87c 5414 "Toggle overwrite mode.
4837b516
GM
5415With prefix argument ARG, turn overwrite mode on if ARG is positive,
5416otherwise turn it off. In overwrite mode, printing characters typed
5417in replace existing text on a one-for-one basis, rather than pushing
5418it to the right. At the end of a line, such characters extend the line.
5419Before a tab, such characters insert until the tab is filled in.
b6a22db0
JB
5420\\[quoted-insert] still inserts characters in overwrite mode; this
5421is supposed to make it easier to insert characters when necessary."
80ac5d4d 5422 :variable (eq overwrite-mode 'overwrite-mode-textual))
b6a22db0 5423
80ac5d4d 5424(define-minor-mode binary-overwrite-mode
b6a22db0 5425 "Toggle binary overwrite mode.
4837b516
GM
5426With prefix argument ARG, turn binary overwrite mode on if ARG is
5427positive, otherwise turn it off. In binary overwrite mode, printing
5428characters typed in replace existing text. Newlines are not treated
5429specially, so typing at the end of a line joins the line to the next,
5430with the typed character between them. Typing before a tab character
5431simply replaces the tab with the character typed. \\[quoted-insert]
5432replaces the text at the cursor, just as ordinary typing characters do.
b6a22db0
JB
5433
5434Note that binary overwrite mode is not its own minor mode; it is a
f33321ad 5435specialization of overwrite mode, entered by setting the
b6a22db0 5436`overwrite-mode' variable to `overwrite-mode-binary'."
80ac5d4d 5437 :variable (eq overwrite-mode 'overwrite-mode-binary))
eaae8106 5438
6710df48 5439(define-minor-mode line-number-mode
a61099dd 5440 "Toggle Line Number mode.
1d2b0303 5441With ARG, turn Line Number mode on if ARG is positive, otherwise
4837b516
GM
5442turn it off. When Line Number mode is enabled, the line number
5443appears in the mode line.
8dc9e2ef 5444
32f2f98e
EZ
5445Line numbers do not appear for very large buffers and buffers
5446with very long lines; see variables `line-number-display-limit'
5447and `line-number-display-limit-width'."
efeb22bf 5448 :init-value t :global t :group 'mode-line)
bcad4985 5449
6710df48 5450(define-minor-mode column-number-mode
bcad4985 5451 "Toggle Column Number mode.
1d2b0303 5452With ARG, turn Column Number mode on if ARG is positive,
4837b516
GM
5453otherwise turn it off. When Column Number mode is enabled, the
5454column number appears in the mode line."
efeb22bf 5455 :global t :group 'mode-line)
6b61353c
KH
5456
5457(define-minor-mode size-indication-mode
5458 "Toggle Size Indication mode.
1d2b0303 5459With ARG, turn Size Indication mode on if ARG is positive,
4837b516
GM
5460otherwise turn it off. When Size Indication mode is enabled, the
5461size of the accessible part of the buffer appears in the mode line."
efeb22bf 5462 :global t :group 'mode-line)
f3ee9200
SM
5463
5464(define-minor-mode auto-save-mode
5465 "Toggle auto-saving of contents of current buffer.
5466With prefix argument ARG, turn auto-saving on if positive, else off."
5467 :variable ((and buffer-auto-save-file-name
5468 ;; If auto-save is off because buffer has shrunk,
5469 ;; then toggling should turn it on.
5470 (>= buffer-saved-size 0))
5471 . (lambda (val)
5472 (setq buffer-auto-save-file-name
5473 (cond
5474 ((null val) nil)
5475 ((and buffer-file-name auto-save-visited-file-name
5476 (not buffer-read-only))
5477 buffer-file-name)
5478 (t (make-auto-save-file-name))))))
5479 ;; If -1 was stored here, to temporarily turn off saving,
5480 ;; turn it back on.
5481 (and (< buffer-saved-size 0)
5482 (setq buffer-saved-size 0)))
2d88b556 5483\f
4b384a8f 5484(defgroup paren-blinking nil
020db25f 5485 "Blinking matching of parens and expressions."
4b384a8f
SM
5486 :prefix "blink-matching-"
5487 :group 'paren-matching)
5488
69c1dd37 5489(defcustom blink-matching-paren t
1d2b0303 5490 "Non-nil means show matching open-paren when close-paren is inserted."
69c1dd37 5491 :type 'boolean
4b384a8f 5492 :group 'paren-blinking)
2076c87c 5493
69c1dd37 5494(defcustom blink-matching-paren-on-screen t
1d2b0303 5495 "Non-nil means show matching open-paren when it is on screen.
1c2ba4e7 5496If nil, don't show it (but the open-paren can still be shown
92aa8a33
LT
5497when it is off screen).
5498
9cb370a9 5499This variable has no effect if `blink-matching-paren' is nil.
a9f72e5f 5500\(In that case, the open-paren is never shown.)
9cb370a9 5501It is also ignored if `show-paren-mode' is enabled."
69c1dd37 5502 :type 'boolean
4b384a8f 5503 :group 'paren-blinking)
29fc44dd 5504
fd413a37 5505(defcustom blink-matching-paren-distance (* 100 1024)
1d2b0303 5506 "If non-nil, maximum distance to search backwards for matching open-paren.
66d44a36 5507If nil, search stops at the beginning of the accessible portion of the buffer."
fd413a37 5508 :version "23.2" ; 25->100k
66d44a36 5509 :type '(choice (const nil) integer)
4b384a8f 5510 :group 'paren-blinking)
2076c87c 5511
69c1dd37 5512(defcustom blink-matching-delay 1
1d2b0303 5513 "Time in seconds to delay after showing a matching paren."
4b384a8f
SM
5514 :type 'number
5515 :group 'paren-blinking)
72dddf8b 5516
69c1dd37 5517(defcustom blink-matching-paren-dont-ignore-comments nil
1d2b0303 5518 "If nil, `blink-matching-paren' ignores comments.
ab6b3b16
RS
5519More precisely, when looking for the matching parenthesis,
5520it skips the contents of comments that end before point."
69c1dd37 5521 :type 'boolean
4b384a8f 5522 :group 'paren-blinking)
903b7f65 5523
b13ebb5c
SM
5524(defun blink-matching-check-mismatch (start end)
5525 "Return whether or not START...END are matching parens.
5526END is the current point and START is the blink position.
5527START might be nil if no matching starter was found.
5528Returns non-nil if we find there is a mismatch."
5529 (let* ((end-syntax (syntax-after (1- end)))
5530 (matching-paren (and (consp end-syntax)
5531 (eq (syntax-class end-syntax) 5)
5532 (cdr end-syntax))))
5533 ;; For self-matched chars like " and $, we can't know when they're
5534 ;; mismatched or unmatched, so we can only do it for parens.
5535 (when matching-paren
5536 (not (and start
5537 (or
5538 (eq (char-after start) matching-paren)
5539 ;; The cdr might hold a new paren-class info rather than
5540 ;; a matching-char info, in which case the two CDRs
5541 ;; should match.
5542 (eq matching-paren (cdr-safe (syntax-after start)))))))))
5543
5544(defvar blink-matching-check-function #'blink-matching-check-mismatch
5545 "Function to check parentheses mismatches.
5546The function takes two arguments (START and END) where START is the
5547position just before the opening token and END is the position right after.
5548START can be nil, if it was not found.
5549The function should return non-nil if the two tokens do not match.")
5550
2076c87c
JB
5551(defun blink-matching-open ()
5552 "Move cursor momentarily to the beginning of the sexp before point."
5553 (interactive)
b13ebb5c
SM
5554 (when (and (not (bobp))
5555 blink-matching-paren)
1d0e3fc8 5556 (let* ((oldpos (point))
b13ebb5c 5557 (message-log-max nil) ; Don't log messages about paren matching.
3137dda8
SM
5558 (blinkpos
5559 (save-excursion
5560 (save-restriction
5561 (if blink-matching-paren-distance
5562 (narrow-to-region
5563 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
5564 (- (point) blink-matching-paren-distance))
5565 oldpos))
5566 (let ((parse-sexp-ignore-comments
5567 (and parse-sexp-ignore-comments
5568 (not blink-matching-paren-dont-ignore-comments))))
5569 (condition-case ()
4b9c0a49
SM
5570 (progn
5571 (forward-sexp -1)
b13ebb5c
SM
5572 ;; backward-sexp skips backward over prefix chars,
5573 ;; so move back to the matching paren.
5574 (while (and (< (point) (1- oldpos))
984edd22
SM
5575 (let ((code (syntax-after (point))))
5576 (or (eq (syntax-class code) 6)
5577 (eq (logand 1048576 (car code))
5578 1048576))))
b13ebb5c 5579 (forward-char 1))
4b9c0a49 5580 (point))
3137dda8 5581 (error nil))))))
b13ebb5c 5582 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
3137dda8 5583 (cond
b13ebb5c
SM
5584 (mismatch
5585 (if blinkpos
28e271f0 5586 (if (minibufferp)
b13ebb5c
SM
5587 (minibuffer-message " [Mismatched parentheses]")
5588 (message "Mismatched parentheses"))
5589 (if (minibufferp)
5590 (minibuffer-message " [Unmatched parenthesis]")
5591 (message "Unmatched parenthesis"))))
c34a9669 5592 ((not blinkpos) nil)
3137dda8
SM
5593 ((pos-visible-in-window-p blinkpos)
5594 ;; Matching open within window, temporarily move to blinkpos but only
5595 ;; if `blink-matching-paren-on-screen' is non-nil.
5596 (and blink-matching-paren-on-screen
5597 (not show-paren-mode)
5598 (save-excursion
5599 (goto-char blinkpos)
5600 (sit-for blink-matching-delay))))
5601 (t
5602 (save-excursion
5603 (goto-char blinkpos)
5604 (let ((open-paren-line-string
5605 ;; Show what precedes the open in its line, if anything.
5606 (cond
5607 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
5608 (buffer-substring (line-beginning-position)
5609 (1+ blinkpos)))
5610 ;; Show what follows the open in its line, if anything.
5611 ((save-excursion
5612 (forward-char 1)
5613 (skip-chars-forward " \t")
5614 (not (eolp)))
5615 (buffer-substring blinkpos
5616 (line-end-position)))
5617 ;; Otherwise show the previous nonblank line,
5618 ;; if there is one.
5619 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
5620 (concat
5621 (buffer-substring (progn
5622 (skip-chars-backward "\n \t")
5623 (line-beginning-position))
5624 (progn (end-of-line)
5625 (skip-chars-backward " \t")
5626 (point)))
5627 ;; Replace the newline and other whitespace with `...'.
5628 "..."
5629 (buffer-substring blinkpos (1+ blinkpos))))
5630 ;; There is nothing to show except the char itself.
5631 (t (buffer-substring blinkpos (1+ blinkpos))))))
5632 (message "Matches %s"
5633 (substring-no-properties open-paren-line-string)))))))))
5634
8f4e9110
SM
5635(defvar blink-paren-function 'blink-matching-open
5636 "Function called, if non-nil, whenever a close parenthesis is inserted.
5637More precisely, a char with closeparen syntax is self-inserted.")
5638
5639(defun blink-paren-post-self-insert-function ()
5640 (when (and (eq (char-before) last-command-event) ; Sanity check.
5641 (memq (char-syntax last-command-event) '(?\) ?\$))
5642 blink-paren-function
5643 (not executing-kbd-macro)
b13ebb5c
SM
5644 (not noninteractive)
5645 ;; Verify an even number of quoting characters precede the close.
5646 (= 1 (logand 1 (- (point)
5647 (save-excursion
5648 (forward-char -1)
5649 (skip-syntax-backward "/\\")
5650 (point))))))
8f4e9110
SM
5651 (funcall blink-paren-function)))
5652
5653(add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
5654 ;; Most likely, this hook is nil, so this arg doesn't matter,
5655 ;; but I use it as a reminder that this function usually
5656 ;; likes to be run after others since it does `sit-for'.
5657 'append)
2d88b556 5658\f
9a1277dd
RS
5659;; This executes C-g typed while Emacs is waiting for a command.
5660;; Quitting out of a program does not go through here;
5661;; that happens in the QUIT macro at the C code level.
2076c87c 5662(defun keyboard-quit ()
d5dae4e1 5663 "Signal a `quit' condition.
af39530e
RS
5664During execution of Lisp code, this character causes a quit directly.
5665At top-level, as an editor command, this simply beeps."
2076c87c 5666 (interactive)
9852377f
CY
5667 ;; Avoid adding the region to the window selection.
5668 (setq saved-region-selection nil)
5669 (let (select-active-regions)
5670 (deactivate-mark))
8a7644e9
KS
5671 (if (fboundp 'kmacro-keyboard-quit)
5672 (kmacro-keyboard-quit))
f5e13057 5673 (setq defining-kbd-macro nil)
2076c87c
JB
5674 (signal 'quit nil))
5675
1c6c6fde
RS
5676(defvar buffer-quit-function nil
5677 "Function to call to \"quit\" the current buffer, or nil if none.
5678\\[keyboard-escape-quit] calls this function when its more local actions
5679\(such as cancelling a prefix argument, minibuffer or region) do not apply.")
5680
c66587fe
RS
5681(defun keyboard-escape-quit ()
5682 "Exit the current \"mode\" (in a generalized sense of the word).
5683This command can exit an interactive command such as `query-replace',
5684can clear out a prefix argument or a region,
5685can get out of the minibuffer or other recursive edit,
1c6c6fde
RS
5686cancel the use of the current buffer (for special-purpose buffers),
5687or go back to just one window (by deleting all but the selected window)."
c66587fe
RS
5688 (interactive)
5689 (cond ((eq last-command 'mode-exited) nil)
67189e62
JL
5690 ((region-active-p)
5691 (deactivate-mark))
c66587fe
RS
5692 ((> (minibuffer-depth) 0)
5693 (abort-recursive-edit))
5694 (current-prefix-arg
5695 nil)
1b657835
RS
5696 ((> (recursion-depth) 0)
5697 (exit-recursive-edit))
1c6c6fde
RS
5698 (buffer-quit-function
5699 (funcall buffer-quit-function))
c66587fe 5700 ((not (one-window-p t))
1b657835
RS
5701 (delete-other-windows))
5702 ((string-match "^ \\*" (buffer-name (current-buffer)))
5703 (bury-buffer))))
c66587fe 5704
2d88b556
RS
5705(defun play-sound-file (file &optional volume device)
5706 "Play sound stored in FILE.
5707VOLUME and DEVICE correspond to the keywords of the sound
5708specification for `play-sound'."
5709 (interactive "fPlay sound file: ")
5710 (let ((sound (list :file file)))
5711 (if volume
5712 (plist-put sound :volume volume))
5713 (if device
5714 (plist-put sound :device device))
5715 (push 'sound sound)
5716 (play-sound sound)))
5717
56abefac 5718\f
7683b5c2 5719(defcustom read-mail-command 'rmail
1d2b0303 5720 "Your preference for a mail reading package.
9023837e
DL
5721This is used by some keybindings which support reading mail.
5722See also `mail-user-agent' concerning sending mail."
f6714ede
GM
5723 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
5724 (function-item :tag "Gnus" :format "%t\n" gnus)
5725 (function-item :tag "Emacs interface to MH"
5726 :format "%t\n" mh-rmail)
5727 (function :tag "Other"))
7683b5c2
DL
5728 :version "21.1"
5729 :group 'mail)
5730
cbd61418 5731(defcustom mail-user-agent 'message-user-agent
1d2b0303 5732 "Your preference for a mail composition package.
9023837e 5733Various Emacs Lisp packages (e.g. Reporter) require you to compose an
a31ca314
RS
5734outgoing email message. This variable lets you specify which
5735mail-sending package you prefer.
5736
5737Valid values include:
5738
cfc47664
GM
5739 `message-user-agent' -- use the Message package.
5740 See Info node `(message)'.
5741 `sendmail-user-agent' -- use the Mail package.
9023837e
DL
5742 See Info node `(emacs)Sending Mail'.
5743 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
5744 See Info node `(mh-e)'.
9023837e
DL
5745 `gnus-user-agent' -- like `message-user-agent', but with Gnus
5746 paraphernalia, particularly the Gcc: header for
5747 archiving.
a31ca314
RS
5748
5749Additional valid symbols may be available; check with the author of
15d0c9b1
DL
5750your package for details. The function should return non-nil if it
5751succeeds.
9023837e
DL
5752
5753See also `read-mail-command' concerning reading mail."
cfc47664
GM
5754 :type '(radio (function-item :tag "Message package"
5755 :format "%t\n"
5756 message-user-agent)
5757 (function-item :tag "Mail package"
69c1dd37
RS
5758 :format "%t\n"
5759 sendmail-user-agent)
5760 (function-item :tag "Emacs interface to MH"
5761 :format "%t\n"
5762 mh-e-user-agent)
cfc47664 5763 (function-item :tag "Message with full Gnus features"
9023837e
DL
5764 :format "%t\n"
5765 gnus-user-agent)
69c1dd37 5766 (function :tag "Other"))
cfc47664 5767 :version "23.2" ; sendmail->message
69c1dd37 5768 :group 'mail)
a31ca314 5769
3d68fa99
CY
5770(defcustom compose-mail-user-agent-warnings t
5771 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
5772If the value of `mail-user-agent' is the default, and the user
5773appears to have customizations applying to the old default,
5774`compose-mail' issues a warning."
5775 :type 'boolean
5776 :version "23.2"
5777 :group 'mail)
5778
360b5483 5779(defun rfc822-goto-eoh ()
41002397
GM
5780 "If the buffer starts with a mail header, move point to the header's end.
5781Otherwise, moves to `point-min'.
5782The end of the header is the start of the next line, if there is one,
5783else the end of the last line. This function obeys RFC822."
360b5483 5784 (goto-char (point-min))
e1e04350
SM
5785 (when (re-search-forward
5786 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
5787 (goto-char (match-beginning 0))))
360b5483 5788
d0008a00 5789(defun compose-mail (&optional to subject other-headers continue
25ca2e61
CY
5790 switch-function yank-action send-actions
5791 return-action)
d0008a00
RS
5792 "Start composing a mail message to send.
5793This uses the user's chosen mail composition package
5794as selected with the variable `mail-user-agent'.
5795The optional arguments TO and SUBJECT specify recipients
5796and the initial Subject field, respectively.
5797
5798OTHER-HEADERS is an alist specifying additional
5799header fields. Elements look like (HEADER . VALUE) where both
5800HEADER and VALUE are strings.
5801
5802CONTINUE, if non-nil, says to continue editing a message already
9dda5b0e 5803being composed. Interactively, CONTINUE is the prefix argument.
d0008a00
RS
5804
5805SWITCH-FUNCTION, if non-nil, is a function to use to
5806switch to and display the buffer used for mail composition.
5807
5808YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
06720de2
RS
5809to insert the raw text of the message being replied to.
5810It has the form (FUNCTION . ARGS). The user agent will apply
5811FUNCTION to ARGS, to insert the raw text of the original message.
5812\(The user agent will also run `mail-citation-hook', *after* the
5813original text has been inserted in this way.)
d0008a00
RS
5814
5815SEND-ACTIONS is a list of actions to call when the message is sent.
25ca2e61
CY
5816Each action has the form (FUNCTION . ARGS).
5817
5818RETURN-ACTION, if non-nil, is an action for returning to the
5819caller. It has the form (FUNCTION . ARGS). The function is
5820called after the mail has been sent or put aside, and the mail
5821buffer buried."
b5f019be
RS
5822 (interactive
5823 (list nil nil nil current-prefix-arg))
3d68fa99
CY
5824
5825 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
5826 ;; from sendmail-user-agent to message-user-agent. Some users may
5827 ;; encounter incompatibilities. This hack tries to detect problems
5828 ;; and warn about them.
5829 (and compose-mail-user-agent-warnings
5830 (eq mail-user-agent 'message-user-agent)
5831 (let (warn-vars)
5832 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
5833 mail-yank-hooks mail-archive-file-name
5834 mail-default-reply-to mail-mailing-lists
5e1d4968 5835 mail-self-blind))
3d68fa99
CY
5836 (and (boundp var)
5837 (symbol-value var)
5838 (push var warn-vars)))
5839 (when warn-vars
5840 (display-warning 'mail
5841 (format "\
5842The default mail mode is now Message mode.
5843You have the following Mail mode variable%s customized:
5844\n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7f0b7b3e 5845To disable this warning, set `compose-mail-user-agent-warnings' to nil."
3d68fa99
CY
5846 (if (> (length warn-vars) 1) "s" "")
5847 (mapconcat 'symbol-name
5848 warn-vars " "))))))
5849
676b1a74 5850 (let ((function (get mail-user-agent 'composefunc)))
25ca2e61
CY
5851 (funcall function to subject other-headers continue switch-function
5852 yank-action send-actions return-action)))
b5f019be
RS
5853
5854(defun compose-mail-other-window (&optional to subject other-headers continue
25ca2e61
CY
5855 yank-action send-actions
5856 return-action)
b5f019be 5857 "Like \\[compose-mail], but edit the outgoing message in another window."
25ca2e61 5858 (interactive (list nil nil nil current-prefix-arg))
b5f019be 5859 (compose-mail to subject other-headers continue
25ca2e61
CY
5860 'switch-to-buffer-other-window yank-action send-actions
5861 return-action))
b5f019be
RS
5862
5863(defun compose-mail-other-frame (&optional to subject other-headers continue
25ca2e61
CY
5864 yank-action send-actions
5865 return-action)
b5f019be 5866 "Like \\[compose-mail], but edit the outgoing message in another frame."
25ca2e61 5867 (interactive (list nil nil nil current-prefix-arg))
b5f019be 5868 (compose-mail to subject other-headers continue
25ca2e61
CY
5869 'switch-to-buffer-other-frame yank-action send-actions
5870 return-action))
5871
56abefac 5872\f
610c1c68 5873(defvar set-variable-value-history nil
987ec16d
EZ
5874 "History of values entered with `set-variable'.
5875
5876Maximum length of the history list is determined by the value
5877of `history-length', which see.")
610c1c68 5878
d6281b4e 5879(defun set-variable (variable value &optional make-local)
610c1c68 5880 "Set VARIABLE to VALUE. VALUE is a Lisp object.
d6281b4e
RS
5881VARIABLE should be a user option variable name, a Lisp variable
5882meant to be customized by users. You should enter VALUE in Lisp syntax,
5883so if you want VALUE to be a string, you must surround it with doublequotes.
610c1c68
RS
5884VALUE is used literally, not evaluated.
5885
5886If VARIABLE has a `variable-interactive' property, that is used as if
5887it were the arg to `interactive' (which see) to interactively read VALUE.
5888
5889If VARIABLE has been defined with `defcustom', then the type information
16236388
RS
5890in the definition is used to check that VALUE is valid.
5891
5892With a prefix argument, set VARIABLE to VALUE buffer-locally."
e9dfb72e
RS
5893 (interactive
5894 (let* ((default-var (variable-at-point))
7fd0ef0d
JL
5895 (var (if (user-variable-p default-var)
5896 (read-variable (format "Set variable (default %s): " default-var)
5897 default-var)
5898 (read-variable "Set variable: ")))
6b61353c
KH
5899 (minibuffer-help-form '(describe-variable var))
5900 (prop (get var 'variable-interactive))
0684376b
JB
5901 (obsolete (car (get var 'byte-obsolete-variable)))
5902 (prompt (format "Set %s %s to value: " var
6b61353c 5903 (cond ((local-variable-p var)
0684376b 5904 "(buffer-local)")
6b61353c
KH
5905 ((or current-prefix-arg
5906 (local-variable-if-set-p var))
0684376b
JB
5907 "buffer-locally")
5908 (t "globally"))))
5909 (val (progn
5910 (when obsolete
5911 (message (concat "`%S' is obsolete; "
5912 (if (symbolp obsolete) "use `%S' instead" "%s"))
5913 var obsolete)
5914 (sit-for 3))
5915 (if prop
5916 ;; Use VAR's `variable-interactive' property
5917 ;; as an interactive spec for prompting.
5918 (call-interactively `(lambda (arg)
5919 (interactive ,prop)
5920 arg))
5921 (read
5922 (read-string prompt nil
7fd0ef0d
JL
5923 'set-variable-value-history
5924 (format "%S" (symbol-value var))))))))
6b61353c 5925 (list var val current-prefix-arg)))
610c1c68 5926
d6281b4e
RS
5927 (and (custom-variable-p variable)
5928 (not (get variable 'custom-type))
5929 (custom-load-symbol variable))
5930 (let ((type (get variable 'custom-type)))
610c1c68
RS
5931 (when type
5932 ;; Match with custom type.
36755dd9 5933 (require 'cus-edit)
610c1c68 5934 (setq type (widget-convert type))
d6281b4e 5935 (unless (widget-apply type :match value)
1e722f9f 5936 (error "Value `%S' does not match type %S of %S"
d6281b4e 5937 value (car type) variable))))
16236388
RS
5938
5939 (if make-local
d6281b4e 5940 (make-local-variable variable))
f1180544 5941
d6281b4e 5942 (set variable value)
a2aef080
GM
5943
5944 ;; Force a thorough redisplay for the case that the variable
5945 ;; has an effect on the display, like `tab-width' has.
5946 (force-mode-line-update))
56abefac 5947\f
e8a700bf
RS
5948;; Define the major mode for lists of completions.
5949
e2947429
SM
5950(defvar completion-list-mode-map
5951 (let ((map (make-sparse-keymap)))
5952 (define-key map [mouse-2] 'mouse-choose-completion)
5953 (define-key map [follow-link] 'mouse-face)
5954 (define-key map [down-mouse-2] nil)
5955 (define-key map "\C-m" 'choose-completion)
5956 (define-key map "\e\e\e" 'delete-completion-window)
5957 (define-key map [left] 'previous-completion)
5958 (define-key map [right] 'next-completion)
45f8cb0c 5959 (define-key map "q" 'quit-window)
abef340a 5960 (define-key map "z" 'kill-this-buffer)
e2947429 5961 map)
98b45886 5962 "Local map for completion list buffers.")
e8a700bf
RS
5963
5964;; Completion mode is suitable only for specially formatted data.
ac29eb79 5965(put 'completion-list-mode 'mode-class 'special)
e8a700bf 5966
98b45886
RS
5967(defvar completion-reference-buffer nil
5968 "Record the buffer that was current when the completion list was requested.
5969This is a local variable in the completion list buffer.
ec39964e 5970Initial value is nil to avoid some compiler warnings.")
3819736b 5971
83434bda
RS
5972(defvar completion-no-auto-exit nil
5973 "Non-nil means `choose-completion-string' should never exit the minibuffer.
f6714ede 5974This also applies to other functions such as `choose-completion'.")
83434bda 5975
d5e63715
SM
5976(defvar completion-base-position nil
5977 "Position of the base of the text corresponding to the shown completions.
5978This variable is used in the *Completions* buffers.
5979Its value is a list of the form (START END) where START is the place
5980where the completion should be inserted and END (if non-nil) is the end
5981of the text to replace. If END is nil, point is used instead.")
5982
98b45886 5983(defvar completion-base-size nil
3c59150d
CY
5984 "Number of chars before point not involved in completion.
5985This is a local variable in the completion list buffer.
5986It refers to the chars in the minibuffer if completing in the
5987minibuffer, or in `completion-reference-buffer' otherwise.
5988Only characters in the field at point are included.
5989
5990If nil, Emacs determines which part of the tail end of the
5991buffer's text is involved in completion by comparing the text
5992directly.")
d5e63715 5993(make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
f6b293e3 5994
1c6c6fde
RS
5995(defun delete-completion-window ()
5996 "Delete the completion list window.
5997Go to the window from which completion was requested."
5998 (interactive)
5999 (let ((buf completion-reference-buffer))
ddb2b181
RS
6000 (if (one-window-p t)
6001 (if (window-dedicated-p (selected-window))
6002 (delete-frame (selected-frame)))
6003 (delete-window (selected-window))
6004 (if (get-buffer-window buf)
6005 (select-window (get-buffer-window buf))))))
1c6c6fde 6006
dde69dbe
RS
6007(defun previous-completion (n)
6008 "Move to the previous item in the completion list."
6009 (interactive "p")
6010 (next-completion (- n)))
6011
6012(defun next-completion (n)
6013 "Move to the next item in the completion list.
1f238ac2 6014With prefix argument N, move N items (negative N means move backward)."
dde69dbe 6015 (interactive "p")
58dd38f1
SM
6016 (let ((beg (point-min)) (end (point-max)))
6017 (while (and (> n 0) (not (eobp)))
dde69dbe 6018 ;; If in a completion, move to the end of it.
58dd38f1
SM
6019 (when (get-text-property (point) 'mouse-face)
6020 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
dde69dbe 6021 ;; Move to start of next one.
58dd38f1
SM
6022 (unless (get-text-property (point) 'mouse-face)
6023 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
6024 (setq n (1- n)))
6025 (while (and (< n 0) (not (bobp)))
6026 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
6027 ;; If in a completion, move to the start of it.
6028 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
b61a81c2 6029 (goto-char (previous-single-property-change
58dd38f1
SM
6030 (point) 'mouse-face nil beg)))
6031 ;; Move to end of the previous completion.
6032 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
6033 (goto-char (previous-single-property-change
6034 (point) 'mouse-face nil beg)))
6035 ;; Move to the start of that one.
6036 (goto-char (previous-single-property-change
6037 (point) 'mouse-face nil beg))
6038 (setq n (1+ n))))))
dde69dbe 6039
d5e63715
SM
6040(defun choose-completion (&optional event)
6041 "Choose the completion at point."
6042 (interactive (list last-nonmenu-event))
6043 ;; In case this is run via the mouse, give temporary modes such as
6044 ;; isearch a chance to turn off.
6045 (run-hooks 'mouse-leave-buffer-hook)
6046 (let (buffer base-size base-position choice)
6047 (with-current-buffer (window-buffer (posn-window (event-start event)))
6048 (setq buffer completion-reference-buffer)
6049 (setq base-size completion-base-size)
6050 (setq base-position completion-base-position)
6051 (save-excursion
6052 (goto-char (posn-point (event-start event)))
6053 (let (beg end)
6054 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
6055 (setq end (point) beg (1+ (point))))
6056 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
6057 (setq end (1- (point)) beg (point)))
6058 (if (null beg)
6059 (error "No completion here"))
6060 (setq beg (previous-single-property-change beg 'mouse-face))
6061 (setq end (or (next-single-property-change end 'mouse-face)
6062 (point-max)))
6063 (setq choice (buffer-substring-no-properties beg end)))))
6064
ab63960f 6065 (let ((owindow (selected-window)))
d5e63715 6066 (select-window (posn-window (event-start event)))
ab63960f 6067 (if (and (one-window-p t 'selected-frame)
d5e63715 6068 (window-dedicated-p (selected-window)))
ab63960f
RS
6069 ;; This is a special buffer's frame
6070 (iconify-frame (selected-frame))
6071 (or (window-dedicated-p (selected-window))
6072 (bury-buffer)))
8a7daef5
CY
6073 (select-window
6074 (or (and (buffer-live-p buffer)
d5e63715 6075 (get-buffer-window buffer 0))
8a7daef5 6076 owindow)))
f6714ede 6077
d5e63715
SM
6078 (choose-completion-string
6079 choice buffer
6080 (or base-position
6081 (when base-size
6082 ;; Someone's using old completion code that doesn't know
6083 ;; about base-position yet.
6084 (list (+ base-size (with-current-buffer buffer (field-beginning)))))
6085 ;; If all else fails, just guess.
6086 (with-current-buffer buffer
6087 (list (choose-completion-guess-base-position choice)))))))
80298193
RS
6088
6089;; Delete the longest partial match for STRING
6090;; that can be found before POINT.
d5e63715
SM
6091(defun choose-completion-guess-base-position (string)
6092 (save-excursion
6093 (let ((opoint (point))
6094 len)
6095 ;; Try moving back by the length of the string.
6096 (goto-char (max (- (point) (length string))
6097 (minibuffer-prompt-end)))
6098 ;; See how far back we were actually able to move. That is the
6099 ;; upper bound on how much we can match and delete.
6100 (setq len (- opoint (point)))
6101 (if completion-ignore-case
6102 (setq string (downcase string)))
6103 (while (and (> len 0)
6104 (let ((tail (buffer-substring (point) opoint)))
6105 (if completion-ignore-case
6106 (setq tail (downcase tail)))
6107 (not (string= tail (substring string 0 len)))))
6108 (setq len (1- len))
6109 (forward-char 1))
6110 (point))))
6111
80298193 6112(defun choose-completion-delete-max-match (string)
d5e63715
SM
6113 (delete-region (choose-completion-guess-base-position string) (point)))
6114(make-obsolete 'choose-completion-delete-max-match
6115 'choose-completion-guess-base-position "23.2")
80298193 6116
ba36181b 6117(defvar choose-completion-string-functions nil
bbbbb15b
KS
6118 "Functions that may override the normal insertion of a completion choice.
6119These functions are called in order with four arguments:
6120CHOICE - the string to insert in the buffer,
6121BUFFER - the buffer in which the choice should be inserted,
4837b516 6122MINI-P - non-nil if BUFFER is a minibuffer, and
12829a07
RS
6123BASE-SIZE - the number of characters in BUFFER before
6124the string being completed.
6125
bbbbb15b
KS
6126If a function in the list returns non-nil, that function is supposed
6127to have inserted the CHOICE in the BUFFER, and possibly exited
12829a07 6128the minibuffer; no further functions will be called.
ba36181b 6129
12829a07
RS
6130If all functions in the list return nil, that means to use
6131the default method of inserting the completion in BUFFER.")
74d0290b 6132
d5e63715 6133(defun choose-completion-string (choice &optional buffer base-position)
12829a07 6134 "Switch to BUFFER and insert the completion choice CHOICE.
d5e63715 6135BASE-POSITION, says where to insert the completion."
12829a07
RS
6136
6137 ;; If BUFFER is the minibuffer, exit the minibuffer
6138 ;; unless it is reading a file name and CHOICE is a directory,
6139 ;; or completion-no-auto-exit is non-nil.
6140
d5e63715
SM
6141 ;; Some older code may call us passing `base-size' instead of
6142 ;; `base-position'. It's difficult to make any use of `base-size',
6143 ;; so we just ignore it.
6144 (unless (consp base-position)
6145 (message "Obsolete `base-size' passed to choose-completion-string")
6146 (setq base-position nil))
6147
1a0d0b6a
JPW
6148 (let* ((buffer (or buffer completion-reference-buffer))
6149 (mini-p (minibufferp buffer)))
cf52ad58
RS
6150 ;; If BUFFER is a minibuffer, barf unless it's the currently
6151 ;; active minibuffer.
f436a90a 6152 (if (and mini-p
45486731
RS
6153 (or (not (active-minibuffer-window))
6154 (not (equal buffer
6155 (window-buffer (active-minibuffer-window))))))
cf52ad58 6156 (error "Minibuffer is not active for completion")
17aa3385
KS
6157 ;; Set buffer so buffer-local choose-completion-string-functions works.
6158 (set-buffer buffer)
f1180544 6159 (unless (run-hook-with-args-until-success
d99f8496 6160 'choose-completion-string-functions
d5e63715
SM
6161 ;; The fourth arg used to be `mini-p' but was useless
6162 ;; (since minibufferp can be used on the `buffer' arg)
6163 ;; and indeed unused. The last used to be `base-size', so we
6164 ;; keep it to try and avoid breaking old code.
6165 choice buffer base-position nil)
d99f8496 6166 ;; Insert the completion into the buffer where it was requested.
d5e63715
SM
6167 (delete-region (or (car base-position) (point))
6168 (or (cadr base-position) (point)))
bbbbb15b
KS
6169 (insert choice)
6170 (remove-text-properties (- (point) (length choice)) (point)
6171 '(mouse-face nil))
6172 ;; Update point in the window that BUFFER is showing in.
6173 (let ((window (get-buffer-window buffer t)))
6174 (set-window-point window (point)))
6175 ;; If completing for the minibuffer, exit it with this choice.
6176 (and (not completion-no-auto-exit)
6138158d 6177 (minibufferp buffer)
bbbbb15b
KS
6178 minibuffer-completion-table
6179 ;; If this is reading a file name, and the file name chosen
6180 ;; is a directory, don't exit the minibuffer.
85be9ec4
SM
6181 (let* ((result (buffer-substring (field-beginning) (point)))
6182 (bounds
6183 (completion-boundaries result minibuffer-completion-table
6184 minibuffer-completion-predicate
6185 "")))
6186 (if (eq (car bounds) (length result))
6187 ;; The completion chosen leads to a new set of completions
6188 ;; (e.g. it's a directory): don't exit the minibuffer yet.
6189 (let ((mini (active-minibuffer-window)))
6190 (select-window mini)
6191 (when minibuffer-auto-raise
6192 (raise-frame (window-frame mini))))
6193 (exit-minibuffer))))))))
80298193 6194
e2947429 6195(define-derived-mode completion-list-mode nil "Completion List"
e8a700bf 6196 "Major mode for buffers showing lists of possible completions.
80298193
RS
6197Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
6198 to select the completion near point.
6199Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
3a77346c
GM
6200 with the mouse.
6201
6202\\{completion-list-mode-map}"
e2947429 6203 (set (make-local-variable 'completion-base-size) nil))
e8a700bf 6204
c8d6d636
GM
6205(defun completion-list-mode-finish ()
6206 "Finish setup of the completions buffer.
6207Called from `temp-buffer-show-hook'."
6208 (when (eq major-mode 'completion-list-mode)
6209 (toggle-read-only 1)))
6210
6211(add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
6212
f5fab556
MY
6213
6214;; Variables and faces used in `completion-setup-function'.
747a0e2f 6215
d0fd0916
JPW
6216(defcustom completion-show-help t
6217 "Non-nil means show help message in *Completions* buffer."
6218 :type 'boolean
6219 :version "22.1"
6220 :group 'completion)
6221
f5fab556
MY
6222;; This function goes in completion-setup-hook, so that it is called
6223;; after the text of the completion list buffer is written.
e8a700bf 6224(defun completion-setup-function ()
1b5fd09e 6225 (let* ((mainbuf (current-buffer))
a9e3ff69
SM
6226 (base-dir
6227 ;; When reading a file name in the minibuffer,
6228 ;; try and find the right default-directory to set in the
6229 ;; completion list buffer.
6230 ;; FIXME: Why do we do that, actually? --Stef
6231 (if minibuffer-completing-file-name
6232 (file-name-as-directory
6233 (expand-file-name
6234 (substring (minibuffer-completion-contents)
6235 0 (or completion-base-size 0)))))))
621a3f62 6236 (with-current-buffer standard-output
d5e63715
SM
6237 (let ((base-size completion-base-size) ;Read before killing localvars.
6238 (base-position completion-base-position))
e2947429 6239 (completion-list-mode)
d5e63715
SM
6240 (set (make-local-variable 'completion-base-size) base-size)
6241 (set (make-local-variable 'completion-base-position) base-position))
1b5fd09e 6242 (set (make-local-variable 'completion-reference-buffer) mainbuf)
a9e3ff69 6243 (if base-dir (setq default-directory base-dir))
d0fd0916
JPW
6244 ;; Maybe insert help string.
6245 (when completion-show-help
6246 (goto-char (point-min))
6247 (if (display-mouse-p)
6248 (insert (substitute-command-keys
6249 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
6250 (insert (substitute-command-keys
6251 "In this buffer, type \\[choose-completion] to \
6252select the completion near point.\n\n"))))))
c88ab9ce 6253
e8a700bf 6254(add-hook 'completion-setup-hook 'completion-setup-function)
dde69dbe 6255
1b5fd09e
SM
6256(define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
6257(define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
dde69dbe
RS
6258
6259(defun switch-to-completions ()
6260 "Select the completion list window."
6261 (interactive)
ab14d7d5 6262 (let ((window (or (get-buffer-window "*Completions*" 0)
042b7cc6 6263 ;; Make sure we have a completions window.
ab14d7d5
SM
6264 (progn (minibuffer-completion-help)
6265 (get-buffer-window "*Completions*" 0)))))
fdbd7c4d
KH
6266 (when window
6267 (select-window window)
042b7cc6
JL
6268 ;; In the new buffer, go to the first completion.
6269 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
6270 (when (bobp)
6271 (next-completion 1)))))
f6039de6
JL
6272\f
6273;;; Support keyboard commands to turn on various modifiers.
82072f33
RS
6274
6275;; These functions -- which are not commands -- each add one modifier
6276;; to the following event.
6277
06b60517 6278(defun event-apply-alt-modifier (_ignore-prompt)
1e96c007 6279 "\\<function-key-map>Add the Alt modifier to the following event.
70cf9f08 6280For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
82072f33 6281 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
06b60517 6282(defun event-apply-super-modifier (_ignore-prompt)
1e96c007 6283 "\\<function-key-map>Add the Super modifier to the following event.
70cf9f08 6284For example, type \\[event-apply-super-modifier] & to enter Super-&."
82072f33 6285 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
06b60517 6286(defun event-apply-hyper-modifier (_ignore-prompt)
1e96c007 6287 "\\<function-key-map>Add the Hyper modifier to the following event.
70cf9f08 6288For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
82072f33 6289 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
06b60517 6290(defun event-apply-shift-modifier (_ignore-prompt)
1e96c007 6291 "\\<function-key-map>Add the Shift modifier to the following event.
70cf9f08 6292For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
82072f33 6293 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
06b60517 6294(defun event-apply-control-modifier (_ignore-prompt)
1e96c007 6295 "\\<function-key-map>Add the Ctrl modifier to the following event.
70cf9f08 6296For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
82072f33 6297 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
06b60517 6298(defun event-apply-meta-modifier (_ignore-prompt)
1e96c007 6299 "\\<function-key-map>Add the Meta modifier to the following event.
70cf9f08 6300For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
82072f33
RS
6301 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
6302
6303(defun event-apply-modifier (event symbol lshiftby prefix)
6304 "Apply a modifier flag to event EVENT.
6305SYMBOL is the name of this modifier, as a symbol.
6306LSHIFTBY is the numeric value of this modifier, in keyboard events.
6307PREFIX is the string that represents this modifier in an event type symbol."
6308 (if (numberp event)
6309 (cond ((eq symbol 'control)
90bebcb0
KH
6310 (if (and (<= (downcase event) ?z)
6311 (>= (downcase event) ?a))
82072f33 6312 (- (downcase event) ?a -1)
90bebcb0
KH
6313 (if (and (<= (downcase event) ?Z)
6314 (>= (downcase event) ?A))
82072f33
RS
6315 (- (downcase event) ?A -1)
6316 (logior (lsh 1 lshiftby) event))))
6317 ((eq symbol 'shift)
6318 (if (and (<= (downcase event) ?z)
6319 (>= (downcase event) ?a))
6320 (upcase event)
6321 (logior (lsh 1 lshiftby) event)))
6322 (t
6323 (logior (lsh 1 lshiftby) event)))
6324 (if (memq symbol (event-modifiers event))
6325 event
6326 (let ((event-type (if (symbolp event) event (car event))))
6327 (setq event-type (intern (concat prefix (symbol-name event-type))))
6328 (if (symbolp event)
6329 event-type
6330 (cons event-type (cdr event)))))))
6331
e5fff738
KH
6332(define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
6333(define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
6334(define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
6335(define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
6336(define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
6337(define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
f6039de6 6338\f
a3d1480b
JB
6339;;;; Keypad support.
6340
9b77469a
SM
6341;; Make the keypad keys act like ordinary typing keys. If people add
6342;; bindings for the function key symbols, then those bindings will
6343;; override these, so this shouldn't interfere with any existing
6344;; bindings.
a3d1480b 6345
0d173134 6346;; Also tell read-char how to handle these keys.
e1e04350 6347(mapc
a3d1480b
JB
6348 (lambda (keypad-normal)
6349 (let ((keypad (nth 0 keypad-normal))
6350 (normal (nth 1 keypad-normal)))
0d173134 6351 (put keypad 'ascii-character normal)
a3d1480b
JB
6352 (define-key function-key-map (vector keypad) (vector normal))))
6353 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
6354 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
f33321ad 6355 (kp-space ?\s)
a3d1480b
JB
6356 (kp-tab ?\t)
6357 (kp-enter ?\r)
6358 (kp-multiply ?*)
6359 (kp-add ?+)
6360 (kp-separator ?,)
6361 (kp-subtract ?-)
6362 (kp-decimal ?.)
6363 (kp-divide ?/)
31cd2dd4
SM
6364 (kp-equal ?=)
6365 ;; Do the same for various keys that are represented as symbols under
6366 ;; GUIs but naturally correspond to characters.
6367 (backspace 127)
6368 (delete 127)
6369 (tab ?\t)
6370 (linefeed ?\n)
6371 (clear ?\C-l)
6372 (return ?\C-m)
6373 (escape ?\e)
6374 ))
f54b0d85 6375\f
1e722f9f 6376;;;;
b005abd5 6377;;;; forking a twin copy of a buffer.
1e722f9f 6378;;;;
b005abd5
SM
6379
6380(defvar clone-buffer-hook nil
6381 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
6382
64663f06
SM
6383(defvar clone-indirect-buffer-hook nil
6384 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
6385
b005abd5
SM
6386(defun clone-process (process &optional newname)
6387 "Create a twin copy of PROCESS.
6388If NEWNAME is nil, it defaults to PROCESS' name;
6389NEWNAME is modified by adding or incrementing <N> at the end as necessary.
6390If PROCESS is associated with a buffer, the new process will be associated
6391 with the current buffer instead.
6392Returns nil if PROCESS has already terminated."
6393 (setq newname (or newname (process-name process)))
6394 (if (string-match "<[0-9]+>\\'" newname)
6395 (setq newname (substring newname 0 (match-beginning 0))))
6396 (when (memq (process-status process) '(run stop open))
6397 (let* ((process-connection-type (process-tty-name process))
b005abd5
SM
6398 (new-process
6399 (if (memq (process-status process) '(open))
ed7069af
KS
6400 (let ((args (process-contact process t)))
6401 (setq args (plist-put args :name newname))
6402 (setq args (plist-put args :buffer
403ca8d9
KS
6403 (if (process-buffer process)
6404 (current-buffer))))
ed7069af 6405 (apply 'make-network-process args))
b005abd5
SM
6406 (apply 'start-process newname
6407 (if (process-buffer process) (current-buffer))
6408 (process-command process)))))
ed7069af
KS
6409 (set-process-query-on-exit-flag
6410 new-process (process-query-on-exit-flag process))
b005abd5
SM
6411 (set-process-inherit-coding-system-flag
6412 new-process (process-inherit-coding-system-flag process))
6413 (set-process-filter new-process (process-filter process))
6414 (set-process-sentinel new-process (process-sentinel process))
403ca8d9 6415 (set-process-plist new-process (copy-sequence (process-plist process)))
b005abd5
SM
6416 new-process)))
6417
b75b82ab 6418;; things to maybe add (currently partly covered by `funcall mode'):
b005abd5
SM
6419;; - syntax-table
6420;; - overlays
6421(defun clone-buffer (&optional newname display-flag)
6b61353c
KH
6422 "Create and return a twin copy of the current buffer.
6423Unlike an indirect buffer, the new buffer can be edited
6424independently of the old one (if it is not read-only).
6425NEWNAME is the name of the new buffer. It may be modified by
6426adding or incrementing <N> at the end as necessary to create a
6427unique buffer name. If nil, it defaults to the name of the
6428current buffer, with the proper suffix. If DISPLAY-FLAG is
6429non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
6430clone a file-visiting buffer, or a buffer whose major mode symbol
6431has a non-nil `no-clone' property, results in an error.
6432
6433Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
6434current buffer with appropriate suffix. However, if a prefix
6435argument is given, then the command prompts for NEWNAME in the
6436minibuffer.
b005abd5 6437
b005abd5
SM
6438This runs the normal hook `clone-buffer-hook' in the new buffer
6439after it has been set up properly in other respects."
61acfe7f
RS
6440 (interactive
6441 (progn
6442 (if buffer-file-name
6443 (error "Cannot clone a file-visiting buffer"))
6444 (if (get major-mode 'no-clone)
6445 (error "Cannot clone a buffer in %s mode" mode-name))
f6039de6
JL
6446 (list (if current-prefix-arg
6447 (read-buffer "Name of new cloned buffer: " (current-buffer)))
61acfe7f 6448 t)))
b005abd5
SM
6449 (if buffer-file-name
6450 (error "Cannot clone a file-visiting buffer"))
6451 (if (get major-mode 'no-clone)
6452 (error "Cannot clone a buffer in %s mode" mode-name))
6453 (setq newname (or newname (buffer-name)))
6454 (if (string-match "<[0-9]+>\\'" newname)
6455 (setq newname (substring newname 0 (match-beginning 0))))
6456 (let ((buf (current-buffer))
6457 (ptmin (point-min))
6458 (ptmax (point-max))
6459 (pt (point))
6460 (mk (if mark-active (mark t)))
6461 (modified (buffer-modified-p))
6462 (mode major-mode)
6463 (lvars (buffer-local-variables))
6464 (process (get-buffer-process (current-buffer)))
6465 (new (generate-new-buffer (or newname (buffer-name)))))
6466 (save-restriction
6467 (widen)
6468 (with-current-buffer new
6469 (insert-buffer-substring buf)))
6470 (with-current-buffer new
6471 (narrow-to-region ptmin ptmax)
6472 (goto-char pt)
6473 (if mk (set-mark mk))
6474 (set-buffer-modified-p modified)
6475
6476 ;; Clone the old buffer's process, if any.
6477 (when process (clone-process process))
6478
6479 ;; Now set up the major mode.
6480 (funcall mode)
6481
6482 ;; Set up other local variables.
9ca2204b
JB
6483 (mapc (lambda (v)
6484 (condition-case () ;in case var is read-only
6485 (if (symbolp v)
6486 (makunbound v)
6487 (set (make-local-variable (car v)) (cdr v)))
6488 (error nil)))
6489 lvars)
b005abd5
SM
6490
6491 ;; Run any hooks (typically set up by the major mode
6492 ;; for cloning to work properly).
6493 (run-hooks 'clone-buffer-hook))
0a487199
SM
6494 (if display-flag
6495 ;; Presumably the current buffer is shown in the selected frame, so
6496 ;; we want to display the clone elsewhere.
6497 (let ((same-window-regexps nil)
6498 (same-window-buffer-names))
6499 (pop-to-buffer new)))
b005abd5
SM
6500 new))
6501
fa65f20b 6502
7e3afb04 6503(defun clone-indirect-buffer (newname display-flag &optional norecord)
fa65f20b
GM
6504 "Create an indirect buffer that is a twin copy of the current buffer.
6505
01ba9662 6506Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
fa65f20b
GM
6507from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
6508or if not called with a prefix arg, NEWNAME defaults to the current
6509buffer's name. The name is modified by adding a `<N>' suffix to it
1d2b0303
JB
6510or by incrementing the N in an existing suffix. Trying to clone a
6511buffer whose major mode symbol has a non-nil `no-clone-indirect'
6512property results in an error.
fa65f20b
GM
6513
6514DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7e3afb04
GM
6515This is always done when called interactively.
6516
f33321ad 6517Optional third arg NORECORD non-nil means do not put this buffer at the
7e3afb04 6518front of the list of recently selected ones."
61acfe7f
RS
6519 (interactive
6520 (progn
6521 (if (get major-mode 'no-clone-indirect)
6522 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6523 (list (if current-prefix-arg
f6039de6 6524 (read-buffer "Name of indirect buffer: " (current-buffer)))
61acfe7f
RS
6525 t)))
6526 (if (get major-mode 'no-clone-indirect)
6527 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
fa65f20b
GM
6528 (setq newname (or newname (buffer-name)))
6529 (if (string-match "<[0-9]+>\\'" newname)
6530 (setq newname (substring newname 0 (match-beginning 0))))
6531 (let* ((name (generate-new-buffer-name newname))
6532 (buffer (make-indirect-buffer (current-buffer) name t)))
64663f06
SM
6533 (with-current-buffer buffer
6534 (run-hooks 'clone-indirect-buffer-hook))
fa65f20b 6535 (when display-flag
58dd38f1 6536 (pop-to-buffer buffer norecord))
fa65f20b
GM
6537 buffer))
6538
6539
1fffd65f
RS
6540(defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
6541 "Like `clone-indirect-buffer' but display in another window."
2ef0a47e
RS
6542 (interactive
6543 (progn
6544 (if (get major-mode 'no-clone-indirect)
6545 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6546 (list (if current-prefix-arg
f6039de6 6547 (read-buffer "Name of indirect buffer: " (current-buffer)))
2ef0a47e 6548 t)))
acd39eb6 6549 (let ((pop-up-windows t))
1fffd65f 6550 (clone-indirect-buffer newname display-flag norecord)))
7e3afb04 6551
f54b0d85 6552\f
1d4b11bf
GM
6553;;; Handling of Backspace and Delete keys.
6554
30a2fded 6555(defcustom normal-erase-is-backspace 'maybe
3784ec80 6556 "Set the default behavior of the Delete and Backspace keys.
30a2fded
KL
6557
6558If set to t, Delete key deletes forward and Backspace key deletes
6559backward.
6560
6561If set to nil, both Delete and Backspace keys delete backward.
6562
6563If set to 'maybe (which is the default), Emacs automatically
3784ec80 6564selects a behavior. On window systems, the behavior depends on
30a2fded
KL
6565the keyboard used. If the keyboard has both a Backspace key and
6566a Delete key, and both are mapped to their usual meanings, the
6567option's default value is set to t, so that Backspace can be used
6568to delete backward, and Delete can be used to delete forward.
6569
6570If not running under a window system, customizing this option
6571accomplishes a similar effect by mapping C-h, which is usually
6572generated by the Backspace key, to DEL, and by mapping DEL to C-d
6573via `keyboard-translate'. The former functionality of C-h is
6574available on the F1 key. You should probably not use this
6575setting if you don't have both Backspace, Delete and F1 keys.
f060b834
GM
6576
6577Setting this variable with setq doesn't take effect. Programmatically,
7f62656b 6578call `normal-erase-is-backspace-mode' (which see) instead."
30a2fded
KL
6579 :type '(choice (const :tag "Off" nil)
6580 (const :tag "Maybe" maybe)
6581 (other :tag "On" t))
1d4b11bf
GM
6582 :group 'editing-basics
6583 :version "21.1"
6584 :set (lambda (symbol value)
6585 ;; The fboundp is because of a problem with :set when
6586 ;; dumping Emacs. It doesn't really matter.
7f62656b
EZ
6587 (if (fboundp 'normal-erase-is-backspace-mode)
6588 (normal-erase-is-backspace-mode (or value 0))
1d4b11bf
GM
6589 (set-default symbol value))))
6590
30a2fded
KL
6591(defun normal-erase-is-backspace-setup-frame (&optional frame)
6592 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
6593 (unless frame (setq frame (selected-frame)))
6594 (with-selected-frame frame
ed8dad6b 6595 (unless (terminal-parameter nil 'normal-erase-is-backspace)
08ea6d2f
SM
6596 (normal-erase-is-backspace-mode
6597 (if (if (eq normal-erase-is-backspace 'maybe)
6598 (and (not noninteractive)
6599 (or (memq system-type '(ms-dos windows-nt))
79cb9c05 6600 (memq window-system '(ns))
08ea6d2f
SM
6601 (and (memq window-system '(x))
6602 (fboundp 'x-backspace-delete-keys-p)
6603 (x-backspace-delete-keys-p))
6604 ;; If the terminal Emacs is running on has erase char
6605 ;; set to ^H, use the Backspace key for deleting
6606 ;; backward, and the Delete key for deleting forward.
6607 (and (null window-system)
6608 (eq tty-erase-char ?\^H))))
6609 normal-erase-is-backspace)
6610 1 0)))))
1d4b11bf 6611
80ac5d4d 6612(define-minor-mode normal-erase-is-backspace-mode
7f62656b
EZ
6613 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
6614
1d2b0303 6615With numeric ARG, turn the mode on if and only if ARG is positive.
7f62656b 6616
30a2fded
KL
6617On window systems, when this mode is on, Delete is mapped to C-d
6618and Backspace is mapped to DEL; when this mode is off, both
6619Delete and Backspace are mapped to DEL. (The remapping goes via
6620`local-function-key-map', so binding Delete or Backspace in the
6621global or local keymap will override that.)
7f62656b
EZ
6622
6623In addition, on window systems, the bindings of C-Delete, M-Delete,
6624C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
6625the global keymap in accordance with the functionality of Delete and
6626Backspace. For example, if Delete is remapped to C-d, which deletes
6627forward, C-Delete is bound to `kill-word', but if Delete is remapped
6628to DEL, which deletes backward, C-Delete is bound to
6629`backward-kill-word'.
6630
6631If not running on a window system, a similar effect is accomplished by
6632remapping C-h (normally produced by the Backspace key) and DEL via
6633`keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
6634to C-d; if it's off, the keys are not remapped.
6635
6636When not running on a window system, and this mode is turned on, the
6637former functionality of C-h is available on the F1 key. You should
6638probably not turn on this mode on a text-only terminal if you don't
6639have both Backspace, Delete and F1 keys.
6640
6641See also `normal-erase-is-backspace'."
80ac5d4d
SM
6642 :variable (eq (terminal-parameter
6643 nil 'normal-erase-is-backspace) 1)
6644 (let ((enabled (eq 1 (terminal-parameter
6645 nil 'normal-erase-is-backspace))))
0103b7c9 6646
9e2a2647 6647 (cond ((or (memq window-system '(x w32 ns pc))
0103b7c9 6648 (memq system-type '(ms-dos windows-nt)))
06b60517
JB
6649 (let ((bindings
6650 `(([M-delete] [M-backspace])
6651 ([C-M-delete] [C-M-backspace])
6652 ([?\e C-delete] [?\e C-backspace]))))
0103b7c9
KL
6653
6654 (if enabled
6655 (progn
b8a47412 6656 (define-key local-function-key-map [delete] [deletechar])
0103b7c9 6657 (define-key local-function-key-map [kp-delete] [?\C-d])
28a90c44
SM
6658 (define-key local-function-key-map [backspace] [?\C-?])
6659 (dolist (b bindings)
6660 ;; Not sure if input-decode-map is really right, but
6661 ;; keyboard-translate-table (used below) only works
6662 ;; for integer events, and key-translation-table is
6663 ;; global (like the global-map, used earlier).
6664 (define-key input-decode-map (car b) nil)
6665 (define-key input-decode-map (cadr b) nil)))
0103b7c9
KL
6666 (define-key local-function-key-map [delete] [?\C-?])
6667 (define-key local-function-key-map [kp-delete] [?\C-?])
28a90c44
SM
6668 (define-key local-function-key-map [backspace] [?\C-?])
6669 (dolist (b bindings)
6670 (define-key input-decode-map (car b) (cadr b))
6671 (define-key input-decode-map (cadr b) (car b))))))
0103b7c9
KL
6672 (t
6673 (if enabled
ec9f4754 6674 (progn
0103b7c9
KL
6675 (keyboard-translate ?\C-h ?\C-?)
6676 (keyboard-translate ?\C-? ?\C-d))
6677 (keyboard-translate ?\C-h ?\C-h)
6678 (keyboard-translate ?\C-? ?\C-?))))
6679
32226619 6680 (if (called-interactively-p 'interactive)
0103b7c9 6681 (message "Delete key deletes %s"
b08016f2 6682 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
0103b7c9 6683 "forward" "backward")))))
ea82f0df 6684\f
aca8bee5 6685(defvar vis-mode-saved-buffer-invisibility-spec nil
0f7df535 6686 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
7f62656b 6687
0f7df535
RS
6688(define-minor-mode visible-mode
6689 "Toggle Visible mode.
4837b516
GM
6690With argument ARG turn Visible mode on if ARG is positive, otherwise
6691turn it off.
1d4b11bf 6692
0f7df535 6693Enabling Visible mode makes all invisible text temporarily visible.
1d2b0303
JB
6694Disabling Visible mode turns off that effect. Visible mode works by
6695saving the value of `buffer-invisibility-spec' and setting it to nil."
4e57881d 6696 :lighter " Vis"
ab77efd0 6697 :group 'editing-basics
aca8bee5
SM
6698 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
6699 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
6700 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
0f7df535 6701 (when visible-mode
aca8bee5
SM
6702 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
6703 buffer-invisibility-spec)
6704 (setq buffer-invisibility-spec nil)))
4e57881d 6705\f
e1e04350 6706;; Minibuffer prompt stuff.
9b350152 6707
2ec42da9
SM
6708;;(defun minibuffer-prompt-modification (start end)
6709;; (error "You cannot modify the prompt"))
6710;;
6711;;
6712;;(defun minibuffer-prompt-insertion (start end)
6713;; (let ((inhibit-modification-hooks t))
6714;; (delete-region start end)
6715;; ;; Discard undo information for the text insertion itself
6716;; ;; and for the text deletion.above.
6717;; (when (consp buffer-undo-list)
6718;; (setq buffer-undo-list (cddr buffer-undo-list)))
6719;; (message "You cannot modify the prompt")))
6720;;
6721;;
6722;;(setq minibuffer-prompt-properties
6723;; (list 'modification-hooks '(minibuffer-prompt-modification)
6724;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
9b350152 6725
a2603048
GM
6726\f
6727;;;; Problematic external packages.
6728
6729;; rms says this should be done by specifying symbols that define
6730;; versions together with bad values. This is therefore not as
6731;; flexible as it could be. See the thread:
6732;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
6733(defconst bad-packages-alist
6734 ;; Not sure exactly which semantic versions have problems.
6735 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
7796ee61 6736 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
a2603048 6737 "The version of `semantic' loaded does not work in Emacs 22.
72d595b5
GM
6738It can cause constant high CPU load.
6739Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
a2603048
GM
6740 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
6741 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
6742 ;; provided the `CUA-mode' feature. Since this is no longer true,
6743 ;; we can warn the user if the `CUA-mode' feature is ever provided.
6744 (CUA-mode t nil
6745"CUA-mode is now part of the standard GNU Emacs distribution,
6746so you can now enable CUA via the Options menu or by customizing `cua-mode'.
6747
6748You have loaded an older version of CUA-mode which does not work
6749correctly with this version of Emacs. You should remove the old
6750version and use the one distributed with Emacs."))
6751 "Alist of packages known to cause problems in this version of Emacs.
6752Each element has the form (PACKAGE SYMBOL REGEXP STRING).
6753PACKAGE is either a regular expression to match file names, or a
6754symbol (a feature name); see the documentation of
6755`after-load-alist', to which this variable adds functions.
6756SYMBOL is either the name of a string variable, or `t'. Upon
6757loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
6758warning using STRING as the message.")
6759
6760(defun bad-package-check (package)
6761 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
6762 (condition-case nil
6763 (let* ((list (assoc package bad-packages-alist))
6764 (symbol (nth 1 list)))
6765 (and list
6766 (boundp symbol)
6767 (or (eq symbol t)
6768 (and (stringp (setq symbol (eval symbol)))
9bc505ab
JB
6769 (string-match-p (nth 2 list) symbol)))
6770 (display-warning package (nth 3 list) :warning)))
a2603048
GM
6771 (error nil)))
6772
6773(mapc (lambda (elem)
6774 (eval-after-load (car elem) `(bad-package-check ',(car elem))))
6775 bad-packages-alist)
6776
6777
00398e3b 6778(provide 'simple)
6b61353c 6779
c88ab9ce 6780;;; simple.el ends here