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