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