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