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