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