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