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