(Fread_from_minibuffer): Make position 0 in the initial
[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 ))
831 (shell-command-on-region (point) (point) command nil)
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.
e6291fe1
RS
1224 ((or (and buffer-read-only (not inhibit-read-only))
1225 (text-property-not-all beg end 'read-only nil))
2aa7a8bf 1226 (copy-region-as-kill beg end)
1537a263 1227 ;; This should always barf, and give us the correct error.
e6291fe1
RS
1228 (if kill-read-only-ok
1229 (message "Read only text copied to kill ring")
626a097c 1230 (setq this-command 'kill-region)
3a5da8a8
RS
1231 ;; Signal an error if the buffer is read-only.
1232 (barf-if-buffer-read-only)
1233 ;; If the buffer isn't read-only, the text is.
1234 (signal 'text-read-only (list (current-buffer)))))
2aa7a8bf
JB
1235
1236 ;; In certain cases, we can arrange for the undo list and the kill
1237 ;; ring to share the same string object. This code does that.
70e14c01
JB
1238 ((not (or (eq buffer-undo-list t)
1239 (eq last-command 'kill-region)
713dca1c
RS
1240 ;; Use = since positions may be numbers or markers.
1241 (= beg end)))
70e14c01 1242 ;; Don't let the undo list be truncated before we can even access it.
12bcd3b6
RS
1243 (let ((undo-strong-limit (+ (- (max beg end) (min beg end)) 100))
1244 (old-list buffer-undo-list)
1245 tail)
70e14c01 1246 (delete-region beg end)
12bcd3b6
RS
1247 ;; Search back in buffer-undo-list for this string,
1248 ;; in case a change hook made property changes.
1249 (setq tail buffer-undo-list)
1250 (while (not (stringp (car (car tail))))
1251 (setq tail (cdr tail)))
70e14c01
JB
1252 ;; Take the same string recorded for undo
1253 ;; and put it in the kill-ring.
626a097c 1254 (kill-new (car (car tail)))))
2aa7a8bf 1255
70e14c01 1256 (t
2076c87c 1257 (copy-region-as-kill beg end)
626a097c
KH
1258 (delete-region beg end)))
1259 (setq this-command 'kill-region))
2076c87c 1260
a382890a
KH
1261;; copy-region-as-kill no longer sets this-command, because it's confusing
1262;; to get two copies of the text when the user accidentally types M-w and
1263;; then corrects it with the intended C-w.
2076c87c
JB
1264(defun copy-region-as-kill (beg end)
1265 "Save the region as if killed, but don't kill it.
46947372
JB
1266If `interprogram-cut-function' is non-nil, also save the text for a window
1267system cut and paste."
2076c87c
JB
1268 (interactive "r")
1269 (if (eq last-command 'kill-region)
1270 (kill-append (buffer-substring beg end) (< end beg))
70e14c01 1271 (kill-new (buffer-substring beg end)))
2076c87c
JB
1272 nil)
1273
1274(defun kill-ring-save (beg end)
0964e562 1275 "Save the region as if killed, but don't kill it.
230c6b36 1276This command is similar to `copy-region-as-kill', except that it gives
0964e562
JB
1277visual feedback indicating the extent of the region being copied.
1278If `interprogram-cut-function' is non-nil, also save the text for a window
1279system cut and paste."
2076c87c
JB
1280 (interactive "r")
1281 (copy-region-as-kill beg end)
3a801d0c 1282 (if (interactive-p)
66050f10
RS
1283 (let ((other-end (if (= (point) beg) end beg))
1284 (opoint (point))
1285 ;; Inhibit quitting so we can make a quit here
1286 ;; look like a C-g typed as a command.
1287 (inhibit-quit t))
1288 (if (pos-visible-in-window-p other-end (selected-window))
1289 (progn
1290 ;; Swap point and mark.
1291 (set-marker (mark-marker) (point) (current-buffer))
1292 (goto-char other-end)
1293 (sit-for 1)
1294 ;; Swap back.
1295 (set-marker (mark-marker) other-end (current-buffer))
1296 (goto-char opoint)
1297 ;; If user quit, deactivate the mark
1298 ;; as C-g would as a command.
e4e593ae 1299 (and quit-flag mark-active
fcadf1c7 1300 (deactivate-mark)))
66050f10
RS
1301 (let* ((killed-text (current-kill 0))
1302 (message-len (min (length killed-text) 40)))
1303 (if (= (point) beg)
1304 ;; Don't say "killed"; that is misleading.
1305 (message "Saved text until \"%s\""
1306 (substring killed-text (- message-len)))
1307 (message "Saved text from \"%s\""
1308 (substring killed-text 0 message-len))))))))
2076c87c
JB
1309
1310(defun append-next-kill ()
ff1fbe3e 1311 "Cause following command, if it kills, to append to previous kill."
2076c87c
JB
1312 (interactive)
1313 (if (interactive-p)
1314 (progn
1315 (setq this-command 'kill-region)
1316 (message "If the next command is a kill, it will append"))
1317 (setq last-command 'kill-region)))
1318
2076c87c 1319(defun yank-pop (arg)
ff1fbe3e
RS
1320 "Replace just-yanked stretch of killed text with a different stretch.
1321This command is allowed only immediately after a `yank' or a `yank-pop'.
2076c87c 1322At such a time, the region contains a stretch of reinserted
ff1fbe3e 1323previously-killed text. `yank-pop' deletes that text and inserts in its
2076c87c
JB
1324place a different stretch of killed text.
1325
1326With no argument, the previous kill is inserted.
ff1fbe3e
RS
1327With argument N, insert the Nth previous kill.
1328If N is negative, this is a more recent kill.
2076c87c
JB
1329
1330The sequence of kills wraps around, so that after the oldest one
1331comes the newest one."
1332 (interactive "*p")
1333 (if (not (eq last-command 'yank))
1334 (error "Previous command was not a yank"))
1335 (setq this-command 'yank)
3a5da8a8
RS
1336 (let ((inhibit-read-only t)
1337 (before (< (point) (mark t))))
9a1277dd 1338 (delete-region (point) (mark t))
fd0f4056 1339 (set-marker (mark-marker) (point) (current-buffer))
70e14c01 1340 (insert (current-kill arg))
fd0f4056
RS
1341 (if before
1342 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
1343 ;; It is cleaner to avoid activation, even though the command
1344 ;; loop would deactivate the mark because we inserted text.
1345 (goto-char (prog1 (mark t)
1346 (set-marker (mark-marker) (point) (current-buffer))))))
0964e562 1347 nil)
2076c87c
JB
1348
1349(defun yank (&optional arg)
1350 "Reinsert the last stretch of killed text.
1351More precisely, reinsert the stretch of killed text most recently
ff1fbe3e
RS
1352killed OR yanked. Put point at end, and set mark at beginning.
1353With just C-u as argument, same but put point at beginning (and mark at end).
1354With argument N, reinsert the Nth most recently killed stretch of killed
2076c87c
JB
1355text.
1356See also the command \\[yank-pop]."
1357 (interactive "*P")
456c617c
RS
1358 ;; If we don't get all the way thru, make last-command indicate that
1359 ;; for the following command.
1360 (setq this-command t)
2076c87c 1361 (push-mark (point))
70e14c01
JB
1362 (insert (current-kill (cond
1363 ((listp arg) 0)
1364 ((eq arg '-) -1)
1365 (t (1- arg)))))
2076c87c 1366 (if (consp arg)
fd0f4056
RS
1367 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
1368 ;; It is cleaner to avoid activation, even though the command
1369 ;; loop would deactivate the mark because we inserted text.
1370 (goto-char (prog1 (mark t)
1371 (set-marker (mark-marker) (point) (current-buffer)))))
456c617c
RS
1372 ;; If we do get all the way thru, make this-command indicate that.
1373 (setq this-command 'yank)
0964e562 1374 nil)
70e14c01
JB
1375
1376(defun rotate-yank-pointer (arg)
1377 "Rotate the yanking point in the kill ring.
1378With argument, rotate that many kills forward (or backward, if negative)."
1379 (interactive "p")
1380 (current-kill arg))
1381
2076c87c
JB
1382\f
1383(defun insert-buffer (buffer)
1384 "Insert after point the contents of BUFFER.
1385Puts mark after the inserted text.
1386BUFFER may be a buffer or a buffer name."
c3d4f949 1387 (interactive
a3e7c391
FP
1388 (list
1389 (progn
1390 (barf-if-buffer-read-only)
1391 (read-buffer "Insert buffer: "
1392 (if (eq (selected-window) (next-window (selected-window)))
1393 (other-buffer (current-buffer))
1394 (window-buffer (next-window (selected-window))))
1395 t))))
2076c87c
JB
1396 (or (bufferp buffer)
1397 (setq buffer (get-buffer buffer)))
1398 (let (start end newmark)
1399 (save-excursion
1400 (save-excursion
1401 (set-buffer buffer)
1402 (setq start (point-min) end (point-max)))
1403 (insert-buffer-substring buffer start end)
1404 (setq newmark (point)))
1537a263
JB
1405 (push-mark newmark))
1406 nil)
2076c87c
JB
1407
1408(defun append-to-buffer (buffer start end)
1409 "Append to specified buffer the text of the region.
1410It is inserted into that buffer before its point.
1411
1412When calling from a program, give three arguments:
1413BUFFER (or buffer name), START and END.
1414START and END specify the portion of the current buffer to be copied."
70e14c01 1415 (interactive
5d771766 1416 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
23efee2c 1417 (region-beginning) (region-end)))
2076c87c
JB
1418 (let ((oldbuf (current-buffer)))
1419 (save-excursion
1420 (set-buffer (get-buffer-create buffer))
1421 (insert-buffer-substring oldbuf start end))))
1422
1423(defun prepend-to-buffer (buffer start end)
1424 "Prepend to specified buffer the text of the region.
1425It is inserted into that buffer after its point.
1426
1427When calling from a program, give three arguments:
1428BUFFER (or buffer name), START and END.
1429START and END specify the portion of the current buffer to be copied."
1430 (interactive "BPrepend to buffer: \nr")
1431 (let ((oldbuf (current-buffer)))
1432 (save-excursion
1433 (set-buffer (get-buffer-create buffer))
1434 (save-excursion
1435 (insert-buffer-substring oldbuf start end)))))
1436
1437(defun copy-to-buffer (buffer start end)
1438 "Copy to specified buffer the text of the region.
1439It is inserted into that buffer, replacing existing text there.
1440
1441When calling from a program, give three arguments:
1442BUFFER (or buffer name), START and END.
1443START and END specify the portion of the current buffer to be copied."
1444 (interactive "BCopy to buffer: \nr")
1445 (let ((oldbuf (current-buffer)))
1446 (save-excursion
1447 (set-buffer (get-buffer-create buffer))
1448 (erase-buffer)
1449 (save-excursion
1450 (insert-buffer-substring oldbuf start end)))))
1451\f
62d1c1fc
RM
1452(put 'mark-inactive 'error-conditions '(mark-inactive error))
1453(put 'mark-inactive 'error-message "The mark is not active now")
1454
af39530e 1455(defun mark (&optional force)
c7c8b31e 1456 "Return this buffer's mark value as integer; error if mark inactive.
af39530e 1457If optional argument FORCE is non-nil, access the mark value
c7c8b31e
RS
1458even if the mark is not currently active, and return nil
1459if there is no mark at all.
af39530e 1460
2076c87c
JB
1461If you are using this in an editing command, you are most likely making
1462a mistake; see the documentation of `set-mark'."
0e3a7b14 1463 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
af39530e 1464 (marker-position (mark-marker))
62d1c1fc 1465 (signal 'mark-inactive nil)))
2076c87c 1466
19d35374
RM
1467;; Many places set mark-active directly, and several of them failed to also
1468;; run deactivate-mark-hook. This shorthand should simplify.
1469(defsubst deactivate-mark ()
1470 "Deactivate the mark by setting `mark-active' to nil.
fcadf1c7 1471\(That makes a difference only in Transient Mark mode.)
19d35374 1472Also runs the hook `deactivate-mark-hook'."
a4b9d3da
RS
1473 (if transient-mark-mode
1474 (progn
1475 (setq mark-active nil)
1476 (run-hooks 'deactivate-mark-hook))))
19d35374 1477
2076c87c
JB
1478(defun set-mark (pos)
1479 "Set this buffer's mark to POS. Don't use this function!
1480That is to say, don't use this function unless you want
1481the user to see that the mark has moved, and you want the previous
1482mark position to be lost.
1483
1484Normally, when a new mark is set, the old one should go on the stack.
1485This is why most applications should use push-mark, not set-mark.
1486
ff1fbe3e 1487Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
1488purposes. The mark saves a location for the user's convenience.
1489Most editing commands should not alter the mark.
1490To remember a location for internal use in the Lisp program,
1491store it in a Lisp variable. Example:
1492
1493 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
1494
fcadf1c7
RS
1495 (if pos
1496 (progn
1497 (setq mark-active t)
1498 (run-hooks 'activate-mark-hook)
1499 (set-marker (mark-marker) pos (current-buffer)))
24c22852
RS
1500 ;; Normally we never clear mark-active except in Transient Mark mode.
1501 ;; But when we actually clear out the mark value too,
1502 ;; we must clear mark-active in any mode.
1503 (setq mark-active nil)
1504 (run-hooks 'deactivate-mark-hook)
1505 (set-marker (mark-marker) nil)))
2076c87c
JB
1506
1507(defvar mark-ring nil
e55e2267 1508 "The list of former marks of the current buffer, most recent first.")
2076c87c 1509(make-variable-buffer-local 'mark-ring)
e55e2267 1510(put 'mark-ring 'permanent-local t)
2076c87c
JB
1511
1512(defconst mark-ring-max 16
1513 "*Maximum size of mark ring. Start discarding off end if gets this big.")
1514
dc029f0b
RM
1515(defvar global-mark-ring nil
1516 "The list of saved global marks, most recent first.")
1517
1518(defconst global-mark-ring-max 16
1519 "*Maximum size of global mark ring. \
1520Start discarding off end if gets this big.")
1521
2076c87c
JB
1522(defun set-mark-command (arg)
1523 "Set mark at where point is, or jump to mark.
dc029f0b
RM
1524With no prefix argument, set mark, push old mark position on local mark
1525ring, and push mark on global mark ring.
1526With argument, jump to mark, and pop a new position for mark off the ring
1527\(does not affect global mark ring\).
2076c87c 1528
ff1fbe3e 1529Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
1530purposes. See the documentation of `set-mark' for more information."
1531 (interactive "P")
1532 (if (null arg)
9a1277dd 1533 (progn
fd0f4056 1534 (push-mark nil nil t))
af39530e 1535 (if (null (mark t))
2076c87c 1536 (error "No mark set in this buffer")
9a1277dd 1537 (goto-char (mark t))
2076c87c
JB
1538 (pop-mark))))
1539
fd0f4056 1540(defun push-mark (&optional location nomsg activate)
2076c87c 1541 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
f1382a3d
RM
1542If the last global mark pushed was not in the current buffer,
1543also push LOCATION on the global mark ring.
fd0f4056 1544Display `Mark set' unless the optional second arg NOMSG is non-nil.
8cdc660f 1545In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
2076c87c 1546
ff1fbe3e 1547Novice Emacs Lisp programmers often try to use the mark for the wrong
9a1277dd
RS
1548purposes. See the documentation of `set-mark' for more information.
1549
1550In Transient Mark mode, this does not activate the mark."
af39530e 1551 (if (null (mark t))
2076c87c
JB
1552 nil
1553 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
1554 (if (> (length mark-ring) mark-ring-max)
1555 (progn
1556 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
1557 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil))))
9a1277dd 1558 (set-marker (mark-marker) (or location (point)) (current-buffer))
dc029f0b 1559 ;; Now push the mark on the global mark ring.
f1382a3d 1560 (if (and global-mark-ring
e08d3f7c 1561 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
f1382a3d
RM
1562 ;; The last global mark pushed was in this same buffer.
1563 ;; Don't push another one.
1564 nil
1565 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
dc029f0b
RM
1566 (if (> (length global-mark-ring) global-mark-ring-max)
1567 (progn
1568 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring))
1569 nil)
f1382a3d 1570 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil))))
efcf38c7 1571 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
2076c87c 1572 (message "Mark set"))
8cdc660f
RS
1573 (if (or activate (not transient-mark-mode))
1574 (set-mark (mark t)))
2076c87c
JB
1575 nil)
1576
1577(defun pop-mark ()
1578 "Pop off mark ring into the buffer's actual mark.
1579Does not set point. Does nothing if mark ring is empty."
1580 (if mark-ring
1581 (progn
1582 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
9a1277dd 1583 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
19d35374 1584 (deactivate-mark)
2076c87c 1585 (move-marker (car mark-ring) nil)
9a1277dd 1586 (if (null (mark t)) (ding))
2076c87c
JB
1587 (setq mark-ring (cdr mark-ring)))))
1588
dff7d67f 1589(define-function 'exchange-dot-and-mark 'exchange-point-and-mark)
2076c87c 1590(defun exchange-point-and-mark ()
af39530e
RS
1591 "Put the mark where point is now, and point where the mark is now.
1592This command works even when the mark is not active,
1593and it reactivates the mark."
2076c87c 1594 (interactive nil)
af39530e 1595 (let ((omark (mark t)))
2076c87c
JB
1596 (if (null omark)
1597 (error "No mark set in this buffer"))
1598 (set-mark (point))
1599 (goto-char omark)
1600 nil))
e23c2c21
RS
1601
1602(defun transient-mark-mode (arg)
1603 "Toggle Transient Mark mode.
b411b5fa 1604With arg, turn Transient Mark mode on if arg is positive, off otherwise.
e23c2c21 1605
5dd1220d
RS
1606In Transient Mark mode, when the mark is active, the region is highlighted.
1607Changing the buffer \"deactivates\" the mark.
1608So do certain other operations that set the mark
1609but whose main purpose is something else--for example,
1610incremental search, \\[beginning-of-buffer], and \\[end-of-buffer]."
e23c2c21
RS
1611 (interactive "P")
1612 (setq transient-mark-mode
1613 (if (null arg)
1614 (not transient-mark-mode)
1615 (> (prefix-numeric-value arg) 0))))
dc029f0b
RM
1616
1617(defun pop-global-mark ()
1618 "Pop off global mark ring and jump to the top location."
1619 (interactive)
52b6d445
RS
1620 ;; Pop entries which refer to non-existent buffers.
1621 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
1622 (setq global-mark-ring (cdr global-mark-ring)))
dc029f0b
RM
1623 (or global-mark-ring
1624 (error "No global mark set"))
1625 (let* ((marker (car global-mark-ring))
1626 (buffer (marker-buffer marker))
1627 (position (marker-position marker)))
34c31301
RS
1628 (setq global-mark-ring (nconc (cdr global-mark-ring)
1629 (list (car global-mark-ring))))
dc029f0b
RM
1630 (set-buffer buffer)
1631 (or (and (>= position (point-min))
1632 (<= position (point-max)))
1633 (widen))
1634 (goto-char position)
1635 (switch-to-buffer buffer)))
2076c87c 1636\f
38ebcf29 1637(defvar next-line-add-newlines t
dff7d67f 1638 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error.")
38ebcf29 1639
2076c87c
JB
1640(defun next-line (arg)
1641 "Move cursor vertically down ARG lines.
1642If there is no character in the target line exactly under the current column,
1643the cursor is positioned after the character in that line which spans this
1644column, or at the end of the line if it is not long enough.
38ebcf29 1645If there is no line in the buffer after this one, behavior depends on the
1a2c3941
RS
1646value of `next-line-add-newlines'. If non-nil, it inserts a newline character
1647to create a line, and moves the cursor to that line. Otherwise it moves the
e47d38f6 1648cursor to the end of the buffer.
2076c87c
JB
1649
1650The command \\[set-goal-column] can be used to create
1651a semipermanent goal column to which this command always moves.
1652Then it does not try to move vertically. This goal column is stored
1653in `goal-column', which is nil when there is none.
1654
1655If you are thinking of using this in a Lisp program, consider
1656using `forward-line' instead. It is usually easier to use
1657and more reliable (no dependence on goal column, etc.)."
1658 (interactive "p")
028922cf
RS
1659 (if (and next-line-add-newlines (= arg 1))
1660 (let ((opoint (point)))
3534a809
RS
1661 (end-of-line)
1662 (if (eobp)
28191e20 1663 (newline 1)
028922cf
RS
1664 (goto-char opoint)
1665 (line-move arg)))
1a2c3941
RS
1666 (if (interactive-p)
1667 (condition-case nil
1668 (line-move arg)
1669 ((beginning-of-buffer end-of-buffer) (ding)))
1670 (line-move arg)))
2076c87c
JB
1671 nil)
1672
1673(defun previous-line (arg)
1674 "Move cursor vertically up ARG lines.
1675If there is no character in the target line exactly over the current column,
1676the cursor is positioned after the character in that line which spans this
1677column, or at the end of the line if it is not long enough.
1678
1679The command \\[set-goal-column] can be used to create
1680a semipermanent goal column to which this command always moves.
1681Then it does not try to move vertically.
1682
1683If you are thinking of using this in a Lisp program, consider using
c2e8a012 1684`forward-line' with a negative argument instead. It is usually easier
2076c87c
JB
1685to use and more reliable (no dependence on goal column, etc.)."
1686 (interactive "p")
1a2c3941
RS
1687 (if (interactive-p)
1688 (condition-case nil
1689 (line-move (- arg))
1690 ((beginning-of-buffer end-of-buffer) (ding)))
1691 (line-move (- arg)))
2076c87c
JB
1692 nil)
1693
1694(defconst track-eol nil
1695 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
1696This means moving to the end of each line moved onto.
1697The beginning of a blank line does not count as the end of a line.")
1698
912c6728
RS
1699(defvar goal-column nil
1700 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.")
1701(make-variable-buffer-local 'goal-column)
2076c87c
JB
1702
1703(defvar temporary-goal-column 0
1704 "Current goal column for vertical motion.
1705It is the column where point was
1706at the start of current run of vertical motion commands.
c637ae6f 1707When the `track-eol' feature is doing its job, the value is 9999.")
2076c87c 1708
098fc1fb
RS
1709(defvar line-move-ignore-invisible nil
1710 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
1711Outline mode sets this.")
1712
8c745744
RS
1713;; This is the guts of next-line and previous-line.
1714;; Arg says how many lines to move.
2076c87c 1715(defun line-move (arg)
2596511d
RS
1716 ;; Don't run any point-motion hooks, and disregard intangibility,
1717 ;; for intermediate positions.
1718 (let ((inhibit-point-motion-hooks t)
1719 (opoint (point))
1720 new)
1721 (unwind-protect
1722 (progn
1723 (if (not (or (eq last-command 'next-line)
1724 (eq last-command 'previous-line)))
1725 (setq temporary-goal-column
1726 (if (and track-eol (eolp)
1727 ;; Don't count beg of empty line as end of line
1728 ;; unless we just did explicit end-of-line.
1729 (or (not (bolp)) (eq last-command 'end-of-line)))
1730 9999
1731 (current-column))))
1732 (if (and (not (integerp selective-display))
1733 (not line-move-ignore-invisible))
1734 ;; Use just newline characters.
1735 (or (if (> arg 0)
1736 (progn (if (> arg 1) (forward-line (1- arg)))
1737 ;; This way of moving forward ARG lines
1738 ;; verifies that we have a newline after the last one.
1739 ;; It doesn't get confused by intangible text.
1740 (end-of-line)
1741 (zerop (forward-line 1)))
1742 (and (zerop (forward-line arg))
1743 (bolp)))
1744 (signal (if (< arg 0)
1745 'beginning-of-buffer
1746 'end-of-buffer)
1747 nil))
1748 ;; Move by arg lines, but ignore invisible ones.
1749 (while (> arg 0)
1750 (end-of-line)
1751 (and (zerop (vertical-motion 1))
1752 (signal 'end-of-buffer nil))
1753 ;; If the following character is currently invisible,
1754 ;; skip all characters with that same `invisible' property value.
1755 (while (and (not (eobp))
1756 (let ((prop
1757 (get-char-property (point) 'invisible)))
1758 (if (eq buffer-invisibility-spec t)
1759 prop
1760 (or (memq prop buffer-invisibility-spec)
1761 (assq prop buffer-invisibility-spec)))))
1762 (if (get-text-property (point) 'invisible)
1763 (goto-char (next-single-property-change (point) 'invisible))
1764 (goto-char (next-overlay-change (point)))))
1765 (setq arg (1- arg)))
1766 (while (< arg 0)
1767 (beginning-of-line)
1768 (and (zerop (vertical-motion -1))
1769 (signal 'beginning-of-buffer nil))
1770 (while (and (not (bobp))
1771 (let ((prop
1772 (get-char-property (1- (point)) 'invisible)))
1773 (if (eq buffer-invisibility-spec t)
1774 prop
1775 (or (memq prop buffer-invisibility-spec)
1776 (assq prop buffer-invisibility-spec)))))
1777 (if (get-text-property (1- (point)) 'invisible)
1778 (goto-char (previous-single-property-change (point) 'invisible))
1779 (goto-char (previous-overlay-change (point)))))
1780 (setq arg (1+ arg))))
1781 (move-to-column (or goal-column temporary-goal-column)))
1782 ;; Remember where we moved to, go back home,
1783 ;; then do the motion over again
1784 ;; in just one step, with intangibility and point-motion hooks
1785 ;; enabled this time.
1786 (setq new (point))
1787 (goto-char opoint)
1788 (setq inhibit-point-motion-hooks nil)
1789 (goto-char new)))
1790 nil)
2076c87c 1791
d5ab2033
JB
1792;;; Many people have said they rarely use this feature, and often type
1793;;; it by accident. Maybe it shouldn't even be on a key.
1794(put 'set-goal-column 'disabled t)
2076c87c
JB
1795
1796(defun set-goal-column (arg)
1797 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
1798Those commands will move to this position in the line moved to
1799rather than trying to keep the same horizontal position.
1800With a non-nil argument, clears out the goal column
912c6728
RS
1801so that \\[next-line] and \\[previous-line] resume vertical motion.
1802The goal column is stored in the variable `goal-column'."
2076c87c
JB
1803 (interactive "P")
1804 (if arg
1805 (progn
1806 (setq goal-column nil)
1807 (message "No goal column"))
1808 (setq goal-column (current-column))
1809 (message (substitute-command-keys
1810 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
1811 goal-column))
1812 nil)
1813\f
0d5bbbf7
ER
1814;;; Partial support for horizontal autoscrolling. Someday, this feature
1815;;; will be built into the C level and all the (hscroll-point-visible) calls
1816;;; will go away.
1817
1818(defvar hscroll-step 0
1819 "*The number of columns to try scrolling a window by when point moves out.
1820If that fails to bring point back on frame, point is centered instead.
1821If this is zero, point is always centered after it moves off frame.")
1822
1823(defun hscroll-point-visible ()
26c5bf8e
KH
1824 "Scrolls the selected window horizontally to make point visible."
1825 (save-excursion
1826 (set-buffer (window-buffer))
1827 (if (not (or truncate-lines
1828 (> (window-hscroll) 0)
1829 (and truncate-partial-width-windows
1830 (< (window-width) (frame-width)))))
1831 ;; Point is always visible when lines are wrapped.
1832 ()
1833 ;; If point is on the invisible part of the line before window-start,
1834 ;; then hscrolling can't bring it back, so reset window-start first.
1835 (and (< (point) (window-start))
1836 (let ((ws-bol (save-excursion
1837 (goto-char (window-start))
1838 (beginning-of-line)
1839 (point))))
1840 (and (>= (point) ws-bol)
1841 (set-window-start nil ws-bol))))
1842 (let* ((here (hscroll-window-column))
1843 (left (min (window-hscroll) 1))
1844 (right (1- (window-width))))
1845 ;; Allow for the truncation glyph, if we're not exactly at eol.
1846 (if (not (and (= here right)
1847 (= (following-char) ?\n)))
1848 (setq right (1- right)))
1849 (cond
1850 ;; If too far away, just recenter. But don't show too much
1851 ;; white space off the end of the line.
1852 ((or (< here (- left hscroll-step))
1853 (> here (+ right hscroll-step)))
1854 (let ((eol (save-excursion (end-of-line) (hscroll-window-column))))
1855 (scroll-left (min (- here (/ (window-width) 2))
1856 (- eol (window-width) -5)))))
1857 ;; Within range. Scroll by one step (or maybe not at all).
1858 ((< here left)
1859 (scroll-right hscroll-step))
1860 ((> here right)
1861 (scroll-left hscroll-step)))))))
1862
1863;; This function returns the window's idea of the display column of point,
1864;; assuming that the window is already known to be truncated rather than
1865;; wrapped, and that we've already handled the case where point is on the
1866;; part of the line before window-start. We ignore window-width; if point
1867;; is beyond the right margin, we want to know how far. The return value
1868;; includes the effects of window-hscroll, window-start, and the prompt
1869;; string in the minibuffer. It may be negative due to hscroll.
1870(defun hscroll-window-column ()
1871 (let* ((hscroll (window-hscroll))
1872 (startpos (save-excursion
1873 (beginning-of-line)
1874 (if (= (point) (save-excursion
1875 (goto-char (window-start))
1876 (beginning-of-line)
1877 (point)))
1878 (goto-char (window-start)))
1879 (point)))
1880 (hpos (+ (if (and (eq (selected-window) (minibuffer-window))
1881 (= 1 (window-start))
1882 (= startpos (point-min)))
1883 (minibuffer-prompt-width)
1884 0)
1885 (min 0 (- 1 hscroll))))
1886 val)
1887 (car (cdr (compute-motion startpos (cons hpos 0)
1888 (point) (cons 0 1)
1889 1000000 (cons hscroll 0) nil)))))
1890
0d5bbbf7 1891
dff7d67f
RS
1892;; rms: (1) The definitions of arrow keys should not simply restate
1893;; what keys they are. The arrow keys should run the ordinary commands.
1894;; (2) The arrow keys are just one of many common ways of moving point
1895;; within a line. Real horizontal autoscrolling would be a good feature,
1896;; but supporting it only for arrow keys is too incomplete to be desirable.
1897
1898;;;;; Make arrow keys do the right thing for improved terminal support
1899;;;;; When we implement true horizontal autoscrolling, right-arrow and
1900;;;;; left-arrow can lose the (if truncate-lines ...) clause and become
1901;;;;; aliases. These functions are bound to the corresponding keyboard
1902;;;;; events in loaddefs.el.
1903
1904;;(defun right-arrow (arg)
1905;; "Move right one character on the screen (with prefix ARG, that many chars).
1906;;Scroll right if needed to keep point horizontally onscreen."
1907;; (interactive "P")
1908;; (forward-char arg)
1909;; (hscroll-point-visible))
1910
1911;;(defun left-arrow (arg)
1912;; "Move left one character on the screen (with prefix ARG, that many chars).
1913;;Scroll left if needed to keep point horizontally onscreen."
1914;; (interactive "P")
1915;; (backward-char arg)
1916;; (hscroll-point-visible))
7492f5a6
RS
1917
1918(defun scroll-other-window-down (lines)
e47d38f6
RS
1919 "Scroll the \"other window\" down.
1920For more details, see the documentation for `scroll-other-window'."
7492f5a6
RS
1921 (interactive "P")
1922 (scroll-other-window
1923 ;; Just invert the argument's meaning.
1924 ;; We can do that without knowing which window it will be.
1925 (if (eq lines '-) nil
1926 (if (null lines) '-
1927 (- (prefix-numeric-value lines))))))
e47d38f6 1928(define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
3aef9604
RS
1929
1930(defun beginning-of-buffer-other-window (arg)
1931 "Move point to the beginning of the buffer in the other window.
1932Leave mark at previous position.
1933With arg N, put point N/10 of the way from the true beginning."
1934 (interactive "P")
1935 (let ((orig-window (selected-window))
1936 (window (other-window-for-scrolling)))
1937 ;; We use unwind-protect rather than save-window-excursion
1938 ;; because the latter would preserve the things we want to change.
1939 (unwind-protect
1940 (progn
1941 (select-window window)
1942 ;; Set point and mark in that window's buffer.
1943 (beginning-of-buffer arg)
1944 ;; Set point accordingly.
1945 (recenter '(t)))
1946 (select-window orig-window))))
1947
1948(defun end-of-buffer-other-window (arg)
1949 "Move point to the end of the buffer in the other window.
1950Leave mark at previous position.
1951With arg N, put point N/10 of the way from the true end."
1952 (interactive "P")
1953 ;; See beginning-of-buffer-other-window for comments.
1954 (let ((orig-window (selected-window))
1955 (window (other-window-for-scrolling)))
1956 (unwind-protect
1957 (progn
1958 (select-window window)
4500ff36 1959 (end-of-buffer arg)
3aef9604
RS
1960 (recenter '(t)))
1961 (select-window orig-window))))
38ebcf29 1962\f
2076c87c
JB
1963(defun transpose-chars (arg)
1964 "Interchange characters around point, moving forward one character.
1965With prefix arg ARG, effect is to take character before point
1966and drag it forward past ARG other characters (backward if ARG negative).
1967If no argument and at end of line, the previous two chars are exchanged."
1968 (interactive "*P")
1969 (and (null arg) (eolp) (forward-char -1))
1970 (transpose-subr 'forward-char (prefix-numeric-value arg)))
1971
1972(defun transpose-words (arg)
1973 "Interchange words around point, leaving point at end of them.
1974With prefix arg ARG, effect is to take word before or around point
1975and drag it forward past ARG other words (backward if ARG negative).
1976If ARG is zero, the words around or after point and around or after mark
1977are interchanged."
1978 (interactive "*p")
1979 (transpose-subr 'forward-word arg))
1980
1981(defun transpose-sexps (arg)
1982 "Like \\[transpose-words] but applies to sexps.
1983Does not work on a sexp that point is in the middle of
1984if it is a list or string."
1985 (interactive "*p")
1986 (transpose-subr 'forward-sexp arg))
1987
1988(defun transpose-lines (arg)
1989 "Exchange current line and previous line, leaving point after both.
1990With argument ARG, takes previous line and moves it past ARG lines.
1991With argument 0, interchanges line point is in with line mark is in."
1992 (interactive "*p")
1993 (transpose-subr (function
1994 (lambda (arg)
1995 (if (= arg 1)
1996 (progn
1997 ;; Move forward over a line,
1998 ;; but create a newline if none exists yet.
1999 (end-of-line)
2000 (if (eobp)
2001 (newline)
2002 (forward-char 1)))
2003 (forward-line arg))))
2004 arg))
2005
2006(defun transpose-subr (mover arg)
2007 (let (start1 end1 start2 end2)
2008 (if (= arg 0)
2009 (progn
2010 (save-excursion
2011 (funcall mover 1)
2012 (setq end2 (point))
2013 (funcall mover -1)
2014 (setq start2 (point))
2015 (goto-char (mark))
2016 (funcall mover 1)
2017 (setq end1 (point))
2018 (funcall mover -1)
2019 (setq start1 (point))
2020 (transpose-subr-1))
2021 (exchange-point-and-mark)))
2022 (while (> arg 0)
2023 (funcall mover -1)
2024 (setq start1 (point))
2025 (funcall mover 1)
2026 (setq end1 (point))
2027 (funcall mover 1)
2028 (setq end2 (point))
2029 (funcall mover -1)
2030 (setq start2 (point))
2031 (transpose-subr-1)
2032 (goto-char end2)
2033 (setq arg (1- arg)))
2034 (while (< arg 0)
2035 (funcall mover -1)
2036 (setq start2 (point))
2037 (funcall mover -1)
2038 (setq start1 (point))
2039 (funcall mover 1)
2040 (setq end1 (point))
2041 (funcall mover 1)
2042 (setq end2 (point))
2043 (transpose-subr-1)
2044 (setq arg (1+ arg)))))
2045
2046(defun transpose-subr-1 ()
2047 (if (> (min end1 end2) (max start1 start2))
2048 (error "Don't have two things to transpose"))
2049 (let ((word1 (buffer-substring start1 end1))
2050 (word2 (buffer-substring start2 end2)))
2051 (delete-region start2 end2)
2052 (goto-char start2)
2053 (insert word1)
2054 (goto-char (if (< start1 start2) start1
2055 (+ start1 (- (length word1) (length word2)))))
2056 (delete-char (length word1))
2057 (insert word2)))
2058\f
2059(defconst comment-column 32
2060 "*Column to indent right-margin comments to.
8a8fa723
JB
2061Setting this variable automatically makes it local to the current buffer.
2062Each mode establishes a different default value for this variable; you
b492f73b 2063can set the value for a particular mode using that mode's hook.")
2076c87c
JB
2064(make-variable-buffer-local 'comment-column)
2065
2066(defconst comment-start nil
534a0de5 2067 "*String to insert to start a new comment, or nil if no comment syntax.")
2076c87c
JB
2068
2069(defconst comment-start-skip nil
2070 "*Regexp to match the start of a comment plus everything up to its body.
2071If there are any \\(...\\) pairs, the comment delimiter text is held to begin
2072at the place matched by the close of the first pair.")
2073
2074(defconst comment-end ""
2075 "*String to insert to end a new comment.
2076Should be an empty string if comments are terminated by end-of-line.")
2077
ec9a76e3
JB
2078(defconst comment-indent-hook nil
2079 "Obsolete variable for function to compute desired indentation for a comment.
2080This function is called with no args with point at the beginning of
2081the comment's starting delimiter.")
2082
2083(defconst comment-indent-function
2076c87c
JB
2084 '(lambda () comment-column)
2085 "Function to compute desired indentation for a comment.
2086This function is called with no args with point at the beginning of
2087the comment's starting delimiter.")
2088
534a0de5
RS
2089(defconst block-comment-start nil
2090 "*String to insert to start a new comment on a line by itself.
2091If nil, use `comment-start' instead.
2092Note that the regular expression `comment-start-skip' should skip this string
2093as well as the `comment-start' string.")
2094
2095(defconst block-comment-end nil
2096 "*String to insert to end a new comment on a line by itself.
2097Should be an empty string if comments are terminated by end-of-line.
2098If nil, use `comment-end' instead.")
2099
2076c87c
JB
2100(defun indent-for-comment ()
2101 "Indent this line's comment to comment column, or insert an empty comment."
2102 (interactive "*")
534a0de5
RS
2103 (let* ((empty (save-excursion (beginning-of-line)
2104 (looking-at "[ \t]*$")))
2105 (starter (or (and empty block-comment-start) comment-start))
2106 (ender (or (and empty block-comment-end) comment-end)))
2107 (if (null starter)
2108 (error "No comment syntax defined")
2109 (let* ((eolpos (save-excursion (end-of-line) (point)))
2110 cpos indent begpos)
6389928d 2111 (beginning-of-line)
534a0de5
RS
2112 (if (re-search-forward comment-start-skip eolpos 'move)
2113 (progn (setq cpos (point-marker))
2114 ;; Find the start of the comment delimiter.
2115 ;; If there were paren-pairs in comment-start-skip,
2116 ;; position at the end of the first pair.
2117 (if (match-end 1)
2118 (goto-char (match-end 1))
2119 ;; If comment-start-skip matched a string with
2120 ;; internal whitespace (not final whitespace) then
2121 ;; the delimiter start at the end of that
2122 ;; whitespace. Otherwise, it starts at the
2123 ;; beginning of what was matched.
2124 (skip-syntax-backward " " (match-beginning 0))
2125 (skip-syntax-backward "^ " (match-beginning 0)))))
2126 (setq begpos (point))
2127 ;; Compute desired indent.
2128 (if (= (current-column)
2129 (setq indent (if comment-indent-hook
2130 (funcall comment-indent-hook)
2131 (funcall comment-indent-function))))
2132 (goto-char begpos)
2133 ;; If that's different from current, change it.
2134 (skip-chars-backward " \t")
2135 (delete-region (point) begpos)
2136 (indent-to indent))
2137 ;; An existing comment?
2138 (if cpos
2139 (progn (goto-char cpos)
2140 (set-marker cpos nil))
2141 ;; No, insert one.
2142 (insert starter)
2143 (save-excursion
2144 (insert ender)))))))
2076c87c
JB
2145
2146(defun set-comment-column (arg)
2147 "Set the comment column based on point.
2148With no arg, set the comment column to the current column.
2149With just minus as arg, kill any comment on this line.
2150With any other arg, set comment column to indentation of the previous comment
2151 and then align or create a comment on this line at that column."
2152 (interactive "P")
2153 (if (eq arg '-)
2154 (kill-comment nil)
2155 (if arg
2156 (progn
2157 (save-excursion
2158 (beginning-of-line)
2159 (re-search-backward comment-start-skip)
2160 (beginning-of-line)
2161 (re-search-forward comment-start-skip)
2162 (goto-char (match-beginning 0))
2163 (setq comment-column (current-column))
2164 (message "Comment column set to %d" comment-column))
2165 (indent-for-comment))
2166 (setq comment-column (current-column))
2167 (message "Comment column set to %d" comment-column))))
2168
2169(defun kill-comment (arg)
2170 "Kill the comment on this line, if any.
2171With argument, kill comments on that many lines starting with this one."
2172 ;; this function loses in a lot of situations. it incorrectly recognises
2173 ;; comment delimiters sometimes (ergo, inside a string), doesn't work
2174 ;; with multi-line comments, can kill extra whitespace if comment wasn't
2175 ;; through end-of-line, et cetera.
2176 (interactive "P")
2177 (or comment-start-skip (error "No comment syntax defined"))
2178 (let ((count (prefix-numeric-value arg)) endc)
2179 (while (> count 0)
2180 (save-excursion
2181 (end-of-line)
2182 (setq endc (point))
2183 (beginning-of-line)
2184 (and (string< "" comment-end)
2185 (setq endc
2186 (progn
2187 (re-search-forward (regexp-quote comment-end) endc 'move)
2188 (skip-chars-forward " \t")
2189 (point))))
2190 (beginning-of-line)
2191 (if (re-search-forward comment-start-skip endc t)
2192 (progn
2193 (goto-char (match-beginning 0))
2194 (skip-chars-backward " \t")
2195 (kill-region (point) endc)
2196 ;; to catch comments a line beginnings
2197 (indent-according-to-mode))))
2198 (if arg (forward-line 1))
2199 (setq count (1- count)))))
2200
2201(defun comment-region (beg end &optional arg)
f28039bb
RS
2202 "Comment or uncomment each line in the region.
2203With just C-u prefix arg, uncomment each line in region.
2204Numeric prefix arg ARG means use ARG comment characters.
2076c87c
JB
2205If ARG is negative, delete that many comment characters instead.
2206Comments are terminated on each line, even for syntax in which newline does
2207not end the comment. Blank lines do not get comments."
2208 ;; if someone wants it to only put a comment-start at the beginning and
2209 ;; comment-end at the end then typing it, C-x C-x, closing it, C-x C-x
2210 ;; is easy enough. No option is made here for other than commenting
2211 ;; every line.
f28039bb 2212 (interactive "r\nP")
2076c87c
JB
2213 (or comment-start (error "No comment syntax is defined"))
2214 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
2215 (save-excursion
2216 (save-restriction
f28039bb
RS
2217 (let ((cs comment-start) (ce comment-end)
2218 numarg)
2219 (if (consp arg) (setq numarg t)
2220 (setq numarg (prefix-numeric-value arg))
2221 ;; For positive arg > 1, replicate the comment delims now,
2222 ;; then insert the replicated strings just once.
2223 (while (> numarg 1)
2224 (setq cs (concat cs comment-start)
2225 ce (concat ce comment-end))
2226 (setq numarg (1- numarg))))
2227 ;; Loop over all lines from BEG to END.
2076c87c
JB
2228 (narrow-to-region beg end)
2229 (goto-char beg)
2230 (while (not (eobp))
f28039bb
RS
2231 (if (or (eq numarg t) (< numarg 0))
2232 (progn
2233 ;; Delete comment start from beginning of line.
2234 (if (eq numarg t)
2235 (while (looking-at (regexp-quote cs))
2236 (delete-char (length cs)))
2237 (let ((count numarg))
2238 (while (and (> 1 (setq count (1+ count)))
2239 (looking-at (regexp-quote cs)))
2240 (delete-char (length cs)))))
2241 ;; Delete comment end from end of line.
2242 (if (string= "" ce)
2243 nil
2244 (if (eq numarg t)
2245 (progn
2246 (end-of-line)
2247 ;; This is questionable if comment-end ends in
2248 ;; whitespace. That is pretty brain-damaged,
2249 ;; though.
2250 (skip-chars-backward " \t")
2251 (if (and (>= (- (point) (point-min)) (length ce))
2252 (save-excursion
2253 (backward-char (length ce))
2254 (looking-at (regexp-quote ce))))
2255 (delete-char (- (length ce)))))
ee095968
RS
2256 (let ((count numarg))
2257 (while (> 1 (setq count (1+ count)))
2258 (end-of-line)
2259 ;; this is questionable if comment-end ends in whitespace
2260 ;; that is pretty brain-damaged though
2261 (skip-chars-backward " \t")
2262 (save-excursion
2263 (backward-char (length ce))
2264 (if (looking-at (regexp-quote ce))
2265 (delete-char (length ce))))))))
6e88ed49 2266 (forward-line 1))
f28039bb 2267 ;; Insert at beginning and at end.
2076c87c
JB
2268 (if (looking-at "[ \t]*$") ()
2269 (insert cs)
2270 (if (string= "" ce) ()
2271 (end-of-line)
2272 (insert ce)))
2273 (search-forward "\n" nil 'move)))))))
2274\f
2275(defun backward-word (arg)
2276 "Move backward until encountering the end of a word.
2277With argument, do this that many times.
ff1fbe3e 2278In programs, it is faster to call `forward-word' with negative arg."
9e50756b 2279 (interactive "p")
2076c87c
JB
2280 (forward-word (- arg)))
2281
2282(defun mark-word (arg)
2283 "Set mark arg words away from point."
2284 (interactive "p")
2285 (push-mark
2286 (save-excursion
2287 (forward-word arg)
fd0f4056
RS
2288 (point))
2289 nil t))
2076c87c
JB
2290
2291(defun kill-word (arg)
2292 "Kill characters forward until encountering the end of a word.
2293With argument, do this that many times."
2294 (interactive "p")
e6291fe1 2295 (kill-region (point) (progn (forward-word arg) (point))))
2076c87c
JB
2296
2297(defun backward-kill-word (arg)
2298 "Kill characters backward until encountering the end of a word.
2299With argument, do this that many times."
2300 (interactive "p")
2301 (kill-word (- arg)))
d7c64071 2302
1e8c5ac4
RS
2303(defun current-word (&optional strict)
2304 "Return the word point is on (or a nearby word) as a string.
2305If optional arg STRICT is non-nil, return nil unless point is within
2306or adjacent to a word."
d7c64071
ER
2307 (save-excursion
2308 (let ((oldpoint (point)) (start (point)) (end (point)))
2309 (skip-syntax-backward "w_") (setq start (point))
2310 (goto-char oldpoint)
2311 (skip-syntax-forward "w_") (setq end (point))
2312 (if (and (eq start oldpoint) (eq end oldpoint))
1e8c5ac4
RS
2313 ;; Point is neither within nor adjacent to a word.
2314 (and (not strict)
2315 (progn
2316 ;; Look for preceding word in same line.
2317 (skip-syntax-backward "^w_"
2318 (save-excursion (beginning-of-line)
2319 (point)))
2320 (if (bolp)
2321 ;; No preceding word in same line.
2322 ;; Look for following word in same line.
2323 (progn
2324 (skip-syntax-forward "^w_"
2325 (save-excursion (end-of-line)
2326 (point)))
2327 (setq start (point))
2328 (skip-syntax-forward "w_")
2329 (setq end (point)))
2330 (setq end (point))
2331 (skip-syntax-backward "w_")
2332 (setq start (point)))
2333 (buffer-substring start end)))
2334 (buffer-substring start end)))))
2076c87c
JB
2335\f
2336(defconst fill-prefix nil
2337 "*String for filling to insert at front of new line, or nil for none.
2338Setting this variable automatically makes it local to the current buffer.")
2339(make-variable-buffer-local 'fill-prefix)
2340
2341(defconst auto-fill-inhibit-regexp nil
2342 "*Regexp to match lines which should not be auto-filled.")
2343
e2504204
KH
2344;; This function is the auto-fill-function of a buffer
2345;; when Auto-Fill mode is enabled.
2346;; It returns t if it really did any work.
2076c87c 2347(defun do-auto-fill ()
a0170800
RS
2348 (let (fc justify bol give-up
2349 (fill-prefix fill-prefix))
c18465c4 2350 (if (or (not (setq justify (current-justification)))
8f066a20
RS
2351 (null (setq fc (current-fill-column)))
2352 (and (eq justify 'left)
2353 (<= (current-column) fc))
eed5698b
RS
2354 (save-excursion (beginning-of-line)
2355 (setq bol (point))
2356 (and auto-fill-inhibit-regexp
2357 (looking-at auto-fill-inhibit-regexp))))
2358 nil ;; Auto-filling not required
3db1e3b5
BG
2359 (if (memq justify '(full center right))
2360 (save-excursion (unjustify-current-line)))
a0170800
RS
2361
2362 ;; Choose a fill-prefix automatically.
2363 (if (and adaptive-fill-mode
2364 (or (null fill-prefix) (string= fill-prefix "")))
e4b62d7c
RS
2365 (let ((prefix
2366 (fill-context-prefix
2367 (save-excursion (backward-paragraph 1) (point))
2368 (save-excursion (forward-paragraph 1) (point))
2369 ;; Don't accept a non-whitespace fill prefix
2370 ;; from the first line of a paragraph.
2371 "^[ \t]*$")))
2372 (and prefix (not (equal prefix ""))
2373 (setq fill-prefix prefix))))
a0170800 2374
eed5698b 2375 (while (and (not give-up) (> (current-column) fc))
e47d38f6
RS
2376 ;; Determine where to split the line.
2377 (let ((fill-point
2378 (let ((opoint (point))
2379 bounce
2380 (first t))
2381 (save-excursion
2382 (move-to-column (1+ fc))
2383 ;; Move back to a word boundary.
2384 (while (or first
2385 ;; If this is after period and a single space,
2386 ;; move back once more--we don't want to break
2387 ;; the line there and make it look like a
2388 ;; sentence end.
2389 (and (not (bobp))
2390 (not bounce)
2391 sentence-end-double-space
2392 (save-excursion (forward-char -1)
2393 (and (looking-at "\\. ")
2394 (not (looking-at "\\. "))))))
2395 (setq first nil)
2396 (skip-chars-backward "^ \t\n")
2397 ;; If we find nowhere on the line to break it,
2398 ;; break after one word. Set bounce to t
2399 ;; so we will not keep going in this while loop.
2400 (if (bolp)
2401 (progn
2402 (re-search-forward "[ \t]" opoint t)
2403 (setq bounce t)))
2404 (skip-chars-backward " \t"))
2405 ;; Let fill-point be set to the place where we end up.
2406 (point)))))
2407 ;; If that place is not the beginning of the line,
2408 ;; break the line there.
2409 (if (save-excursion
2410 (goto-char fill-point)
2411 (not (bolp)))
2412 (let ((prev-column (current-column)))
2413 ;; If point is at the fill-point, do not `save-excursion'.
2414 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
2415 ;; point will end up before it rather than after it.
2416 (if (save-excursion
2417 (skip-chars-backward " \t")
2418 (= (point) fill-point))
2419 (indent-new-comment-line t)
2420 (save-excursion
2421 (goto-char fill-point)
2422 (indent-new-comment-line t)))
2423 ;; Now do justification, if required
2424 (if (not (eq justify 'left))
2425 (save-excursion
2426 (end-of-line 0)
2427 (justify-current-line justify nil t)))
2428 ;; If making the new line didn't reduce the hpos of
2429 ;; the end of the line, then give up now;
2430 ;; trying again will not help.
2431 (if (>= (current-column) prev-column)
2432 (setq give-up t)))
2433 ;; No place to break => stop trying.
2434 (setq give-up t))))
eed5698b 2435 ;; justify last line
e2504204
KH
2436 (justify-current-line justify t t)
2437 t)))
2076c87c 2438
d7465b15
RS
2439(defun auto-fill-mode (&optional arg)
2440 "Toggle auto-fill mode.
2441With arg, turn Auto-Fill mode on if and only if arg is positive.
eed5698b 2442In Auto-Fill mode, inserting a space at a column beyond `current-fill-column'
d7465b15
RS
2443automatically breaks the line at a previous space."
2444 (interactive "P")
2445 (prog1 (setq auto-fill-function
2446 (if (if (null arg)
2447 (not auto-fill-function)
2448 (> (prefix-numeric-value arg) 0))
2449 'do-auto-fill
2450 nil))
7911ecc8 2451 (force-mode-line-update)))
d7465b15
RS
2452
2453;; This holds a document string used to document auto-fill-mode.
2454(defun auto-fill-function ()
2455 "Automatically break line at a previous space, in insertion of text."
2456 nil)
2457
2458(defun turn-on-auto-fill ()
2459 "Unconditionally turn on Auto Fill mode."
2460 (auto-fill-mode 1))
2461
2462(defun set-fill-column (arg)
4cc0ea11
RS
2463 "Set `fill-column' to specified argument.
2464Just \\[universal-argument] as argument means to use the current column."
d7465b15 2465 (interactive "P")
4cc0ea11
RS
2466 (cond ((integerp arg)
2467 (setq fill-column arg))
2468 ((consp arg)
2469 (setq fill-column (current-column)))
2470 ;; Disallow missing argument; it's probably a typo for C-x C-f.
2471 (t
2472 (error "set-fill-column requires an explicit argument")))
d7465b15
RS
2473 (message "fill-column set to %d" fill-column))
2474\f
2076c87c
JB
2475(defconst comment-multi-line nil
2476 "*Non-nil means \\[indent-new-comment-line] should continue same comment
c88ab9ce
ER
2477on new line, with no new terminator or starter.
2478This is obsolete because you might as well use \\[newline-and-indent].")
2076c87c 2479
28191e20 2480(defun indent-new-comment-line (&optional soft)
d7465b15
RS
2481 "Break line at point and indent, continuing comment if within one.
2482This indents the body of the continued comment
2483under the previous comment line.
c88ab9ce
ER
2484
2485This command is intended for styles where you write a comment per line,
2486starting a new comment (and terminating it if necessary) on each line.
28191e20
RS
2487If you want to continue one comment across several lines, use \\[newline-and-indent].
2488
3a0c4755
RS
2489If a fill column is specified, it overrides the use of the comment column
2490or comment indentation.
2491
28191e20
RS
2492The inserted newline is marked hard if `use-hard-newlines' is true,
2493unless optional argument SOFT is non-nil."
2494 (interactive)
2076c87c
JB
2495 (let (comcol comstart)
2496 (skip-chars-backward " \t")
2497 (delete-region (point)
2498 (progn (skip-chars-forward " \t")
2499 (point)))
eed5698b 2500 (if soft (insert-and-inherit ?\n) (newline 1))
3a0c4755
RS
2501 (if fill-prefix
2502 (progn
2503 (indent-to-left-margin)
2504 (insert-and-inherit fill-prefix))
2505 (if (not comment-multi-line)
2076c87c 2506 (save-excursion
3a0c4755
RS
2507 (if (and comment-start-skip
2508 (let ((opoint (point)))
2509 (forward-line -1)
2510 (re-search-forward comment-start-skip opoint t)))
2511 ;; The old line is a comment.
2512 ;; Set WIN to the pos of the comment-start.
2513 ;; But if the comment is empty, look at preceding lines
2514 ;; to find one that has a nonempty comment.
2515
2516 ;; If comment-start-skip contains a \(...\) pair,
2517 ;; the real comment delimiter starts at the end of that pair.
2518 (let ((win (or (match-end 1) (match-beginning 0))))
2519 (while (and (eolp) (not (bobp))
2520 (let (opoint)
2521 (beginning-of-line)
2522 (setq opoint (point))
2523 (forward-line -1)
2524 (re-search-forward comment-start-skip opoint t)))
2525 (setq win (or (match-end 1) (match-beginning 0))))
2526 ;; Indent this line like what we found.
2527 (goto-char win)
2528 (setq comcol (current-column))
2529 (setq comstart
2530 (buffer-substring (point) (match-end 0)))))))
2531 (if comcol
2532 (let ((comment-column comcol)
2533 (comment-start comstart)
2534 (comment-end comment-end))
2535 (and comment-end (not (equal comment-end ""))
2536 ; (if (not comment-multi-line)
2537 (progn
2538 (forward-char -1)
2539 (insert comment-end)
2540 (forward-char 1))
2541 ; (setq comment-column (+ comment-column (length comment-start))
2542 ; comment-start "")
2543 ; )
2544 )
2545 (if (not (eolp))
2546 (setq comment-end ""))
2547 (insert-and-inherit ?\n)
2548 (forward-char -1)
2549 (indent-for-comment)
2550 (save-excursion
2551 ;; Make sure we delete the newline inserted above.
2552 (end-of-line)
2553 (delete-char 1)))
2554 (indent-according-to-mode)))))
2076c87c
JB
2555\f
2556(defun set-selective-display (arg)
ff1fbe3e
RS
2557 "Set `selective-display' to ARG; clear it if no arg.
2558When the value of `selective-display' is a number > 0,
2559lines whose indentation is >= that value are not displayed.
2560The variable `selective-display' has a separate value for each buffer."
2076c87c
JB
2561 (interactive "P")
2562 (if (eq selective-display t)
2563 (error "selective-display already in use for marked lines"))
c88ab9ce
ER
2564 (let ((current-vpos
2565 (save-restriction
2566 (narrow-to-region (point-min) (point))
2567 (goto-char (window-start))
2568 (vertical-motion (window-height)))))
2569 (setq selective-display
2570 (and arg (prefix-numeric-value arg)))
2571 (recenter current-vpos))
2076c87c
JB
2572 (set-window-start (selected-window) (window-start (selected-window)))
2573 (princ "selective-display set to " t)
2574 (prin1 selective-display t)
2575 (princ "." t))
2576
b6a22db0
JB
2577(defconst overwrite-mode-textual " Ovwrt"
2578 "The string displayed in the mode line when in overwrite mode.")
2579(defconst overwrite-mode-binary " Bin Ovwrt"
2580 "The string displayed in the mode line when in binary overwrite mode.")
2581
2076c87c
JB
2582(defun overwrite-mode (arg)
2583 "Toggle overwrite mode.
2584With arg, turn overwrite mode on iff arg is positive.
2585In overwrite mode, printing characters typed in replace existing text
b6a22db0
JB
2586on a one-for-one basis, rather than pushing it to the right. At the
2587end of a line, such characters extend the line. Before a tab,
2588such characters insert until the tab is filled in.
2589\\[quoted-insert] still inserts characters in overwrite mode; this
2590is supposed to make it easier to insert characters when necessary."
2591 (interactive "P")
2592 (setq overwrite-mode
2593 (if (if (null arg) (not overwrite-mode)
2594 (> (prefix-numeric-value arg) 0))
2595 'overwrite-mode-textual))
2596 (force-mode-line-update))
2597
2598(defun binary-overwrite-mode (arg)
2599 "Toggle binary overwrite mode.
2600With arg, turn binary overwrite mode on iff arg is positive.
2601In binary overwrite mode, printing characters typed in replace
2602existing text. Newlines are not treated specially, so typing at the
2603end of a line joins the line to the next, with the typed character
2604between them. Typing before a tab character simply replaces the tab
2605with the character typed.
2606\\[quoted-insert] replaces the text at the cursor, just as ordinary
2607typing characters do.
2608
2609Note that binary overwrite mode is not its own minor mode; it is a
2610specialization of overwrite-mode, entered by setting the
2611`overwrite-mode' variable to `overwrite-mode-binary'."
2076c87c
JB
2612 (interactive "P")
2613 (setq overwrite-mode
b6a22db0 2614 (if (if (null arg)
a61099dd 2615 (not (eq overwrite-mode 'overwrite-mode-binary))
b6a22db0
JB
2616 (> (prefix-numeric-value arg) 0))
2617 'overwrite-mode-binary))
2618 (force-mode-line-update))
2076c87c 2619\f
81e98f1a 2620(defvar line-number-mode t
a61099dd
RS
2621 "*Non-nil means display line number in mode line.")
2622
2623(defun line-number-mode (arg)
2624 "Toggle Line Number mode.
2625With arg, turn Line Number mode on iff arg is positive.
2626When Line Number mode is enabled, the line number appears
2627in the mode line."
2628 (interactive "P")
2629 (setq line-number-mode
2630 (if (null arg) (not line-number-mode)
2631 (> (prefix-numeric-value arg) 0)))
2632 (force-mode-line-update))
2633
71601101 2634(defvar column-number-mode nil
bcad4985
KH
2635 "*Non-nil means display column number in mode line.")
2636
2637(defun column-number-mode (arg)
2638 "Toggle Column Number mode.
2639With arg, turn Column Number mode on iff arg is positive.
2640When Column Number mode is enabled, the column number appears
2641in the mode line."
2642 (interactive "P")
2643 (setq column-number-mode
2644 (if (null arg) (not column-number-mode)
2645 (> (prefix-numeric-value arg) 0)))
2646 (force-mode-line-update))
2647
2076c87c
JB
2648(defvar blink-matching-paren t
2649 "*Non-nil means show matching open-paren when close-paren is inserted.")
2650
29fc44dd
KH
2651(defvar blink-matching-paren-on-screen t
2652 "*Non-nil means show matching open-paren when it is on screen.
2653nil means don't show it (but the open-paren can still be shown
2654when it is off screen.")
2655
37315725
RS
2656(defconst blink-matching-paren-distance 12000
2657 "*If non-nil, is maximum distance to search for matching open-paren.")
2076c87c 2658
72dddf8b
RS
2659(defconst blink-matching-delay 1
2660 "*The number of seconds that `blink-matching-open' will delay at a match.")
2661
903b7f65
RS
2662(defconst blink-matching-paren-dont-ignore-comments nil
2663 "*Non-nil means `blink-matching-paren' should not ignore comments.")
2664
2076c87c
JB
2665(defun blink-matching-open ()
2666 "Move cursor momentarily to the beginning of the sexp before point."
2667 (interactive)
2668 (and (> (point) (1+ (point-min)))
2076c87c 2669 blink-matching-paren
7e1ddd45
RS
2670 ;; Verify an even number of quoting characters precede the close.
2671 (= 1 (logand 1 (- (point)
2672 (save-excursion
2673 (forward-char -1)
2674 (skip-syntax-backward "/\\")
2675 (point)))))
2076c87c
JB
2676 (let* ((oldpos (point))
2677 (blinkpos)
2678 (mismatch))
2679 (save-excursion
2680 (save-restriction
2681 (if blink-matching-paren-distance
2682 (narrow-to-region (max (point-min)
2683 (- (point) blink-matching-paren-distance))
2684 oldpos))
2685 (condition-case ()
903b7f65
RS
2686 (let ((parse-sexp-ignore-comments
2687 (and parse-sexp-ignore-comments
2688 (not blink-matching-paren-dont-ignore-comments))))
2689 (setq blinkpos (scan-sexps oldpos -1)))
2076c87c 2690 (error nil)))
903b7f65
RS
2691 (and blinkpos
2692 (/= (char-syntax (char-after blinkpos))
2693 ?\$)
2076c87c 2694 (setq mismatch
903b7f65
RS
2695 (or (null (matching-paren (char-after blinkpos)))
2696 (/= (char-after (1- oldpos))
2697 (matching-paren (char-after blinkpos))))))
2076c87c
JB
2698 (if mismatch (setq blinkpos nil))
2699 (if blinkpos
2700 (progn
2701 (goto-char blinkpos)
2702 (if (pos-visible-in-window-p)
29fc44dd
KH
2703 (and blink-matching-paren-on-screen
2704 (sit-for blink-matching-delay))
2076c87c
JB
2705 (goto-char blinkpos)
2706 (message
2707 "Matches %s"
e9f1d66d 2708 ;; Show what precedes the open in its line, if anything.
2076c87c
JB
2709 (if (save-excursion
2710 (skip-chars-backward " \t")
2711 (not (bolp)))
2712 (buffer-substring (progn (beginning-of-line) (point))
2713 (1+ blinkpos))
e9f1d66d
RS
2714 ;; Show what follows the open in its line, if anything.
2715 (if (save-excursion
2716 (forward-char 1)
2717 (skip-chars-forward " \t")
2718 (not (eolp)))
2719 (buffer-substring blinkpos
2720 (progn (end-of-line) (point)))
267935b9
RS
2721 ;; Otherwise show the previous nonblank line,
2722 ;; if there is one.
2723 (if (save-excursion
2724 (skip-chars-backward "\n \t")
2725 (not (bobp)))
2726 (concat
2727 (buffer-substring (progn
2728 (skip-chars-backward "\n \t")
2729 (beginning-of-line)
2730 (point))
2731 (progn (end-of-line)
2732 (skip-chars-backward " \t")
2733 (point)))
2734 ;; Replace the newline and other whitespace with `...'.
2735 "..."
2736 (buffer-substring blinkpos (1+ blinkpos)))
2737 ;; There is nothing to show except the char itself.
2738 (buffer-substring blinkpos (1+ blinkpos))))))))
2076c87c
JB
2739 (cond (mismatch
2740 (message "Mismatched parentheses"))
2741 ((not blink-matching-paren-distance)
2742 (message "Unmatched parenthesis"))))))))
2743
2744;Turned off because it makes dbx bomb out.
2745(setq blink-paren-function 'blink-matching-open)
2746
9a1277dd
RS
2747;; This executes C-g typed while Emacs is waiting for a command.
2748;; Quitting out of a program does not go through here;
2749;; that happens in the QUIT macro at the C code level.
2076c87c 2750(defun keyboard-quit ()
af39530e
RS
2751 "Signal a quit condition.
2752During execution of Lisp code, this character causes a quit directly.
2753At top-level, as an editor command, this simply beeps."
2076c87c 2754 (interactive)
19d35374 2755 (deactivate-mark)
2076c87c
JB
2756 (signal 'quit nil))
2757
2758(define-key global-map "\C-g" 'keyboard-quit)
c66587fe 2759
1c6c6fde
RS
2760(defvar buffer-quit-function nil
2761 "Function to call to \"quit\" the current buffer, or nil if none.
2762\\[keyboard-escape-quit] calls this function when its more local actions
2763\(such as cancelling a prefix argument, minibuffer or region) do not apply.")
2764
c66587fe
RS
2765(defun keyboard-escape-quit ()
2766 "Exit the current \"mode\" (in a generalized sense of the word).
2767This command can exit an interactive command such as `query-replace',
2768can clear out a prefix argument or a region,
2769can get out of the minibuffer or other recursive edit,
1c6c6fde
RS
2770cancel the use of the current buffer (for special-purpose buffers),
2771or go back to just one window (by deleting all but the selected window)."
c66587fe
RS
2772 (interactive)
2773 (cond ((eq last-command 'mode-exited) nil)
2774 ((> (minibuffer-depth) 0)
2775 (abort-recursive-edit))
2776 (current-prefix-arg
2777 nil)
2778 ((and transient-mark-mode
2779 mark-active)
2780 (deactivate-mark))
1c6c6fde
RS
2781 (buffer-quit-function
2782 (funcall buffer-quit-function))
c66587fe
RS
2783 ((not (one-window-p t))
2784 (delete-other-windows))))
2785
1c6c6fde 2786(define-key global-map "\e\e\e" 'keyboard-escape-quit)
2076c87c
JB
2787\f
2788(defun set-variable (var val)
2789 "Set VARIABLE to VALUE. VALUE is a Lisp object.
2790When using this interactively, supply a Lisp expression for VALUE.
3a801d0c
ER
2791If you want VALUE to be a string, you must surround it with doublequotes.
2792
2793If VARIABLE has a `variable-interactive' property, that is used as if
2794it were the arg to `interactive' (which see) to interactively read the value."
2076c87c
JB
2795 (interactive
2796 (let* ((var (read-variable "Set variable: "))
2797 (minibuffer-help-form
2798 '(funcall myhelp))
2799 (myhelp
2800 (function
2801 (lambda ()
2802 (with-output-to-temp-buffer "*Help*"
2803 (prin1 var)
2804 (princ "\nDocumentation:\n")
2805 (princ (substring (documentation-property var 'variable-documentation)
2806 1))
2807 (if (boundp var)
2808 (let ((print-length 20))
2809 (princ "\n\nCurrent value: ")
2810 (prin1 (symbol-value var))))
e6bcd155
KH
2811 (save-excursion
2812 (set-buffer standard-output)
2813 (help-mode))
2076c87c
JB
2814 nil)))))
2815 (list var
3a801d0c
ER
2816 (let ((prop (get var 'variable-interactive)))
2817 (if prop
2818 ;; Use VAR's `variable-interactive' property
2819 ;; as an interactive spec for prompting.
2820 (call-interactively (list 'lambda '(arg)
2821 (list 'interactive prop)
2822 'arg))
2823 (eval-minibuffer (format "Set %s to value: " var)))))))
2076c87c 2824 (set var val))
e8a700bf
RS
2825\f
2826;; Define the major mode for lists of completions.
2827
98b45886
RS
2828(defvar completion-list-mode-map nil
2829 "Local map for completion list buffers.")
ac29eb79 2830(or completion-list-mode-map
e8a700bf
RS
2831 (let ((map (make-sparse-keymap)))
2832 (define-key map [mouse-2] 'mouse-choose-completion)
eaf76065 2833 (define-key map [down-mouse-2] nil)
80298193 2834 (define-key map "\C-m" 'choose-completion)
1c6c6fde 2835 (define-key map "\e\e\e" 'delete-completion-window)
dde69dbe
RS
2836 (define-key map [left] 'previous-completion)
2837 (define-key map [right] 'next-completion)
ac29eb79 2838 (setq completion-list-mode-map map)))
e8a700bf
RS
2839
2840;; Completion mode is suitable only for specially formatted data.
ac29eb79 2841(put 'completion-list-mode 'mode-class 'special)
e8a700bf 2842
98b45886
RS
2843(defvar completion-reference-buffer nil
2844 "Record the buffer that was current when the completion list was requested.
2845This is a local variable in the completion list buffer.
ec39964e 2846Initial value is nil to avoid some compiler warnings.")
3819736b 2847
98b45886
RS
2848(defvar completion-base-size nil
2849 "Number of chars at beginning of minibuffer not involved in completion.
2850This is a local variable in the completion list buffer
2851but it talks about the buffer in `completion-reference-buffer'.
2852If this is nil, it means to compare text to determine which part
2853of the tail end of the buffer's text is involved in completion.")
f6b293e3 2854
1c6c6fde
RS
2855(defun delete-completion-window ()
2856 "Delete the completion list window.
2857Go to the window from which completion was requested."
2858 (interactive)
2859 (let ((buf completion-reference-buffer))
2860 (delete-window (selected-window))
2861 (if (get-buffer-window buf)
2862 (select-window (get-buffer-window buf)))))
2863
dde69dbe
RS
2864(defun previous-completion (n)
2865 "Move to the previous item in the completion list."
2866 (interactive "p")
2867 (next-completion (- n)))
2868
2869(defun next-completion (n)
2870 "Move to the next item in the completion list.
1f238ac2 2871With prefix argument N, move N items (negative N means move backward)."
dde69dbe
RS
2872 (interactive "p")
2873 (while (and (> n 0) (not (eobp)))
b61a81c2
RS
2874 (let ((prop (get-text-property (point) 'mouse-face))
2875 (end (point-max)))
dde69dbe
RS
2876 ;; If in a completion, move to the end of it.
2877 (if prop
b61a81c2 2878 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
dde69dbe 2879 ;; Move to start of next one.
b61a81c2 2880 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
dde69dbe
RS
2881 (setq n (1- n)))
2882 (while (and (< n 0) (not (bobp)))
b61a81c2
RS
2883 (let ((prop (get-text-property (1- (point)) 'mouse-face))
2884 (end (point-min)))
dde69dbe
RS
2885 ;; If in a completion, move to the start of it.
2886 (if prop
b61a81c2
RS
2887 (goto-char (previous-single-property-change
2888 (point) 'mouse-face nil end)))
dde69dbe 2889 ;; Move to end of the previous completion.
b61a81c2 2890 (goto-char (previous-single-property-change (point) 'mouse-face nil end))
dde69dbe 2891 ;; Move to the start of that one.
b61a81c2 2892 (goto-char (previous-single-property-change (point) 'mouse-face nil end)))
dde69dbe
RS
2893 (setq n (1+ n))))
2894
80298193
RS
2895(defun choose-completion ()
2896 "Choose the completion that point is in or next to."
2897 (interactive)
f6b293e3
RS
2898 (let (beg end completion (buffer completion-reference-buffer)
2899 (base-size completion-base-size))
6096f362
RS
2900 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
2901 (setq end (point) beg (1+ (point))))
2902 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
3f299281 2903 (setq end (1- (point)) beg (point)))
6096f362
RS
2904 (if (null beg)
2905 (error "No completion here"))
2906 (setq beg (previous-single-property-change beg 'mouse-face))
88dd3c24 2907 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
ab63960f
RS
2908 (setq completion (buffer-substring beg end))
2909 (let ((owindow (selected-window)))
2910 (if (and (one-window-p t 'selected-frame)
2911 (window-dedicated-p (selected-window)))
2912 ;; This is a special buffer's frame
2913 (iconify-frame (selected-frame))
2914 (or (window-dedicated-p (selected-window))
2915 (bury-buffer)))
2916 (select-window owindow))
f6b293e3 2917 (choose-completion-string completion buffer base-size)))
80298193
RS
2918
2919;; Delete the longest partial match for STRING
2920;; that can be found before POINT.
2921(defun choose-completion-delete-max-match (string)
2922 (let ((opoint (point))
2923 (len (min (length string)
2924 (- (point) (point-min)))))
2925 (goto-char (- (point) (length string)))
61bbf6fe
RS
2926 (if completion-ignore-case
2927 (setq string (downcase string)))
80298193
RS
2928 (while (and (> len 0)
2929 (let ((tail (buffer-substring (point)
2930 (+ (point) len))))
61bbf6fe
RS
2931 (if completion-ignore-case
2932 (setq tail (downcase tail)))
80298193
RS
2933 (not (string= tail (substring string 0 len)))))
2934 (setq len (1- len))
2935 (forward-char 1))
2936 (delete-char len)))
2937
98b45886
RS
2938;; Switch to BUFFER and insert the completion choice CHOICE.
2939;; BASE-SIZE, if non-nil, says how many characters of BUFFER's text
2940;; to keep. If it is nil, use choose-completion-delete-max-match instead.
74d0290b
RS
2941
2942;; If BUFFER is the minibuffer, exit the minibuffer
2943;; unless it is reading a file name and CHOICE is a directory.
f6b293e3 2944(defun choose-completion-string (choice &optional buffer base-size)
80298193 2945 (let ((buffer (or buffer completion-reference-buffer)))
cf52ad58
RS
2946 ;; If BUFFER is a minibuffer, barf unless it's the currently
2947 ;; active minibuffer.
2948 (if (and (string-match "\\` \\*Minibuf-[0-9]+\\*\\'" (buffer-name buffer))
45486731
RS
2949 (or (not (active-minibuffer-window))
2950 (not (equal buffer
2951 (window-buffer (active-minibuffer-window))))))
cf52ad58
RS
2952 (error "Minibuffer is not active for completion")
2953 ;; Insert the completion into the buffer where completion was requested.
2954 (set-buffer buffer)
f6b293e3
RS
2955 (if base-size
2956 (delete-region (+ base-size (point-min)) (point))
2957 (choose-completion-delete-max-match choice))
cf52ad58 2958 (insert choice)
63240af1
RS
2959 (remove-text-properties (- (point) (length choice)) (point)
2960 '(mouse-face nil))
cf52ad58
RS
2961 ;; Update point in the window that BUFFER is showing in.
2962 (let ((window (get-buffer-window buffer t)))
2963 (set-window-point window (point)))
2964 ;; If completing for the minibuffer, exit it with this choice.
2965 (and (equal buffer (window-buffer (minibuffer-window)))
8881ad9a 2966 minibuffer-completion-table
74d0290b
RS
2967 ;; If this is reading a file name, and the file name chosen
2968 ;; is a directory, don't exit the minibuffer.
2969 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
2970 (file-directory-p (buffer-string)))
2971 (select-window (active-minibuffer-window))
2972 (exit-minibuffer))))))
80298193 2973
ac29eb79 2974(defun completion-list-mode ()
e8a700bf 2975 "Major mode for buffers showing lists of possible completions.
80298193
RS
2976Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
2977 to select the completion near point.
2978Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
2979 with the mouse."
e8a700bf
RS
2980 (interactive)
2981 (kill-all-local-variables)
ac29eb79
RS
2982 (use-local-map completion-list-mode-map)
2983 (setq mode-name "Completion List")
2984 (setq major-mode 'completion-list-mode)
f6b293e3
RS
2985 (make-local-variable 'completion-base-size)
2986 (setq completion-base-size nil)
ac29eb79 2987 (run-hooks 'completion-list-mode-hook))
e8a700bf 2988
98b45886
RS
2989(defvar completion-fixup-function nil
2990 "A function to customize how completions are identified in completion lists.
2991`completion-setup-function' calls this function with no arguments
2992each time it has found what it thinks is one completion.
2993Point is at the end of the completion in the completion list buffer.
2994If this function moves point, it can alter the end of that completion.")
2995
2996;; This function goes in completion-setup-hook, so that it is called
2997;; after the text of the completion list buffer is written.
6096f362 2998
e8a700bf
RS
2999(defun completion-setup-function ()
3000 (save-excursion
98b45886 3001 (let ((mainbuf (current-buffer)))
3819736b
RS
3002 (set-buffer standard-output)
3003 (completion-list-mode)
3004 (make-local-variable 'completion-reference-buffer)
3005 (setq completion-reference-buffer mainbuf)
98b45886
RS
3006;;; The value 0 is right in most cases, but not for file name completion.
3007;;; so this has to be turned off.
3008;;; (setq completion-base-size 0)
3819736b
RS
3009 (goto-char (point-min))
3010 (if window-system
3011 (insert (substitute-command-keys
80298193
RS
3012 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
3013 (insert (substitute-command-keys
3014 "In this buffer, type \\[choose-completion] to \
c26bb96e
KH
3015select the completion near point.\n\n"))
3016 (forward-line 1)
6096f362
RS
3017 (while (re-search-forward "[^ \t\n]+\\( [^ \t\n]+\\)*" nil t)
3018 (let ((beg (match-beginning 0))
3019 (end (point)))
3020 (if completion-fixup-function
3021 (funcall completion-fixup-function))
3022 (put-text-property beg (point) 'mouse-face 'highlight)
3023 (goto-char end))))))
c88ab9ce 3024
e8a700bf 3025(add-hook 'completion-setup-hook 'completion-setup-function)
dde69dbe
RS
3026
3027(define-key minibuffer-local-completion-map [prior]
3028 'switch-to-completions)
3029(define-key minibuffer-local-must-match-map [prior]
3030 'switch-to-completions)
3031(define-key minibuffer-local-completion-map "\M-v"
3032 'switch-to-completions)
3033(define-key minibuffer-local-must-match-map "\M-v"
3034 'switch-to-completions)
3035
3036(defun switch-to-completions ()
3037 "Select the completion list window."
3038 (interactive)
9595fbdb
RS
3039 ;; Make sure we have a completions window.
3040 (or (get-buffer-window "*Completions*")
3041 (minibuffer-completion-help))
dde69dbe
RS
3042 (select-window (get-buffer-window "*Completions*"))
3043 (goto-char (point-min))
3044 (search-forward "\n\n")
3045 (forward-line 1))
a3d1480b 3046\f
82072f33
RS
3047;; Support keyboard commands to turn on various modifiers.
3048
3049;; These functions -- which are not commands -- each add one modifier
3050;; to the following event.
3051
3052(defun event-apply-alt-modifier (ignore-prompt)
3053 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
3054(defun event-apply-super-modifier (ignore-prompt)
3055 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
3056(defun event-apply-hyper-modifier (ignore-prompt)
3057 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
3058(defun event-apply-shift-modifier (ignore-prompt)
3059 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
3060(defun event-apply-control-modifier (ignore-prompt)
3061 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
3062(defun event-apply-meta-modifier (ignore-prompt)
3063 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
3064
3065(defun event-apply-modifier (event symbol lshiftby prefix)
3066 "Apply a modifier flag to event EVENT.
3067SYMBOL is the name of this modifier, as a symbol.
3068LSHIFTBY is the numeric value of this modifier, in keyboard events.
3069PREFIX is the string that represents this modifier in an event type symbol."
3070 (if (numberp event)
3071 (cond ((eq symbol 'control)
90bebcb0
KH
3072 (if (and (<= (downcase event) ?z)
3073 (>= (downcase event) ?a))
82072f33 3074 (- (downcase event) ?a -1)
90bebcb0
KH
3075 (if (and (<= (downcase event) ?Z)
3076 (>= (downcase event) ?A))
82072f33
RS
3077 (- (downcase event) ?A -1)
3078 (logior (lsh 1 lshiftby) event))))
3079 ((eq symbol 'shift)
3080 (if (and (<= (downcase event) ?z)
3081 (>= (downcase event) ?a))
3082 (upcase event)
3083 (logior (lsh 1 lshiftby) event)))
3084 (t
3085 (logior (lsh 1 lshiftby) event)))
3086 (if (memq symbol (event-modifiers event))
3087 event
3088 (let ((event-type (if (symbolp event) event (car event))))
3089 (setq event-type (intern (concat prefix (symbol-name event-type))))
3090 (if (symbolp event)
3091 event-type
3092 (cons event-type (cdr event)))))))
3093
e5fff738
KH
3094(define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
3095(define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
3096(define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
3097(define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
3098(define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
3099(define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
82072f33 3100\f
a3d1480b
JB
3101;;;; Keypad support.
3102
3103;;; Make the keypad keys act like ordinary typing keys. If people add
3104;;; bindings for the function key symbols, then those bindings will
3105;;; override these, so this shouldn't interfere with any existing
3106;;; bindings.
3107
0d173134 3108;; Also tell read-char how to handle these keys.
a3d1480b
JB
3109(mapcar
3110 (lambda (keypad-normal)
3111 (let ((keypad (nth 0 keypad-normal))
3112 (normal (nth 1 keypad-normal)))
0d173134 3113 (put keypad 'ascii-character normal)
a3d1480b
JB
3114 (define-key function-key-map (vector keypad) (vector normal))))
3115 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
3116 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
3117 (kp-space ?\ )
3118 (kp-tab ?\t)
3119 (kp-enter ?\r)
3120 (kp-multiply ?*)
3121 (kp-add ?+)
3122 (kp-separator ?,)
3123 (kp-subtract ?-)
3124 (kp-decimal ?.)
3125 (kp-divide ?/)
3126 (kp-equal ?=)))
3127
c88ab9ce 3128;;; simple.el ends here