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