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