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