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