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