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