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