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