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