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