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