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