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