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