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