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