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