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