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