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