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