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