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