]> code.delx.au - gnu-emacs/blob - lisp/simple.el
Revision: miles@gnu.org--gnu-2004/emacs--unicode--0--patch-29
[gnu-emacs] / lisp / simple.el
1 ;;; simple.el --- basic editing commands for Emacs
2
3 ;; Copyright (C) 1985, 86, 87, 93, 94, 95, 96, 97, 98, 99,
4 ;; 2000, 01, 02, 03, 04
5 ;; Free Software Foundation, Inc.
6
7 ;; Maintainer: FSF
8 ;; Keywords: internal
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; A grab-bag of basic Emacs commands not specifically related to some
30 ;; major mode or to file-handling.
31
32 ;;; Code:
33
34 (eval-when-compile
35 (autoload 'widget-convert "wid-edit")
36 (autoload 'shell-mode "shell"))
37
38
39 (defgroup killing nil
40 "Killing and yanking commands."
41 :group 'editing)
42
43 (defgroup paren-matching nil
44 "Highlight (un)matching of parens and expressions."
45 :group 'matching)
46
47 (define-key global-map [?\C-x right] 'next-buffer)
48 (define-key global-map [?\C-x left] 'prev-buffer)
49 (defun next-buffer ()
50 "Switch to the next buffer in cyclic order."
51 (interactive)
52 (let ((buffer (current-buffer)))
53 (switch-to-buffer (other-buffer buffer))
54 (bury-buffer buffer)))
55
56 (defun prev-buffer ()
57 "Switch to the previous buffer in cyclic order."
58 (interactive)
59 (let ((list (nreverse (buffer-list)))
60 found)
61 (while (and (not found) list)
62 (let ((buffer (car list)))
63 (if (and (not (get-buffer-window buffer))
64 (not (string-match "\\` " (buffer-name buffer))))
65 (setq found buffer)))
66 (setq list (cdr list)))
67 (switch-to-buffer found)))
68
69 ;;; next-error support framework
70 (defvar next-error-last-buffer nil
71 "The most recent next-error buffer.
72 A buffer becomes most recent when its compilation, grep, or
73 similar mode is started, or when it is used with \\[next-error]
74 or \\[compile-goto-error].")
75
76 (defvar next-error-function nil
77 "Function to use to find the next error in the current buffer.
78 The function is called with 2 parameters:
79 ARG is an integer specifying by how many errors to move.
80 RESET is a boolean which, if non-nil, says to go back to the beginning
81 of the errors before moving.
82 Major modes providing compile-like functionality should set this variable
83 to indicate to `next-error' that this is a candidate buffer and how
84 to navigate in it.")
85
86 (make-variable-buffer-local 'next-error-function)
87
88 (defsubst next-error-buffer-p (buffer &optional extra-test)
89 "Test if BUFFER is a next-error capable buffer."
90 (with-current-buffer buffer
91 (or (and extra-test (funcall extra-test))
92 next-error-function)))
93
94 ;; Return a next-error capable buffer according to the following rules:
95 ;; 1. If the current buffer is a next-error capable buffer, return it.
96 ;; 2. If one window on the selected frame displays such buffer, return it.
97 ;; 3. If next-error-last-buffer is set to a live buffer, use that.
98 ;; 4. Otherwise, look for a next-error capable buffer in a buffer list.
99 ;; 5. Signal an error if there are none.
100 (defun next-error-find-buffer (&optional other-buffer extra-test)
101 (if (and (not other-buffer)
102 (next-error-buffer-p (current-buffer) extra-test))
103 ;; The current buffer is a next-error capable buffer.
104 (current-buffer)
105 (or
106 (let ((window-buffers
107 (delete-dups
108 (delq nil
109 (mapcar (lambda (w)
110 (and (next-error-buffer-p (window-buffer w) extra-test)
111 (window-buffer w)))
112 (window-list))))))
113 (if other-buffer
114 (setq window-buffers (delq (current-buffer) window-buffers)))
115 (if (eq (length window-buffers) 1)
116 (car window-buffers)))
117 (if (and next-error-last-buffer (buffer-name next-error-last-buffer)
118 (next-error-buffer-p next-error-last-buffer extra-test)
119 (or (not other-buffer) (not (eq next-error-last-buffer
120 (current-buffer)))))
121 next-error-last-buffer
122 (let ((buffers (buffer-list)))
123 (while (and buffers (or (not (next-error-buffer-p (car buffers) extra-test))
124 (and other-buffer
125 (eq (car buffers) (current-buffer)))))
126 (setq buffers (cdr buffers)))
127 (if buffers
128 (car buffers)
129 (or (and other-buffer
130 (next-error-buffer-p (current-buffer) extra-test)
131 ;; The current buffer is a next-error capable buffer.
132 (progn
133 (if other-buffer
134 (message "This is the only next-error capable buffer."))
135 (current-buffer)))
136 (error "No next-error capable buffer found"))))))))
137
138 (defun next-error (arg &optional reset)
139 "Visit next next-error message and corresponding source code.
140
141 If all the error messages parsed so far have been processed already,
142 the message buffer is checked for new ones.
143
144 A prefix ARG specifies how many error messages to move;
145 negative means move back to previous error messages.
146 Just \\[universal-argument] as a prefix means reparse the error message buffer
147 and start at the first error.
148
149 The RESET argument specifies that we should restart from the beginning.
150
151 \\[next-error] normally uses the most recently started
152 compilation, grep, or occur buffer. It can also operate on any
153 buffer with output from the \\[compile], \\[grep] commands, or,
154 more generally, on any buffer in Compilation mode or with
155 Compilation Minor mode enabled, or any buffer in which
156 `next-error-function' is bound to an appropriate
157 function. To specify use of a particular buffer for error
158 messages, type \\[next-error] in that buffer.
159
160 Once \\[next-error] has chosen the buffer for error messages,
161 it stays with that buffer until you use it in some other buffer which
162 uses Compilation mode or Compilation Minor mode.
163
164 See variables `compilation-parse-errors-function' and
165 \`compilation-error-regexp-alist' for customization ideas."
166 (interactive "P")
167 (if (consp arg) (setq reset t arg nil))
168 (when (setq next-error-last-buffer (next-error-find-buffer))
169 ;; we know here that next-error-function is a valid symbol we can funcall
170 (with-current-buffer next-error-last-buffer
171 (funcall next-error-function (prefix-numeric-value arg) reset))))
172
173 (defalias 'goto-next-locus 'next-error)
174 (defalias 'next-match 'next-error)
175
176 (define-key ctl-x-map "`" 'next-error)
177
178 (defun previous-error (n)
179 "Visit previous next-error message and corresponding source code.
180
181 Prefix arg N says how many error messages to move backwards (or
182 forwards, if negative).
183
184 This operates on the output from the \\[compile] and \\[grep] commands."
185 (interactive "p")
186 (next-error (- n)))
187
188 (defun first-error (n)
189 "Restart at the first error.
190 Visit corresponding source code.
191 With prefix arg N, visit the source code of the Nth error.
192 This operates on the output from the \\[compile] command, for instance."
193 (interactive "p")
194 (next-error n t))
195
196 (defun next-error-no-select (n)
197 "Move point to the next error in the next-error buffer and highlight match.
198 Prefix arg N says how many error messages to move forwards (or
199 backwards, if negative).
200 Finds and highlights the source line like \\[next-error], but does not
201 select the source buffer."
202 (interactive "p")
203 (next-error n)
204 (pop-to-buffer next-error-last-buffer))
205
206 (defun previous-error-no-select (n)
207 "Move point to the previous error in the next-error buffer and highlight match.
208 Prefix arg N says how many error messages to move backwards (or
209 forwards, if negative).
210 Finds and highlights the source line like \\[previous-error], but does not
211 select the source buffer."
212 (interactive "p")
213 (next-error-no-select (- n)))
214
215 ;;;
216
217 (defun fundamental-mode ()
218 "Major mode not specialized for anything in particular.
219 Other major modes are defined by comparison with this one."
220 (interactive)
221 (kill-all-local-variables))
222
223 ;; Making and deleting lines.
224
225 (defun newline (&optional arg)
226 "Insert a newline, and move to left margin of the new line if it's blank.
227 If `use-hard-newlines' is non-nil, the newline is marked with the
228 text-property `hard'.
229 With ARG, insert that many newlines.
230 Call `auto-fill-function' if the current column number is greater
231 than the value of `fill-column' and ARG is nil."
232 (interactive "*P")
233 (barf-if-buffer-read-only)
234 ;; Inserting a newline at the end of a line produces better redisplay in
235 ;; try_window_id than inserting at the beginning of a line, and the textual
236 ;; result is the same. So, if we're at beginning of line, pretend to be at
237 ;; the end of the previous line.
238 (let ((flag (and (not (bobp))
239 (bolp)
240 ;; Make sure no functions want to be told about
241 ;; the range of the changes.
242 (not after-change-functions)
243 (not before-change-functions)
244 ;; Make sure there are no markers here.
245 (not (buffer-has-markers-at (1- (point))))
246 (not (buffer-has-markers-at (point)))
247 ;; Make sure no text properties want to know
248 ;; where the change was.
249 (not (get-char-property (1- (point)) 'modification-hooks))
250 (not (get-char-property (1- (point)) 'insert-behind-hooks))
251 (or (eobp)
252 (not (get-char-property (point) 'insert-in-front-hooks)))
253 ;; Make sure the newline before point isn't intangible.
254 (not (get-char-property (1- (point)) 'intangible))
255 ;; Make sure the newline before point isn't read-only.
256 (not (get-char-property (1- (point)) 'read-only))
257 ;; Make sure the newline before point isn't invisible.
258 (not (get-char-property (1- (point)) 'invisible))
259 ;; Make sure the newline before point has the same
260 ;; properties as the char before it (if any).
261 (< (or (previous-property-change (point)) -2)
262 (- (point) 2))))
263 (was-page-start (and (bolp)
264 (looking-at page-delimiter)))
265 (beforepos (point)))
266 (if flag (backward-char 1))
267 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
268 ;; Set last-command-char to tell self-insert what to insert.
269 (let ((last-command-char ?\n)
270 ;; Don't auto-fill if we have a numeric argument.
271 ;; Also not if flag is true (it would fill wrong line);
272 ;; there is no need to since we're at BOL.
273 (auto-fill-function (if (or arg flag) nil auto-fill-function)))
274 (unwind-protect
275 (self-insert-command (prefix-numeric-value arg))
276 ;; If we get an error in self-insert-command, put point at right place.
277 (if flag (forward-char 1))))
278 ;; Even if we did *not* get an error, keep that forward-char;
279 ;; all further processing should apply to the newline that the user
280 ;; thinks he inserted.
281
282 ;; Mark the newline(s) `hard'.
283 (if use-hard-newlines
284 (set-hard-newline-properties
285 (- (point) (if arg (prefix-numeric-value arg) 1)) (point)))
286 ;; If the newline leaves the previous line blank,
287 ;; and we have a left margin, delete that from the blank line.
288 (or flag
289 (save-excursion
290 (goto-char beforepos)
291 (beginning-of-line)
292 (and (looking-at "[ \t]$")
293 (> (current-left-margin) 0)
294 (delete-region (point) (progn (end-of-line) (point))))))
295 ;; Indent the line after the newline, except in one case:
296 ;; when we added the newline at the beginning of a line
297 ;; which starts a page.
298 (or was-page-start
299 (move-to-left-margin nil t)))
300 nil)
301
302 (defun set-hard-newline-properties (from to)
303 (let ((sticky (get-text-property from 'rear-nonsticky)))
304 (put-text-property from to 'hard 't)
305 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
306 (if (and (listp sticky) (not (memq 'hard sticky)))
307 (put-text-property from (point) 'rear-nonsticky
308 (cons 'hard sticky)))))
309
310 (defun open-line (n)
311 "Insert a newline and leave point before it.
312 If there is a fill prefix and/or a left-margin, insert them on the new line
313 if the line would have been blank.
314 With arg N, insert N newlines."
315 (interactive "*p")
316 (let* ((do-fill-prefix (and fill-prefix (bolp)))
317 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
318 (loc (point))
319 ;; Don't expand an abbrev before point.
320 (abbrev-mode nil))
321 (newline n)
322 (goto-char loc)
323 (while (> n 0)
324 (cond ((bolp)
325 (if do-left-margin (indent-to (current-left-margin)))
326 (if do-fill-prefix (insert-and-inherit fill-prefix))))
327 (forward-line 1)
328 (setq n (1- n)))
329 (goto-char loc)
330 (end-of-line)))
331
332 (defun split-line (&optional arg)
333 "Split current line, moving portion beyond point vertically down.
334 If the current line starts with `fill-prefix', insert it on the new
335 line as well. With prefix ARG, don't insert fill-prefix on new line.
336
337 When called from Lisp code, ARG may be a prefix string to copy."
338 (interactive "*P")
339 (skip-chars-forward " \t")
340 (let* ((col (current-column))
341 (pos (point))
342 ;; What prefix should we check for (nil means don't).
343 (prefix (cond ((stringp arg) arg)
344 (arg nil)
345 (t fill-prefix)))
346 ;; Does this line start with it?
347 (have-prfx (and prefix
348 (save-excursion
349 (beginning-of-line)
350 (looking-at (regexp-quote prefix))))))
351 (newline 1)
352 (if have-prfx (insert-and-inherit prefix))
353 (indent-to col 0)
354 (goto-char pos)))
355
356 (defun delete-indentation (&optional arg)
357 "Join this line to previous and fix up whitespace at join.
358 If there is a fill prefix, delete it from the beginning of this line.
359 With argument, join this line to following line."
360 (interactive "*P")
361 (beginning-of-line)
362 (if arg (forward-line 1))
363 (if (eq (preceding-char) ?\n)
364 (progn
365 (delete-region (point) (1- (point)))
366 ;; If the second line started with the fill prefix,
367 ;; delete the prefix.
368 (if (and fill-prefix
369 (<= (+ (point) (length fill-prefix)) (point-max))
370 (string= fill-prefix
371 (buffer-substring (point)
372 (+ (point) (length fill-prefix)))))
373 (delete-region (point) (+ (point) (length fill-prefix))))
374 (fixup-whitespace))))
375
376 (defalias 'join-line #'delete-indentation) ; easier to find
377
378 (defun delete-blank-lines ()
379 "On blank line, delete all surrounding blank lines, leaving just one.
380 On isolated blank line, delete that one.
381 On nonblank line, delete any immediately following blank lines."
382 (interactive "*")
383 (let (thisblank singleblank)
384 (save-excursion
385 (beginning-of-line)
386 (setq thisblank (looking-at "[ \t]*$"))
387 ;; Set singleblank if there is just one blank line here.
388 (setq singleblank
389 (and thisblank
390 (not (looking-at "[ \t]*\n[ \t]*$"))
391 (or (bobp)
392 (progn (forward-line -1)
393 (not (looking-at "[ \t]*$")))))))
394 ;; Delete preceding blank lines, and this one too if it's the only one.
395 (if thisblank
396 (progn
397 (beginning-of-line)
398 (if singleblank (forward-line 1))
399 (delete-region (point)
400 (if (re-search-backward "[^ \t\n]" nil t)
401 (progn (forward-line 1) (point))
402 (point-min)))))
403 ;; Delete following blank lines, unless the current line is blank
404 ;; and there are no following blank lines.
405 (if (not (and thisblank singleblank))
406 (save-excursion
407 (end-of-line)
408 (forward-line 1)
409 (delete-region (point)
410 (if (re-search-forward "[^ \t\n]" nil t)
411 (progn (beginning-of-line) (point))
412 (point-max)))))
413 ;; Handle the special case where point is followed by newline and eob.
414 ;; Delete the line, leaving point at eob.
415 (if (looking-at "^[ \t]*\n\\'")
416 (delete-region (point) (point-max)))))
417
418 (defun delete-trailing-whitespace ()
419 "Delete all the trailing whitespace across the current buffer.
420 All whitespace after the last non-whitespace character in a line is deleted.
421 This respects narrowing, created by \\[narrow-to-region] and friends.
422 A formfeed is not considered whitespace by this function."
423 (interactive "*")
424 (save-match-data
425 (save-excursion
426 (goto-char (point-min))
427 (while (re-search-forward "\\s-$" nil t)
428 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
429 ;; Don't delete formfeeds, even if they are considered whitespace.
430 (save-match-data
431 (if (looking-at ".*\f")
432 (goto-char (match-end 0))))
433 (delete-region (point) (match-end 0))))))
434
435 (defun newline-and-indent ()
436 "Insert a newline, then indent according to major mode.
437 Indentation is done using the value of `indent-line-function'.
438 In programming language modes, this is the same as TAB.
439 In some text modes, where TAB inserts a tab, this command indents to the
440 column specified by the function `current-left-margin'."
441 (interactive "*")
442 (delete-horizontal-space t)
443 (newline)
444 (indent-according-to-mode))
445
446 (defun reindent-then-newline-and-indent ()
447 "Reindent current line, insert newline, then indent the new line.
448 Indentation of both lines is done according to the current major mode,
449 which means calling the current value of `indent-line-function'.
450 In programming language modes, this is the same as TAB.
451 In some text modes, where TAB inserts a tab, this indents to the
452 column specified by the function `current-left-margin'."
453 (interactive "*")
454 (let ((pos (point)))
455 ;; Be careful to insert the newline before indenting the line.
456 ;; Otherwise, the indentation might be wrong.
457 (newline)
458 (save-excursion
459 (goto-char pos)
460 (indent-according-to-mode)
461 (delete-horizontal-space t))
462 (indent-according-to-mode)))
463
464 (defun quoted-insert (arg)
465 "Read next input character and insert it.
466 This is useful for inserting control characters.
467
468 If the first character you type after this command is an octal digit,
469 you should type a sequence of octal digits which specify a character code.
470 Any nondigit terminates the sequence. If the terminator is a RET,
471 it is discarded; any other terminator is used itself as input.
472 The variable `read-quoted-char-radix' specifies the radix for this feature;
473 set it to 10 or 16 to use decimal or hex instead of octal.
474
475 In overwrite mode, this function inserts the character anyway, and
476 does not handle octal digits specially. This means that if you use
477 overwrite as your normal editing mode, you can use this function to
478 insert characters when necessary.
479
480 In binary overwrite mode, this function does overwrite, and octal
481 digits are interpreted as a character code. This is intended to be
482 useful for editing binary files."
483 (interactive "*p")
484 (let* ((char (let (translation-table-for-input)
485 (if (or (not overwrite-mode)
486 (eq overwrite-mode 'overwrite-mode-binary))
487 (read-quoted-char)
488 (read-char)))))
489 ;; Assume character codes 0240 - 0377 stand for characters in some
490 ;; single-byte character set, and convert them to Emacs
491 ;; characters.
492 (if (and enable-multibyte-characters
493 (>= char ?\240)
494 (<= char ?\377))
495 (setq char (unibyte-char-to-multibyte char)))
496 (if (> arg 0)
497 (if (eq overwrite-mode 'overwrite-mode-binary)
498 (delete-char arg)))
499 (while (> arg 0)
500 (insert-and-inherit char)
501 (setq arg (1- arg)))))
502
503 (defun forward-to-indentation (&optional arg)
504 "Move forward ARG lines and position at first nonblank character."
505 (interactive "p")
506 (forward-line (or arg 1))
507 (skip-chars-forward " \t"))
508
509 (defun backward-to-indentation (&optional arg)
510 "Move backward ARG lines and position at first nonblank character."
511 (interactive "p")
512 (forward-line (- (or arg 1)))
513 (skip-chars-forward " \t"))
514
515 (defun back-to-indentation ()
516 "Move point to the first non-whitespace character on this line."
517 (interactive)
518 (beginning-of-line 1)
519 (skip-syntax-forward " " (line-end-position))
520 ;; Move back over chars that have whitespace syntax but have the p flag.
521 (backward-prefix-chars))
522
523 (defun fixup-whitespace ()
524 "Fixup white space between objects around point.
525 Leave one space or none, according to the context."
526 (interactive "*")
527 (save-excursion
528 (delete-horizontal-space)
529 (if (or (looking-at "^\\|\\s)")
530 (save-excursion (forward-char -1)
531 (looking-at "$\\|\\s(\\|\\s'")))
532 nil
533 (insert ?\ ))))
534
535 (defun delete-horizontal-space (&optional backward-only)
536 "Delete all spaces and tabs around point.
537 If BACKWARD-ONLY is non-nil, only delete spaces before point."
538 (interactive "*")
539 (let ((orig-pos (point)))
540 (delete-region
541 (if backward-only
542 orig-pos
543 (progn
544 (skip-chars-forward " \t")
545 (constrain-to-field nil orig-pos t)))
546 (progn
547 (skip-chars-backward " \t")
548 (constrain-to-field nil orig-pos)))))
549
550 (defun just-one-space ()
551 "Delete all spaces and tabs around point, leaving one space."
552 (interactive "*")
553 (let ((orig-pos (point)))
554 (skip-chars-backward " \t")
555 (constrain-to-field nil orig-pos)
556 (if (= (following-char) ? )
557 (forward-char 1)
558 (insert ? ))
559 (delete-region
560 (point)
561 (progn
562 (skip-chars-forward " \t")
563 (constrain-to-field nil orig-pos t)))))
564 \f
565 (defvar inhibit-mark-movement nil
566 "If non-nil, \\[beginning-of-buffer] and \\[end-of-buffer] does not set the mark.")
567
568 (defun beginning-of-buffer (&optional arg)
569 "Move point to the beginning of the buffer; leave mark at previous position.
570 With \\[universal-argument] prefix, do not set mark at previous position.
571 With numeric arg N, put point N/10 of the way from the beginning.
572
573 If the buffer is narrowed, this command uses the beginning and size
574 of the accessible part of the buffer.
575
576 Don't use this command in Lisp programs!
577 \(goto-char (point-min)) is faster and avoids clobbering the mark."
578 (interactive "P")
579 (unless (or inhibit-mark-movement (consp arg))
580 (push-mark))
581 (let ((size (- (point-max) (point-min))))
582 (goto-char (if (and arg (not (consp arg)))
583 (+ (point-min)
584 (if (> size 10000)
585 ;; Avoid overflow for large buffer sizes!
586 (* (prefix-numeric-value arg)
587 (/ size 10))
588 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
589 (point-min))))
590 (if arg (forward-line 1)))
591
592 (defun end-of-buffer (&optional arg)
593 "Move point to the end of the buffer; leave mark at previous position.
594 With \\[universal-argument] prefix, do not set mark at previous position.
595 With numeric arg N, put point N/10 of the way from the end.
596
597 If the buffer is narrowed, this command uses the beginning and size
598 of the accessible part of the buffer.
599
600 Don't use this command in Lisp programs!
601 \(goto-char (point-max)) is faster and avoids clobbering the mark."
602 (interactive "P")
603 (unless (or inhibit-mark-movement (consp arg))
604 (push-mark))
605 (let ((size (- (point-max) (point-min))))
606 (goto-char (if (and arg (not (consp arg)))
607 (- (point-max)
608 (if (> size 10000)
609 ;; Avoid overflow for large buffer sizes!
610 (* (prefix-numeric-value arg)
611 (/ size 10))
612 (/ (* size (prefix-numeric-value arg)) 10)))
613 (point-max))))
614 ;; If we went to a place in the middle of the buffer,
615 ;; adjust it to the beginning of a line.
616 (cond (arg (forward-line 1))
617 ((> (point) (window-end nil t))
618 ;; If the end of the buffer is not already on the screen,
619 ;; then scroll specially to put it near, but not at, the bottom.
620 (overlay-recenter (point))
621 (recenter -3))))
622
623 (defun mark-whole-buffer ()
624 "Put point at beginning and mark at end of buffer.
625 You probably should not use this function in Lisp programs;
626 it is usually a mistake for a Lisp function to use any subroutine
627 that uses or sets the mark."
628 (interactive)
629 (push-mark (point))
630 (push-mark (point-max) nil t)
631 (goto-char (point-min)))
632 \f
633
634 ;; Counting lines, one way or another.
635
636 (defun goto-line (arg)
637 "Goto line ARG, counting from line 1 at beginning of buffer."
638 (interactive "NGoto line: ")
639 (setq arg (prefix-numeric-value arg))
640 (save-restriction
641 (widen)
642 (goto-char 1)
643 (if (eq selective-display t)
644 (re-search-forward "[\n\C-m]" nil 'end (1- arg))
645 (forward-line (1- arg)))))
646
647 (defun count-lines-region (start end)
648 "Print number of lines and characters in the region."
649 (interactive "r")
650 (message "Region has %d lines, %d characters"
651 (count-lines start end) (- end start)))
652
653 (defun what-line ()
654 "Print the current buffer line number and narrowed line number of point."
655 (interactive)
656 (let ((opoint (point)) (start (point-min))
657 (n (line-number-at-pos)))
658 (if (= start 1)
659 (message "Line %d" n)
660 (save-excursion
661 (save-restriction
662 (widen)
663 (message "line %d (narrowed line %d)"
664 (+ n (line-number-at-pos start) -1) n))))))
665
666 (defun count-lines (start end)
667 "Return number of lines between START and END.
668 This is usually the number of newlines between them,
669 but can be one more if START is not equal to END
670 and the greater of them is not at the start of a line."
671 (save-excursion
672 (save-restriction
673 (narrow-to-region start end)
674 (goto-char (point-min))
675 (if (eq selective-display t)
676 (save-match-data
677 (let ((done 0))
678 (while (re-search-forward "[\n\C-m]" nil t 40)
679 (setq done (+ 40 done)))
680 (while (re-search-forward "[\n\C-m]" nil t 1)
681 (setq done (+ 1 done)))
682 (goto-char (point-max))
683 (if (and (/= start end)
684 (not (bolp)))
685 (1+ done)
686 done)))
687 (- (buffer-size) (forward-line (buffer-size)))))))
688
689 (defun line-number-at-pos (&optional pos)
690 "Return (narrowed) buffer line number at position POS.
691 If POS is nil, use current buffer location."
692 (let ((opoint (or pos (point))) start)
693 (save-excursion
694 (goto-char (point-min))
695 (setq start (point))
696 (goto-char opoint)
697 (forward-line 0)
698 (1+ (count-lines start (point))))))
699
700 (defun what-cursor-position (&optional detail)
701 "Print info on cursor position (on screen and within buffer).
702 Also describe the character after point, and give its character code
703 in octal, decimal and hex.
704
705 For a non-ASCII multibyte character, also give its encoding in the
706 buffer's selected coding system if the coding system encodes the
707 character safely. If the character is encoded into one byte, that
708 code is shown in hex. If the character is encoded into more than one
709 byte, just \"...\" is shown.
710
711 In addition, with prefix argument, show details about that character
712 in *Help* buffer. See also the command `describe-char'."
713 (interactive "P")
714 (let* ((char (following-char))
715 (beg (point-min))
716 (end (point-max))
717 (pos (point))
718 (total (buffer-size))
719 (percent (if (> total 50000)
720 ;; Avoid overflow from multiplying by 100!
721 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
722 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
723 (hscroll (if (= (window-hscroll) 0)
724 ""
725 (format " Hscroll=%d" (window-hscroll))))
726 (col (current-column)))
727 (if (= pos end)
728 (if (or (/= beg 1) (/= end (1+ total)))
729 (message "point=%d of %d (%d%%) <%d - %d> column %d %s"
730 pos total percent beg end col hscroll)
731 (message "point=%d of %d (%d%%) column %d %s"
732 pos total percent col hscroll))
733 (let ((coding buffer-file-coding-system)
734 encoded encoding-msg)
735 (if (or (not coding)
736 (eq (coding-system-type coding) t))
737 (setq coding default-buffer-file-coding-system))
738 (if (eq (char-charset char) 'eight-bit)
739 (setq encoding-msg
740 (format "(0%o, %d, 0x%x, raw-byte)" char char char))
741 (setq encoded (and (>= char 128) (encode-coding-char char coding)))
742 (setq encoding-msg
743 (if encoded
744 (format "(0%o, %d, 0x%x, file %s)"
745 char char char
746 (if (> (length encoded) 1)
747 "..."
748 (encoded-string-description encoded coding)))
749 (format "(0%o, %d, 0x%x)" char char char))))
750 (if detail
751 ;; We show the detailed information about CHAR.
752 (describe-char (point)))
753 (if (or (/= beg 1) (/= end (1+ total)))
754 (message "Char: %s %s point=%d of %d (%d%%) <%d - %d> column %d %s"
755 (if (< char 256)
756 (single-key-description char)
757 (buffer-substring-no-properties (point) (1+ (point))))
758 encoding-msg pos total percent beg end col hscroll)
759 (message "Char: %s %s point=%d of %d (%d%%) column %d %s"
760 (if (< char 256)
761 (single-key-description char)
762 (buffer-substring-no-properties (point) (1+ (point))))
763 encoding-msg pos total percent col hscroll))))))
764 \f
765 (defvar read-expression-map
766 (let ((m (make-sparse-keymap)))
767 (define-key m "\M-\t" 'lisp-complete-symbol)
768 (set-keymap-parent m minibuffer-local-map)
769 m)
770 "Minibuffer keymap used for reading Lisp expressions.")
771
772 (defvar read-expression-history nil)
773
774 (defcustom eval-expression-print-level 4
775 "*Value to use for `print-level' when printing value in `eval-expression'.
776 A value of nil means no limit."
777 :group 'lisp
778 :type '(choice (const :tag "No Limit" nil) integer)
779 :version "21.1")
780
781 (defcustom eval-expression-print-length 12
782 "*Value to use for `print-length' when printing value in `eval-expression'.
783 A value of nil means no limit."
784 :group 'lisp
785 :type '(choice (const :tag "No Limit" nil) integer)
786 :version "21.1")
787
788 (defcustom eval-expression-debug-on-error t
789 "*Non-nil means set `debug-on-error' when evaluating in `eval-expression'.
790 If nil, don't change the value of `debug-on-error'."
791 :group 'lisp
792 :type 'boolean
793 :version "21.1")
794
795 (defun eval-expression-print-format (value)
796 "Format VALUE as a result of evaluated expression.
797 Return a formatted string which is displayed in the echo area
798 in addition to the value printed by prin1 in functions which
799 display the result of expression evaluation."
800 (if (and (integerp value)
801 (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
802 (eq this-command last-command)
803 (and (boundp 'edebug-active) edebug-active)))
804 (let ((char-string
805 (if (or (and (boundp 'edebug-active) edebug-active)
806 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
807 (prin1-char value))))
808 (if char-string
809 (format " (0%o, 0x%x) = %s" value value char-string)
810 (format " (0%o, 0x%x)" value value)))))
811
812 ;; We define this, rather than making `eval' interactive,
813 ;; for the sake of completion of names like eval-region, eval-current-buffer.
814 (defun eval-expression (eval-expression-arg
815 &optional eval-expression-insert-value)
816 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
817 Value is also consed on to front of the variable `values'.
818 Optional argument EVAL-EXPRESSION-INSERT-VALUE, if non-nil, means
819 insert the result into the current buffer instead of printing it in
820 the echo area."
821 (interactive
822 (list (read-from-minibuffer "Eval: "
823 nil read-expression-map t
824 'read-expression-history)
825 current-prefix-arg))
826
827 (if (null eval-expression-debug-on-error)
828 (setq values (cons (eval eval-expression-arg) values))
829 (let ((old-value (make-symbol "t")) new-value)
830 ;; Bind debug-on-error to something unique so that we can
831 ;; detect when evaled code changes it.
832 (let ((debug-on-error old-value))
833 (setq values (cons (eval eval-expression-arg) values))
834 (setq new-value debug-on-error))
835 ;; If evaled code has changed the value of debug-on-error,
836 ;; propagate that change to the global binding.
837 (unless (eq old-value new-value)
838 (setq debug-on-error new-value))))
839
840 (let ((print-length eval-expression-print-length)
841 (print-level eval-expression-print-level))
842 (if eval-expression-insert-value
843 (with-no-warnings
844 (let ((standard-output (current-buffer)))
845 (eval-last-sexp-print-value (car values))))
846 (prog1
847 (prin1 (car values) t)
848 (let ((str (eval-expression-print-format (car values))))
849 (if str (princ str t)))))))
850
851 (defun edit-and-eval-command (prompt command)
852 "Prompting with PROMPT, let user edit COMMAND and eval result.
853 COMMAND is a Lisp expression. Let user edit that expression in
854 the minibuffer, then read and evaluate the result."
855 (let ((command
856 (let ((print-level nil)
857 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
858 (unwind-protect
859 (read-from-minibuffer prompt
860 (prin1-to-string command)
861 read-expression-map t
862 'command-history)
863 ;; If command was added to command-history as a string,
864 ;; get rid of that. We want only evaluable expressions there.
865 (if (stringp (car command-history))
866 (setq command-history (cdr command-history)))))))
867
868 ;; If command to be redone does not match front of history,
869 ;; add it to the history.
870 (or (equal command (car command-history))
871 (setq command-history (cons command command-history)))
872 (eval command)))
873
874 (defun repeat-complex-command (arg)
875 "Edit and re-evaluate last complex command, or ARGth from last.
876 A complex command is one which used the minibuffer.
877 The command is placed in the minibuffer as a Lisp form for editing.
878 The result is executed, repeating the command as changed.
879 If the command has been changed or is not the most recent previous command
880 it is added to the front of the command history.
881 You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
882 to get different commands to edit and resubmit."
883 (interactive "p")
884 (let ((elt (nth (1- arg) command-history))
885 newcmd)
886 (if elt
887 (progn
888 (setq newcmd
889 (let ((print-level nil)
890 (minibuffer-history-position arg)
891 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
892 (unwind-protect
893 (read-from-minibuffer
894 "Redo: " (prin1-to-string elt) read-expression-map t
895 (cons 'command-history arg))
896
897 ;; If command was added to command-history as a
898 ;; string, get rid of that. We want only
899 ;; evaluable expressions there.
900 (if (stringp (car command-history))
901 (setq command-history (cdr command-history))))))
902
903 ;; If command to be redone does not match front of history,
904 ;; add it to the history.
905 (or (equal newcmd (car command-history))
906 (setq command-history (cons newcmd command-history)))
907 (eval newcmd))
908 (if command-history
909 (error "Argument %d is beyond length of command history" arg)
910 (error "There are no previous complex commands to repeat")))))
911 \f
912 (defvar minibuffer-history nil
913 "Default minibuffer history list.
914 This is used for all minibuffer input
915 except when an alternate history list is specified.")
916 (defvar minibuffer-history-sexp-flag nil
917 "Control whether history list elements are expressions or strings.
918 If the value of this variable equals current minibuffer depth,
919 they are expressions; otherwise they are strings.
920 \(That convention is designed to do the right thing fora
921 recursive uses of the minibuffer.)")
922 (setq minibuffer-history-variable 'minibuffer-history)
923 (setq minibuffer-history-position nil)
924 (defvar minibuffer-history-search-history nil)
925
926 (defvar minibuffer-text-before-history nil
927 "Text that was in this minibuffer before any history commands.
928 This is nil if there have not yet been any history commands
929 in this use of the minibuffer.")
930
931 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
932
933 (defun minibuffer-history-initialize ()
934 (setq minibuffer-text-before-history nil))
935
936 (defun minibuffer-avoid-prompt (new old)
937 "A point-motion hook for the minibuffer, that moves point out of the prompt."
938 (constrain-to-field nil (point-max)))
939
940 (defcustom minibuffer-history-case-insensitive-variables nil
941 "*Minibuffer history variables for which matching should ignore case.
942 If a history variable is a member of this list, then the
943 \\[previous-matching-history-element] and \\[next-matching-history-element]\
944 commands ignore case when searching it, regardless of `case-fold-search'."
945 :type '(repeat variable)
946 :group 'minibuffer)
947
948 (defun previous-matching-history-element (regexp n)
949 "Find the previous history element that matches REGEXP.
950 \(Previous history elements refer to earlier actions.)
951 With prefix argument N, search for Nth previous match.
952 If N is negative, find the next or Nth next match.
953 Normally, history elements are matched case-insensitively if
954 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
955 makes the search case-sensitive.
956 See also `minibuffer-history-case-insensitive-variables'."
957 (interactive
958 (let* ((enable-recursive-minibuffers t)
959 (regexp (read-from-minibuffer "Previous element matching (regexp): "
960 nil
961 minibuffer-local-map
962 nil
963 'minibuffer-history-search-history
964 (car minibuffer-history-search-history))))
965 ;; Use the last regexp specified, by default, if input is empty.
966 (list (if (string= regexp "")
967 (if minibuffer-history-search-history
968 (car minibuffer-history-search-history)
969 (error "No previous history search regexp"))
970 regexp)
971 (prefix-numeric-value current-prefix-arg))))
972 (unless (zerop n)
973 (if (and (zerop minibuffer-history-position)
974 (null minibuffer-text-before-history))
975 (setq minibuffer-text-before-history
976 (minibuffer-contents-no-properties)))
977 (let ((history (symbol-value minibuffer-history-variable))
978 (case-fold-search
979 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
980 ;; On some systems, ignore case for file names.
981 (if (memq minibuffer-history-variable
982 minibuffer-history-case-insensitive-variables)
983 t
984 ;; Respect the user's setting for case-fold-search:
985 case-fold-search)
986 nil))
987 prevpos
988 match-string
989 match-offset
990 (pos minibuffer-history-position))
991 (while (/= n 0)
992 (setq prevpos pos)
993 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
994 (when (= pos prevpos)
995 (error (if (= pos 1)
996 "No later matching history item"
997 "No earlier matching history item")))
998 (setq match-string
999 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1000 (let ((print-level nil))
1001 (prin1-to-string (nth (1- pos) history)))
1002 (nth (1- pos) history)))
1003 (setq match-offset
1004 (if (< n 0)
1005 (and (string-match regexp match-string)
1006 (match-end 0))
1007 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1008 (match-beginning 1))))
1009 (when match-offset
1010 (setq n (+ n (if (< n 0) 1 -1)))))
1011 (setq minibuffer-history-position pos)
1012 (goto-char (point-max))
1013 (delete-minibuffer-contents)
1014 (insert match-string)
1015 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1016 (if (memq (car (car command-history)) '(previous-matching-history-element
1017 next-matching-history-element))
1018 (setq command-history (cdr command-history))))
1019
1020 (defun next-matching-history-element (regexp n)
1021 "Find the next history element that matches REGEXP.
1022 \(The next history element refers to a more recent action.)
1023 With prefix argument N, search for Nth next match.
1024 If N is negative, find the previous or Nth previous match.
1025 Normally, history elements are matched case-insensitively if
1026 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1027 makes the search case-sensitive."
1028 (interactive
1029 (let* ((enable-recursive-minibuffers t)
1030 (regexp (read-from-minibuffer "Next element matching (regexp): "
1031 nil
1032 minibuffer-local-map
1033 nil
1034 'minibuffer-history-search-history)))
1035 ;; Use the last regexp specified, by default, if input is empty.
1036 (list (if (string= regexp "")
1037 (setcar minibuffer-history-search-history
1038 (nth 1 minibuffer-history-search-history))
1039 regexp)
1040 (prefix-numeric-value current-prefix-arg))))
1041 (previous-matching-history-element regexp (- n)))
1042
1043 (defvar minibuffer-temporary-goal-position nil)
1044
1045 (defun next-history-element (n)
1046 "Insert the next element of the minibuffer history into the minibuffer."
1047 (interactive "p")
1048 (or (zerop n)
1049 (let ((narg (- minibuffer-history-position n))
1050 (minimum (if minibuffer-default -1 0))
1051 elt minibuffer-returned-to-present)
1052 (if (and (zerop minibuffer-history-position)
1053 (null minibuffer-text-before-history))
1054 (setq minibuffer-text-before-history
1055 (minibuffer-contents-no-properties)))
1056 (if (< narg minimum)
1057 (if minibuffer-default
1058 (error "End of history; no next item")
1059 (error "End of history; no default available")))
1060 (if (> narg (length (symbol-value minibuffer-history-variable)))
1061 (error "Beginning of history; no preceding item"))
1062 (unless (memq last-command '(next-history-element
1063 previous-history-element))
1064 (let ((prompt-end (minibuffer-prompt-end)))
1065 (set (make-local-variable 'minibuffer-temporary-goal-position)
1066 (cond ((<= (point) prompt-end) prompt-end)
1067 ((eobp) nil)
1068 (t (point))))))
1069 (goto-char (point-max))
1070 (delete-minibuffer-contents)
1071 (setq minibuffer-history-position narg)
1072 (cond ((= narg -1)
1073 (setq elt minibuffer-default))
1074 ((= narg 0)
1075 (setq elt (or minibuffer-text-before-history ""))
1076 (setq minibuffer-returned-to-present t)
1077 (setq minibuffer-text-before-history nil))
1078 (t (setq elt (nth (1- minibuffer-history-position)
1079 (symbol-value minibuffer-history-variable)))))
1080 (insert
1081 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1082 (not minibuffer-returned-to-present))
1083 (let ((print-level nil))
1084 (prin1-to-string elt))
1085 elt))
1086 (goto-char (or minibuffer-temporary-goal-position (point-max))))))
1087
1088 (defun previous-history-element (n)
1089 "Inserts the previous element of the minibuffer history into the minibuffer."
1090 (interactive "p")
1091 (next-history-element (- n)))
1092
1093 (defun next-complete-history-element (n)
1094 "Get next history element which completes the minibuffer before the point.
1095 The contents of the minibuffer after the point are deleted, and replaced
1096 by the new completion."
1097 (interactive "p")
1098 (let ((point-at-start (point)))
1099 (next-matching-history-element
1100 (concat
1101 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1102 n)
1103 ;; next-matching-history-element always puts us at (point-min).
1104 ;; Move to the position we were at before changing the buffer contents.
1105 ;; This is still sensical, because the text before point has not changed.
1106 (goto-char point-at-start)))
1107
1108 (defun previous-complete-history-element (n)
1109 "\
1110 Get previous history element which completes the minibuffer before the point.
1111 The contents of the minibuffer after the point are deleted, and replaced
1112 by the new completion."
1113 (interactive "p")
1114 (next-complete-history-element (- n)))
1115
1116 ;; For compatibility with the old subr of the same name.
1117 (defun minibuffer-prompt-width ()
1118 "Return the display width of the minibuffer prompt.
1119 Return 0 if current buffer is not a mini-buffer."
1120 ;; Return the width of everything before the field at the end of
1121 ;; the buffer; this should be 0 for normal buffers.
1122 (1- (minibuffer-prompt-end)))
1123 \f
1124 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1125 (defalias 'advertised-undo 'undo)
1126
1127 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
1128 "Table mapping redo records to the corresponding undo one.")
1129
1130 (defvar undo-in-region nil
1131 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1132
1133 (defvar undo-no-redo nil
1134 "If t, `undo' doesn't go through redo entries.")
1135
1136 (defun undo (&optional arg)
1137 "Undo some previous changes.
1138 Repeat this command to undo more changes.
1139 A numeric argument serves as a repeat count.
1140
1141 In Transient Mark mode when the mark is active, only undo changes within
1142 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1143 as an argument limits undo to changes within the current region."
1144 (interactive "*P")
1145 ;; Make last-command indicate for the next command that this was an undo.
1146 ;; That way, another undo will undo more.
1147 ;; If we get to the end of the undo history and get an error,
1148 ;; another undo command will find the undo history empty
1149 ;; and will get another error. To begin undoing the undos,
1150 ;; you must type some other command.
1151 (let ((modified (buffer-modified-p))
1152 (recent-save (recent-auto-save-p)))
1153 ;; If we get an error in undo-start,
1154 ;; the next command should not be a "consecutive undo".
1155 ;; So set `this-command' to something other than `undo'.
1156 (setq this-command 'undo-start)
1157
1158 (unless (eq last-command 'undo)
1159 (setq undo-in-region
1160 (if transient-mark-mode mark-active (and arg (not (numberp arg)))))
1161 (if undo-in-region
1162 (undo-start (region-beginning) (region-end))
1163 (undo-start))
1164 ;; get rid of initial undo boundary
1165 (undo-more 1))
1166 ;; If we got this far, the next command should be a consecutive undo.
1167 (setq this-command 'undo)
1168 ;; Check to see whether we're hitting a redo record, and if
1169 ;; so, ask the user whether she wants to skip the redo/undo pair.
1170 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
1171 (or (eq (selected-window) (minibuffer-window))
1172 (message (if undo-in-region
1173 (if equiv "Redo in region!" "Undo in region!")
1174 (if equiv "Redo!" "Undo!"))))
1175 (when (and equiv undo-no-redo)
1176 ;; The equiv entry might point to another redo record if we have done
1177 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1178 (while (let ((next (gethash equiv undo-equiv-table)))
1179 (if next (setq equiv next))))
1180 (setq pending-undo-list equiv)))
1181 (undo-more
1182 (if (or transient-mark-mode (numberp arg))
1183 (prefix-numeric-value arg)
1184 1))
1185 ;; Record the fact that the just-generated undo records come from an
1186 ;; undo operation, so we can skip them later on.
1187 ;; I don't know how to do that in the undo-in-region case.
1188 (unless undo-in-region
1189 (puthash buffer-undo-list pending-undo-list undo-equiv-table))
1190 ;; Don't specify a position in the undo record for the undo command.
1191 ;; Instead, undoing this should move point to where the change is.
1192 (let ((tail buffer-undo-list)
1193 (prev nil))
1194 (while (car tail)
1195 (when (integerp (car tail))
1196 (let ((pos (car tail)))
1197 (if prev
1198 (setcdr prev (cdr tail))
1199 (setq buffer-undo-list (cdr tail)))
1200 (setq tail (cdr tail))
1201 (while (car tail)
1202 (if (eq pos (car tail))
1203 (if prev
1204 (setcdr prev (cdr tail))
1205 (setq buffer-undo-list (cdr tail)))
1206 (setq prev tail))
1207 (setq tail (cdr tail)))
1208 (setq tail nil)))
1209 (setq prev tail tail (cdr tail))))
1210
1211 (and modified (not (buffer-modified-p))
1212 (delete-auto-save-file-if-necessary recent-save))))
1213
1214 (defun undo-only (&optional arg)
1215 "Undo some previous changes.
1216 Repeat this command to undo more changes.
1217 A numeric argument serves as a repeat count.
1218 Contrary to `undo', this will not redo a previous undo."
1219 (interactive "*p")
1220 (let ((undo-no-redo t)) (undo arg)))
1221 ;; Richard said that we should not use C-x <uppercase letter> and I have
1222 ;; no idea whereas to bind it. Any suggestion welcome. -stef
1223 ;; (define-key ctl-x-map "U" 'undo-only)
1224
1225 (defvar pending-undo-list nil
1226 "Within a run of consecutive undo commands, list remaining to be undone.")
1227
1228 (defvar undo-in-progress nil
1229 "Non-nil while performing an undo.
1230 Some change-hooks test this variable to do something different.")
1231
1232 (defun undo-more (count)
1233 "Undo back N undo-boundaries beyond what was already undone recently.
1234 Call `undo-start' to get ready to undo recent changes,
1235 then call `undo-more' one or more times to undo them."
1236 (or pending-undo-list
1237 (error (format "No further undo information%s"
1238 (if (and transient-mark-mode mark-active)
1239 " for region" ""))))
1240 (let ((undo-in-progress t))
1241 (setq pending-undo-list (primitive-undo count pending-undo-list))))
1242
1243 ;; Deep copy of a list
1244 (defun undo-copy-list (list)
1245 "Make a copy of undo list LIST."
1246 (mapcar 'undo-copy-list-1 list))
1247
1248 (defun undo-copy-list-1 (elt)
1249 (if (consp elt)
1250 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1251 elt))
1252
1253 (defun undo-start (&optional beg end)
1254 "Set `pending-undo-list' to the front of the undo list.
1255 The next call to `undo-more' will undo the most recently made change.
1256 If BEG and END are specified, then only undo elements
1257 that apply to text between BEG and END are used; other undo elements
1258 are ignored. If BEG and END are nil, all undo elements are used."
1259 (if (eq buffer-undo-list t)
1260 (error "No undo information in this buffer"))
1261 (setq pending-undo-list
1262 (if (and beg end (not (= beg end)))
1263 (undo-make-selective-list (min beg end) (max beg end))
1264 buffer-undo-list)))
1265
1266 (defvar undo-adjusted-markers)
1267
1268 (defun undo-make-selective-list (start end)
1269 "Return a list of undo elements for the region START to END.
1270 The elements come from `buffer-undo-list', but we keep only
1271 the elements inside this region, and discard those outside this region.
1272 If we find an element that crosses an edge of this region,
1273 we stop and ignore all further elements."
1274 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1275 (undo-list (list nil))
1276 undo-adjusted-markers
1277 some-rejected
1278 undo-elt undo-elt temp-undo-list delta)
1279 (while undo-list-copy
1280 (setq undo-elt (car undo-list-copy))
1281 (let ((keep-this
1282 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1283 ;; This is a "was unmodified" element.
1284 ;; Keep it if we have kept everything thus far.
1285 (not some-rejected))
1286 (t
1287 (undo-elt-in-region undo-elt start end)))))
1288 (if keep-this
1289 (progn
1290 (setq end (+ end (cdr (undo-delta undo-elt))))
1291 ;; Don't put two nils together in the list
1292 (if (not (and (eq (car undo-list) nil)
1293 (eq undo-elt nil)))
1294 (setq undo-list (cons undo-elt undo-list))))
1295 (if (undo-elt-crosses-region undo-elt start end)
1296 (setq undo-list-copy nil)
1297 (setq some-rejected t)
1298 (setq temp-undo-list (cdr undo-list-copy))
1299 (setq delta (undo-delta undo-elt))
1300
1301 (when (/= (cdr delta) 0)
1302 (let ((position (car delta))
1303 (offset (cdr delta)))
1304
1305 ;; Loop down the earlier events adjusting their buffer
1306 ;; positions to reflect the fact that a change to the buffer
1307 ;; isn't being undone. We only need to process those element
1308 ;; types which undo-elt-in-region will return as being in
1309 ;; the region since only those types can ever get into the
1310 ;; output
1311
1312 (while temp-undo-list
1313 (setq undo-elt (car temp-undo-list))
1314 (cond ((integerp undo-elt)
1315 (if (>= undo-elt position)
1316 (setcar temp-undo-list (- undo-elt offset))))
1317 ((atom undo-elt) nil)
1318 ((stringp (car undo-elt))
1319 ;; (TEXT . POSITION)
1320 (let ((text-pos (abs (cdr undo-elt)))
1321 (point-at-end (< (cdr undo-elt) 0 )))
1322 (if (>= text-pos position)
1323 (setcdr undo-elt (* (if point-at-end -1 1)
1324 (- text-pos offset))))))
1325 ((integerp (car undo-elt))
1326 ;; (BEGIN . END)
1327 (when (>= (car undo-elt) position)
1328 (setcar undo-elt (- (car undo-elt) offset))
1329 (setcdr undo-elt (- (cdr undo-elt) offset))))
1330 ((null (car undo-elt))
1331 ;; (nil PROPERTY VALUE BEG . END)
1332 (let ((tail (nthcdr 3 undo-elt)))
1333 (when (>= (car tail) position)
1334 (setcar tail (- (car tail) offset))
1335 (setcdr tail (- (cdr tail) offset))))))
1336 (setq temp-undo-list (cdr temp-undo-list))))))))
1337 (setq undo-list-copy (cdr undo-list-copy)))
1338 (nreverse undo-list)))
1339
1340 (defun undo-elt-in-region (undo-elt start end)
1341 "Determine whether UNDO-ELT falls inside the region START ... END.
1342 If it crosses the edge, we return nil."
1343 (cond ((integerp undo-elt)
1344 (and (>= undo-elt start)
1345 (<= undo-elt end)))
1346 ((eq undo-elt nil)
1347 t)
1348 ((atom undo-elt)
1349 nil)
1350 ((stringp (car undo-elt))
1351 ;; (TEXT . POSITION)
1352 (and (>= (abs (cdr undo-elt)) start)
1353 (< (abs (cdr undo-elt)) end)))
1354 ((and (consp undo-elt) (markerp (car undo-elt)))
1355 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1356 ;; See if MARKER is inside the region.
1357 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1358 (unless alist-elt
1359 (setq alist-elt (cons (car undo-elt)
1360 (marker-position (car undo-elt))))
1361 (setq undo-adjusted-markers
1362 (cons alist-elt undo-adjusted-markers)))
1363 (and (cdr alist-elt)
1364 (>= (cdr alist-elt) start)
1365 (<= (cdr alist-elt) end))))
1366 ((null (car undo-elt))
1367 ;; (nil PROPERTY VALUE BEG . END)
1368 (let ((tail (nthcdr 3 undo-elt)))
1369 (and (>= (car tail) start)
1370 (<= (cdr tail) end))))
1371 ((integerp (car undo-elt))
1372 ;; (BEGIN . END)
1373 (and (>= (car undo-elt) start)
1374 (<= (cdr undo-elt) end)))))
1375
1376 (defun undo-elt-crosses-region (undo-elt start end)
1377 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1378 This assumes we have already decided that UNDO-ELT
1379 is not *inside* the region START...END."
1380 (cond ((atom undo-elt) nil)
1381 ((null (car undo-elt))
1382 ;; (nil PROPERTY VALUE BEG . END)
1383 (let ((tail (nthcdr 3 undo-elt)))
1384 (not (or (< (car tail) end)
1385 (> (cdr tail) start)))))
1386 ((integerp (car undo-elt))
1387 ;; (BEGIN . END)
1388 (not (or (< (car undo-elt) end)
1389 (> (cdr undo-elt) start))))))
1390
1391 ;; Return the first affected buffer position and the delta for an undo element
1392 ;; delta is defined as the change in subsequent buffer positions if we *did*
1393 ;; the undo.
1394 (defun undo-delta (undo-elt)
1395 (if (consp undo-elt)
1396 (cond ((stringp (car undo-elt))
1397 ;; (TEXT . POSITION)
1398 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1399 ((integerp (car undo-elt))
1400 ;; (BEGIN . END)
1401 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1402 (t
1403 '(0 . 0)))
1404 '(0 . 0)))
1405 \f
1406 (defvar shell-command-history nil
1407 "History list for some commands that read shell commands.")
1408
1409 (defvar shell-command-switch "-c"
1410 "Switch used to have the shell execute its command line argument.")
1411
1412 (defvar shell-command-default-error-buffer nil
1413 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1414 This buffer is used when `shell-command' or `shell-command-on-region'
1415 is run interactively. A value of nil means that output to stderr and
1416 stdout will be intermixed in the output stream.")
1417
1418 (defun shell-command (command &optional output-buffer error-buffer)
1419 "Execute string COMMAND in inferior shell; display output, if any.
1420 With prefix argument, insert the COMMAND's output at point.
1421
1422 If COMMAND ends in ampersand, execute it asynchronously.
1423 The output appears in the buffer `*Async Shell Command*'.
1424 That buffer is in shell mode.
1425
1426 Otherwise, COMMAND is executed synchronously. The output appears in
1427 the buffer `*Shell Command Output*'. If the output is short enough to
1428 display in the echo area (which is determined by the variables
1429 `resize-mini-windows' and `max-mini-window-height'), it is shown
1430 there, but it is nonetheless available in buffer `*Shell Command
1431 Output*' even though that buffer is not automatically displayed.
1432
1433 To specify a coding system for converting non-ASCII characters
1434 in the shell command output, use \\[universal-coding-system-argument]
1435 before this command.
1436
1437 Noninteractive callers can specify coding systems by binding
1438 `coding-system-for-read' and `coding-system-for-write'.
1439
1440 The optional second argument OUTPUT-BUFFER, if non-nil,
1441 says to put the output in some other buffer.
1442 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1443 If OUTPUT-BUFFER is not a buffer and not nil,
1444 insert output in current buffer. (This cannot be done asynchronously.)
1445 In either case, the output is inserted after point (leaving mark after it).
1446
1447 If the command terminates without error, but generates output,
1448 and you did not specify \"insert it in the current buffer\",
1449 the output can be displayed in the echo area or in its buffer.
1450 If the output is short enough to display in the echo area
1451 \(determined by the variable `max-mini-window-height' if
1452 `resize-mini-windows' is non-nil), it is shown there. Otherwise,
1453 the buffer containing the output is displayed.
1454
1455 If there is output and an error, and you did not specify \"insert it
1456 in the current buffer\", a message about the error goes at the end
1457 of the output.
1458
1459 If there is no output, or if output is inserted in the current buffer,
1460 then `*Shell Command Output*' is deleted.
1461
1462 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
1463 or buffer name to which to direct the command's standard error output.
1464 If it is nil, error output is mingled with regular output.
1465 In an interactive call, the variable `shell-command-default-error-buffer'
1466 specifies the value of ERROR-BUFFER."
1467
1468 (interactive (list (read-from-minibuffer "Shell command: "
1469 nil nil nil 'shell-command-history)
1470 current-prefix-arg
1471 shell-command-default-error-buffer))
1472 ;; Look for a handler in case default-directory is a remote file name.
1473 (let ((handler
1474 (find-file-name-handler (directory-file-name default-directory)
1475 'shell-command)))
1476 (if handler
1477 (funcall handler 'shell-command command output-buffer error-buffer)
1478 (if (and output-buffer
1479 (not (or (bufferp output-buffer) (stringp output-buffer))))
1480 ;; Output goes in current buffer.
1481 (let ((error-file
1482 (if error-buffer
1483 (make-temp-file
1484 (expand-file-name "scor"
1485 (or small-temporary-file-directory
1486 temporary-file-directory)))
1487 nil)))
1488 (barf-if-buffer-read-only)
1489 (push-mark nil t)
1490 ;; We do not use -f for csh; we will not support broken use of
1491 ;; .cshrcs. Even the BSD csh manual says to use
1492 ;; "if ($?prompt) exit" before things which are not useful
1493 ;; non-interactively. Besides, if someone wants their other
1494 ;; aliases for shell commands then they can still have them.
1495 (call-process shell-file-name nil
1496 (if error-file
1497 (list t error-file)
1498 t)
1499 nil shell-command-switch command)
1500 (when (and error-file (file-exists-p error-file))
1501 (if (< 0 (nth 7 (file-attributes error-file)))
1502 (with-current-buffer (get-buffer-create error-buffer)
1503 (let ((pos-from-end (- (point-max) (point))))
1504 (or (bobp)
1505 (insert "\f\n"))
1506 ;; Do no formatting while reading error file,
1507 ;; because that can run a shell command, and we
1508 ;; don't want that to cause an infinite recursion.
1509 (format-insert-file error-file nil)
1510 ;; Put point after the inserted errors.
1511 (goto-char (- (point-max) pos-from-end)))
1512 (display-buffer (current-buffer))))
1513 (delete-file error-file))
1514 ;; This is like exchange-point-and-mark, but doesn't
1515 ;; activate the mark. It is cleaner to avoid activation,
1516 ;; even though the command loop would deactivate the mark
1517 ;; because we inserted text.
1518 (goto-char (prog1 (mark t)
1519 (set-marker (mark-marker) (point)
1520 (current-buffer)))))
1521 ;; Output goes in a separate buffer.
1522 ;; Preserve the match data in case called from a program.
1523 (save-match-data
1524 (if (string-match "[ \t]*&[ \t]*\\'" command)
1525 ;; Command ending with ampersand means asynchronous.
1526 (let ((buffer (get-buffer-create
1527 (or output-buffer "*Async Shell Command*")))
1528 (directory default-directory)
1529 proc)
1530 ;; Remove the ampersand.
1531 (setq command (substring command 0 (match-beginning 0)))
1532 ;; If will kill a process, query first.
1533 (setq proc (get-buffer-process buffer))
1534 (if proc
1535 (if (yes-or-no-p "A command is running. Kill it? ")
1536 (kill-process proc)
1537 (error "Shell command in progress")))
1538 (with-current-buffer buffer
1539 (setq buffer-read-only nil)
1540 (erase-buffer)
1541 (display-buffer buffer)
1542 (setq default-directory directory)
1543 (setq proc (start-process "Shell" buffer shell-file-name
1544 shell-command-switch command))
1545 (setq mode-line-process '(":%s"))
1546 (require 'shell) (shell-mode)
1547 (set-process-sentinel proc 'shell-command-sentinel)
1548 ))
1549 (shell-command-on-region (point) (point) command
1550 output-buffer nil error-buffer)))))))
1551
1552 (defun display-message-or-buffer (message
1553 &optional buffer-name not-this-window frame)
1554 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
1555 MESSAGE may be either a string or a buffer.
1556
1557 A buffer is displayed using `display-buffer' if MESSAGE is too long for
1558 the maximum height of the echo area, as defined by `max-mini-window-height'
1559 if `resize-mini-windows' is non-nil.
1560
1561 Returns either the string shown in the echo area, or when a pop-up
1562 buffer is used, the window used to display it.
1563
1564 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
1565 name of the buffer used to display it in the case where a pop-up buffer
1566 is used, defaulting to `*Message*'. In the case where MESSAGE is a
1567 string and it is displayed in the echo area, it is not specified whether
1568 the contents are inserted into the buffer anyway.
1569
1570 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
1571 and only used if a buffer is displayed."
1572 (cond ((and (stringp message) (not (string-match "\n" message)))
1573 ;; Trivial case where we can use the echo area
1574 (message "%s" message))
1575 ((and (stringp message)
1576 (= (string-match "\n" message) (1- (length message))))
1577 ;; Trivial case where we can just remove single trailing newline
1578 (message "%s" (substring message 0 (1- (length message)))))
1579 (t
1580 ;; General case
1581 (with-current-buffer
1582 (if (bufferp message)
1583 message
1584 (get-buffer-create (or buffer-name "*Message*")))
1585
1586 (unless (bufferp message)
1587 (erase-buffer)
1588 (insert message))
1589
1590 (let ((lines
1591 (if (= (buffer-size) 0)
1592 0
1593 (count-lines (point-min) (point-max)))))
1594 (cond ((= lines 0))
1595 ((and (or (<= lines 1)
1596 (<= lines
1597 (if resize-mini-windows
1598 (cond ((floatp max-mini-window-height)
1599 (* (frame-height)
1600 max-mini-window-height))
1601 ((integerp max-mini-window-height)
1602 max-mini-window-height)
1603 (t
1604 1))
1605 1)))
1606 ;; Don't use the echo area if the output buffer is
1607 ;; already dispayed in the selected frame.
1608 (not (get-buffer-window (current-buffer))))
1609 ;; Echo area
1610 (goto-char (point-max))
1611 (when (bolp)
1612 (backward-char 1))
1613 (message "%s" (buffer-substring (point-min) (point))))
1614 (t
1615 ;; Buffer
1616 (goto-char (point-min))
1617 (display-buffer (current-buffer)
1618 not-this-window frame))))))))
1619
1620
1621 ;; We have a sentinel to prevent insertion of a termination message
1622 ;; in the buffer itself.
1623 (defun shell-command-sentinel (process signal)
1624 (if (memq (process-status process) '(exit signal))
1625 (message "%s: %s."
1626 (car (cdr (cdr (process-command process))))
1627 (substring signal 0 -1))))
1628
1629 (defun shell-command-on-region (start end command
1630 &optional output-buffer replace
1631 error-buffer)
1632 "Execute string COMMAND in inferior shell with region as input.
1633 Normally display output (if any) in temp buffer `*Shell Command Output*';
1634 Prefix arg means replace the region with it. Return the exit code of
1635 COMMAND.
1636
1637 To specify a coding system for converting non-ASCII characters
1638 in the input and output to the shell command, use \\[universal-coding-system-argument]
1639 before this command. By default, the input (from the current buffer)
1640 is encoded in the same coding system that will be used to save the file,
1641 `buffer-file-coding-system'. If the output is going to replace the region,
1642 then it is decoded from that same coding system.
1643
1644 The noninteractive arguments are START, END, COMMAND, OUTPUT-BUFFER,
1645 REPLACE, ERROR-BUFFER. Noninteractive callers can specify coding
1646 systems by binding `coding-system-for-read' and
1647 `coding-system-for-write'.
1648
1649 If the command generates output, the output may be displayed
1650 in the echo area or in a buffer.
1651 If the output is short enough to display in the echo area
1652 \(determined by the variable `max-mini-window-height' if
1653 `resize-mini-windows' is non-nil), it is shown there. Otherwise
1654 it is displayed in the buffer `*Shell Command Output*'. The output
1655 is available in that buffer in both cases.
1656
1657 If there is output and an error, a message about the error
1658 appears at the end of the output.
1659
1660 If there is no output, or if output is inserted in the current buffer,
1661 then `*Shell Command Output*' is deleted.
1662
1663 If the optional fourth argument OUTPUT-BUFFER is non-nil,
1664 that says to put the output in some other buffer.
1665 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1666 If OUTPUT-BUFFER is not a buffer and not nil,
1667 insert output in the current buffer.
1668 In either case, the output is inserted after point (leaving mark after it).
1669
1670 If REPLACE, the optional fifth argument, is non-nil, that means insert
1671 the output in place of text from START to END, putting point and mark
1672 around it.
1673
1674 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
1675 or buffer name to which to direct the command's standard error output.
1676 If it is nil, error output is mingled with regular output.
1677 In an interactive call, the variable `shell-command-default-error-buffer'
1678 specifies the value of ERROR-BUFFER."
1679 (interactive (let (string)
1680 (unless (mark)
1681 (error "The mark is not set now, so there is no region"))
1682 ;; Do this before calling region-beginning
1683 ;; and region-end, in case subprocess output
1684 ;; relocates them while we are in the minibuffer.
1685 (setq string (read-from-minibuffer "Shell command on region: "
1686 nil nil nil
1687 'shell-command-history))
1688 ;; call-interactively recognizes region-beginning and
1689 ;; region-end specially, leaving them in the history.
1690 (list (region-beginning) (region-end)
1691 string
1692 current-prefix-arg
1693 current-prefix-arg
1694 shell-command-default-error-buffer)))
1695 (let ((error-file
1696 (if error-buffer
1697 (make-temp-file
1698 (expand-file-name "scor"
1699 (or small-temporary-file-directory
1700 temporary-file-directory)))
1701 nil))
1702 exit-status)
1703 (if (or replace
1704 (and output-buffer
1705 (not (or (bufferp output-buffer) (stringp output-buffer)))))
1706 ;; Replace specified region with output from command.
1707 (let ((swap (and replace (< start end))))
1708 ;; Don't muck with mark unless REPLACE says we should.
1709 (goto-char start)
1710 (and replace (push-mark (point) 'nomsg))
1711 (setq exit-status
1712 (call-process-region start end shell-file-name t
1713 (if error-file
1714 (list t error-file)
1715 t)
1716 nil shell-command-switch command))
1717 ;; It is rude to delete a buffer which the command is not using.
1718 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
1719 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
1720 ;; (kill-buffer shell-buffer)))
1721 ;; Don't muck with mark unless REPLACE says we should.
1722 (and replace swap (exchange-point-and-mark)))
1723 ;; No prefix argument: put the output in a temp buffer,
1724 ;; replacing its entire contents.
1725 (let ((buffer (get-buffer-create
1726 (or output-buffer "*Shell Command Output*"))))
1727 (unwind-protect
1728 (if (eq buffer (current-buffer))
1729 ;; If the input is the same buffer as the output,
1730 ;; delete everything but the specified region,
1731 ;; then replace that region with the output.
1732 (progn (setq buffer-read-only nil)
1733 (delete-region (max start end) (point-max))
1734 (delete-region (point-min) (min start end))
1735 (setq exit-status
1736 (call-process-region (point-min) (point-max)
1737 shell-file-name t
1738 (if error-file
1739 (list t error-file)
1740 t)
1741 nil shell-command-switch
1742 command)))
1743 ;; Clear the output buffer, then run the command with
1744 ;; output there.
1745 (let ((directory default-directory))
1746 (save-excursion
1747 (set-buffer buffer)
1748 (setq buffer-read-only nil)
1749 (if (not output-buffer)
1750 (setq default-directory directory))
1751 (erase-buffer)))
1752 (setq exit-status
1753 (call-process-region start end shell-file-name nil
1754 (if error-file
1755 (list buffer error-file)
1756 buffer)
1757 nil shell-command-switch command)))
1758 ;; Report the output.
1759 (with-current-buffer buffer
1760 (setq mode-line-process
1761 (cond ((null exit-status)
1762 " - Error")
1763 ((stringp exit-status)
1764 (format " - Signal [%s]" exit-status))
1765 ((not (equal 0 exit-status))
1766 (format " - Exit [%d]" exit-status)))))
1767 (if (with-current-buffer buffer (> (point-max) (point-min)))
1768 ;; There's some output, display it
1769 (display-message-or-buffer buffer)
1770 ;; No output; error?
1771 (let ((output
1772 (if (and error-file
1773 (< 0 (nth 7 (file-attributes error-file))))
1774 "some error output"
1775 "no output")))
1776 (cond ((null exit-status)
1777 (message "(Shell command failed with error)"))
1778 ((equal 0 exit-status)
1779 (message "(Shell command succeeded with %s)"
1780 output))
1781 ((stringp exit-status)
1782 (message "(Shell command killed by signal %s)"
1783 exit-status))
1784 (t
1785 (message "(Shell command failed with code %d and %s)"
1786 exit-status output))))
1787 ;; Don't kill: there might be useful info in the undo-log.
1788 ;; (kill-buffer buffer)
1789 ))))
1790
1791 (when (and error-file (file-exists-p error-file))
1792 (if (< 0 (nth 7 (file-attributes error-file)))
1793 (with-current-buffer (get-buffer-create error-buffer)
1794 (let ((pos-from-end (- (point-max) (point))))
1795 (or (bobp)
1796 (insert "\f\n"))
1797 ;; Do no formatting while reading error file,
1798 ;; because that can run a shell command, and we
1799 ;; don't want that to cause an infinite recursion.
1800 (format-insert-file error-file nil)
1801 ;; Put point after the inserted errors.
1802 (goto-char (- (point-max) pos-from-end)))
1803 (display-buffer (current-buffer))))
1804 (delete-file error-file))
1805 exit-status))
1806
1807 (defun shell-command-to-string (command)
1808 "Execute shell command COMMAND and return its output as a string."
1809 (with-output-to-string
1810 (with-current-buffer
1811 standard-output
1812 (call-process shell-file-name nil t nil shell-command-switch command))))
1813 \f
1814 (defvar universal-argument-map
1815 (let ((map (make-sparse-keymap)))
1816 (define-key map [t] 'universal-argument-other-key)
1817 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
1818 (define-key map [switch-frame] nil)
1819 (define-key map [?\C-u] 'universal-argument-more)
1820 (define-key map [?-] 'universal-argument-minus)
1821 (define-key map [?0] 'digit-argument)
1822 (define-key map [?1] 'digit-argument)
1823 (define-key map [?2] 'digit-argument)
1824 (define-key map [?3] 'digit-argument)
1825 (define-key map [?4] 'digit-argument)
1826 (define-key map [?5] 'digit-argument)
1827 (define-key map [?6] 'digit-argument)
1828 (define-key map [?7] 'digit-argument)
1829 (define-key map [?8] 'digit-argument)
1830 (define-key map [?9] 'digit-argument)
1831 (define-key map [kp-0] 'digit-argument)
1832 (define-key map [kp-1] 'digit-argument)
1833 (define-key map [kp-2] 'digit-argument)
1834 (define-key map [kp-3] 'digit-argument)
1835 (define-key map [kp-4] 'digit-argument)
1836 (define-key map [kp-5] 'digit-argument)
1837 (define-key map [kp-6] 'digit-argument)
1838 (define-key map [kp-7] 'digit-argument)
1839 (define-key map [kp-8] 'digit-argument)
1840 (define-key map [kp-9] 'digit-argument)
1841 (define-key map [kp-subtract] 'universal-argument-minus)
1842 map)
1843 "Keymap used while processing \\[universal-argument].")
1844
1845 (defvar universal-argument-num-events nil
1846 "Number of argument-specifying events read by `universal-argument'.
1847 `universal-argument-other-key' uses this to discard those events
1848 from (this-command-keys), and reread only the final command.")
1849
1850 (defvar overriding-map-is-bound nil
1851 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
1852
1853 (defvar saved-overriding-map nil
1854 "The saved value of `overriding-terminal-local-map'.
1855 That variable gets restored to this value on exiting \"universal
1856 argument mode\".")
1857
1858 (defun ensure-overriding-map-is-bound ()
1859 "Check `overriding-terminal-local-map' is `universal-argument-map'."
1860 (unless overriding-map-is-bound
1861 (setq saved-overriding-map overriding-terminal-local-map)
1862 (setq overriding-terminal-local-map universal-argument-map)
1863 (setq overriding-map-is-bound t)))
1864
1865 (defun restore-overriding-map ()
1866 "Restore `overriding-terminal-local-map' to its saved value."
1867 (setq overriding-terminal-local-map saved-overriding-map)
1868 (setq overriding-map-is-bound nil))
1869
1870 (defun universal-argument ()
1871 "Begin a numeric argument for the following command.
1872 Digits or minus sign following \\[universal-argument] make up the numeric argument.
1873 \\[universal-argument] following the digits or minus sign ends the argument.
1874 \\[universal-argument] without digits or minus sign provides 4 as argument.
1875 Repeating \\[universal-argument] without digits or minus sign
1876 multiplies the argument by 4 each time.
1877 For some commands, just \\[universal-argument] by itself serves as a flag
1878 which is different in effect from any particular numeric argument.
1879 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
1880 (interactive)
1881 (setq prefix-arg (list 4))
1882 (setq universal-argument-num-events (length (this-command-keys)))
1883 (ensure-overriding-map-is-bound))
1884
1885 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
1886 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
1887 (defun universal-argument-more (arg)
1888 (interactive "P")
1889 (if (consp arg)
1890 (setq prefix-arg (list (* 4 (car arg))))
1891 (if (eq arg '-)
1892 (setq prefix-arg (list -4))
1893 (setq prefix-arg arg)
1894 (restore-overriding-map)))
1895 (setq universal-argument-num-events (length (this-command-keys))))
1896
1897 (defun negative-argument (arg)
1898 "Begin a negative numeric argument for the next command.
1899 \\[universal-argument] following digits or minus sign ends the argument."
1900 (interactive "P")
1901 (cond ((integerp arg)
1902 (setq prefix-arg (- arg)))
1903 ((eq arg '-)
1904 (setq prefix-arg nil))
1905 (t
1906 (setq prefix-arg '-)))
1907 (setq universal-argument-num-events (length (this-command-keys)))
1908 (ensure-overriding-map-is-bound))
1909
1910 (defun digit-argument (arg)
1911 "Part of the numeric argument for the next command.
1912 \\[universal-argument] following digits or minus sign ends the argument."
1913 (interactive "P")
1914 (let* ((char (if (integerp last-command-char)
1915 last-command-char
1916 (get last-command-char 'ascii-character)))
1917 (digit (- (logand char ?\177) ?0)))
1918 (cond ((integerp arg)
1919 (setq prefix-arg (+ (* arg 10)
1920 (if (< arg 0) (- digit) digit))))
1921 ((eq arg '-)
1922 ;; Treat -0 as just -, so that -01 will work.
1923 (setq prefix-arg (if (zerop digit) '- (- digit))))
1924 (t
1925 (setq prefix-arg digit))))
1926 (setq universal-argument-num-events (length (this-command-keys)))
1927 (ensure-overriding-map-is-bound))
1928
1929 ;; For backward compatibility, minus with no modifiers is an ordinary
1930 ;; command if digits have already been entered.
1931 (defun universal-argument-minus (arg)
1932 (interactive "P")
1933 (if (integerp arg)
1934 (universal-argument-other-key arg)
1935 (negative-argument arg)))
1936
1937 ;; Anything else terminates the argument and is left in the queue to be
1938 ;; executed as a command.
1939 (defun universal-argument-other-key (arg)
1940 (interactive "P")
1941 (setq prefix-arg arg)
1942 (let* ((key (this-command-keys))
1943 (keylist (listify-key-sequence key)))
1944 (setq unread-command-events
1945 (append (nthcdr universal-argument-num-events keylist)
1946 unread-command-events)))
1947 (reset-this-command-lengths)
1948 (restore-overriding-map))
1949 \f
1950 ;;;; Window system cut and paste hooks.
1951
1952 (defvar interprogram-cut-function nil
1953 "Function to call to make a killed region available to other programs.
1954
1955 Most window systems provide some sort of facility for cutting and
1956 pasting text between the windows of different programs.
1957 This variable holds a function that Emacs calls whenever text
1958 is put in the kill ring, to make the new kill available to other
1959 programs.
1960
1961 The function takes one or two arguments.
1962 The first argument, TEXT, is a string containing
1963 the text which should be made available.
1964 The second, optional, argument PUSH, has the same meaning as the
1965 similar argument to `x-set-cut-buffer', which see.")
1966
1967 (defvar interprogram-paste-function nil
1968 "Function to call to get text cut from other programs.
1969
1970 Most window systems provide some sort of facility for cutting and
1971 pasting text between the windows of different programs.
1972 This variable holds a function that Emacs calls to obtain
1973 text that other programs have provided for pasting.
1974
1975 The function should be called with no arguments. If the function
1976 returns nil, then no other program has provided such text, and the top
1977 of the Emacs kill ring should be used. If the function returns a
1978 string, then the caller of the function \(usually `current-kill')
1979 should put this string in the kill ring as the latest kill.
1980
1981 Note that the function should return a string only if a program other
1982 than Emacs has provided a string for pasting; if Emacs provided the
1983 most recent string, the function should return nil. If it is
1984 difficult to tell whether Emacs or some other program provided the
1985 current string, it is probably good enough to return nil if the string
1986 is equal (according to `string=') to the last text Emacs provided.")
1987 \f
1988
1989
1990 ;;;; The kill ring data structure.
1991
1992 (defvar kill-ring nil
1993 "List of killed text sequences.
1994 Since the kill ring is supposed to interact nicely with cut-and-paste
1995 facilities offered by window systems, use of this variable should
1996 interact nicely with `interprogram-cut-function' and
1997 `interprogram-paste-function'. The functions `kill-new',
1998 `kill-append', and `current-kill' are supposed to implement this
1999 interaction; you may want to use them instead of manipulating the kill
2000 ring directly.")
2001
2002 (defcustom kill-ring-max 60
2003 "*Maximum length of kill ring before oldest elements are thrown away."
2004 :type 'integer
2005 :group 'killing)
2006
2007 (defvar kill-ring-yank-pointer nil
2008 "The tail of the kill ring whose car is the last thing yanked.")
2009
2010 (defun kill-new (string &optional replace yank-handler)
2011 "Make STRING the latest kill in the kill ring.
2012 Set `kill-ring-yank-pointer' to point to it.
2013 If `interprogram-cut-function' is non-nil, apply it to STRING.
2014 Optional second argument REPLACE non-nil means that STRING will replace
2015 the front of the kill ring, rather than being added to the list.
2016
2017 Optional third arguments YANK-HANDLER controls how the STRING is later
2018 inserted into a buffer; see `insert-for-yank' for details.
2019 When a yank handler is specified, STRING must be non-empty (the yank
2020 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2021
2022 When the yank handler has a non-nil PARAM element, the original STRING
2023 argument is not used by `insert-for-yank'. However, since Lisp code
2024 may access and use elements from the kill-ring directly, the STRING
2025 argument should still be a \"useful\" string for such uses."
2026 (if (> (length string) 0)
2027 (if yank-handler
2028 (put-text-property 0 (length string)
2029 'yank-handler yank-handler string))
2030 (if yank-handler
2031 (signal 'args-out-of-range
2032 (list string "yank-handler specified for empty string"))))
2033 (if (fboundp 'menu-bar-update-yank-menu)
2034 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
2035 (if (and replace kill-ring)
2036 (setcar kill-ring string)
2037 (setq kill-ring (cons string kill-ring))
2038 (if (> (length kill-ring) kill-ring-max)
2039 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
2040 (setq kill-ring-yank-pointer kill-ring)
2041 (if interprogram-cut-function
2042 (funcall interprogram-cut-function string (not replace))))
2043
2044 (defun kill-append (string before-p &optional yank-handler)
2045 "Append STRING to the end of the latest kill in the kill ring.
2046 If BEFORE-P is non-nil, prepend STRING to the kill.
2047 Optional third argument YANK-HANDLER, if non-nil, specifies the
2048 yank-handler text property to be set on the combined kill ring
2049 string. If the specified yank-handler arg differs from the
2050 yank-handler property of the latest kill string, this function
2051 adds the combined string to the kill ring as a new element,
2052 instead of replacing the last kill with it.
2053 If `interprogram-cut-function' is set, pass the resulting kill to it."
2054 (let* ((cur (car kill-ring)))
2055 (kill-new (if before-p (concat string cur) (concat cur string))
2056 (or (= (length cur) 0)
2057 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2058 yank-handler)))
2059
2060 (defun current-kill (n &optional do-not-move)
2061 "Rotate the yanking point by N places, and then return that kill.
2062 If N is zero, `interprogram-paste-function' is set, and calling it
2063 returns a string, then that string is added to the front of the
2064 kill ring and returned as the latest kill.
2065 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
2066 yanking point; just return the Nth kill forward."
2067 (let ((interprogram-paste (and (= n 0)
2068 interprogram-paste-function
2069 (funcall interprogram-paste-function))))
2070 (if interprogram-paste
2071 (progn
2072 ;; Disable the interprogram cut function when we add the new
2073 ;; text to the kill ring, so Emacs doesn't try to own the
2074 ;; selection, with identical text.
2075 (let ((interprogram-cut-function nil))
2076 (kill-new interprogram-paste))
2077 interprogram-paste)
2078 (or kill-ring (error "Kill ring is empty"))
2079 (let ((ARGth-kill-element
2080 (nthcdr (mod (- n (length kill-ring-yank-pointer))
2081 (length kill-ring))
2082 kill-ring)))
2083 (or do-not-move
2084 (setq kill-ring-yank-pointer ARGth-kill-element))
2085 (car ARGth-kill-element)))))
2086
2087
2088
2089 ;;;; Commands for manipulating the kill ring.
2090
2091 (defcustom kill-read-only-ok nil
2092 "*Non-nil means don't signal an error for killing read-only text."
2093 :type 'boolean
2094 :group 'killing)
2095
2096 (put 'text-read-only 'error-conditions
2097 '(text-read-only buffer-read-only error))
2098 (put 'text-read-only 'error-message "Text is read-only")
2099
2100 (defun kill-region (beg end &optional yank-handler)
2101 "Kill between point and mark.
2102 The text is deleted but saved in the kill ring.
2103 The command \\[yank] can retrieve it from there.
2104 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
2105
2106 If you want to append the killed region to the last killed text,
2107 use \\[append-next-kill] before \\[kill-region].
2108
2109 If the buffer is read-only, Emacs will beep and refrain from deleting
2110 the text, but put the text in the kill ring anyway. This means that
2111 you can use the killing commands to copy text from a read-only buffer.
2112
2113 This is the primitive for programs to kill text (as opposed to deleting it).
2114 Supply two arguments, character positions indicating the stretch of text
2115 to be killed.
2116 Any command that calls this function is a \"kill command\".
2117 If the previous command was also a kill command,
2118 the text killed this time appends to the text killed last time
2119 to make one entry in the kill ring.
2120
2121 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
2122 specifies the yank-handler text property to be set on the killed
2123 text. See `insert-for-yank'."
2124 (interactive "r")
2125 (condition-case nil
2126 (let ((string (delete-and-extract-region beg end)))
2127 (when string ;STRING is nil if BEG = END
2128 ;; Add that string to the kill ring, one way or another.
2129 (if (eq last-command 'kill-region)
2130 (kill-append string (< end beg) yank-handler)
2131 (kill-new string nil yank-handler)))
2132 (when (or string (eq last-command 'kill-region))
2133 (setq this-command 'kill-region))
2134 nil)
2135 ((buffer-read-only text-read-only)
2136 ;; The code above failed because the buffer, or some of the characters
2137 ;; in the region, are read-only.
2138 ;; We should beep, in case the user just isn't aware of this.
2139 ;; However, there's no harm in putting
2140 ;; the region's text in the kill ring, anyway.
2141 (copy-region-as-kill beg end)
2142 ;; Set this-command now, so it will be set even if we get an error.
2143 (setq this-command 'kill-region)
2144 ;; This should barf, if appropriate, and give us the correct error.
2145 (if kill-read-only-ok
2146 (progn (message "Read only text copied to kill ring") nil)
2147 ;; Signal an error if the buffer is read-only.
2148 (barf-if-buffer-read-only)
2149 ;; If the buffer isn't read-only, the text is.
2150 (signal 'text-read-only (list (current-buffer)))))))
2151
2152 ;; copy-region-as-kill no longer sets this-command, because it's confusing
2153 ;; to get two copies of the text when the user accidentally types M-w and
2154 ;; then corrects it with the intended C-w.
2155 (defun copy-region-as-kill (beg end)
2156 "Save the region as if killed, but don't kill it.
2157 In Transient Mark mode, deactivate the mark.
2158 If `interprogram-cut-function' is non-nil, also save the text for a window
2159 system cut and paste."
2160 (interactive "r")
2161 (if (eq last-command 'kill-region)
2162 (kill-append (buffer-substring beg end) (< end beg))
2163 (kill-new (buffer-substring beg end)))
2164 (if transient-mark-mode
2165 (setq deactivate-mark t))
2166 nil)
2167
2168 (defun kill-ring-save (beg end)
2169 "Save the region as if killed, but don't kill it.
2170 In Transient Mark mode, deactivate the mark.
2171 If `interprogram-cut-function' is non-nil, also save the text for a window
2172 system cut and paste.
2173
2174 If you want to append the killed line to the last killed text,
2175 use \\[append-next-kill] before \\[kill-ring-save].
2176
2177 This command is similar to `copy-region-as-kill', except that it gives
2178 visual feedback indicating the extent of the region being copied."
2179 (interactive "r")
2180 (copy-region-as-kill beg end)
2181 (if (interactive-p)
2182 (let ((other-end (if (= (point) beg) end beg))
2183 (opoint (point))
2184 ;; Inhibit quitting so we can make a quit here
2185 ;; look like a C-g typed as a command.
2186 (inhibit-quit t))
2187 (if (pos-visible-in-window-p other-end (selected-window))
2188 (unless (and transient-mark-mode
2189 (face-background 'region))
2190 ;; Swap point and mark.
2191 (set-marker (mark-marker) (point) (current-buffer))
2192 (goto-char other-end)
2193 (sit-for blink-matching-delay)
2194 ;; Swap back.
2195 (set-marker (mark-marker) other-end (current-buffer))
2196 (goto-char opoint)
2197 ;; If user quit, deactivate the mark
2198 ;; as C-g would as a command.
2199 (and quit-flag mark-active
2200 (deactivate-mark)))
2201 (let* ((killed-text (current-kill 0))
2202 (message-len (min (length killed-text) 40)))
2203 (if (= (point) beg)
2204 ;; Don't say "killed"; that is misleading.
2205 (message "Saved text until \"%s\""
2206 (substring killed-text (- message-len)))
2207 (message "Saved text from \"%s\""
2208 (substring killed-text 0 message-len))))))))
2209
2210 (defun append-next-kill (&optional interactive)
2211 "Cause following command, if it kills, to append to previous kill.
2212 The argument is used for internal purposes; do not supply one."
2213 (interactive "p")
2214 ;; We don't use (interactive-p), since that breaks kbd macros.
2215 (if interactive
2216 (progn
2217 (setq this-command 'kill-region)
2218 (message "If the next command is a kill, it will append"))
2219 (setq last-command 'kill-region)))
2220 \f
2221 ;; Yanking.
2222
2223 ;; This is actually used in subr.el but defcustom does not work there.
2224 (defcustom yank-excluded-properties
2225 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2226 yank-handler)
2227 "*Text properties to discard when yanking.
2228 The value should be a list of text properties to discard or t,
2229 which means to discard all text properties."
2230 :type '(choice (const :tag "All" t) (repeat symbol))
2231 :group 'killing
2232 :version "21.4")
2233
2234 (defvar yank-window-start nil)
2235 (defvar yank-undo-function nil
2236 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2237 Function is called with two parameters, START and END corresponding to
2238 the value of the mark and point; it is guaranteed that START <= END.
2239 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
2240
2241 (defun yank-pop (&optional arg)
2242 "Replace just-yanked stretch of killed text with a different stretch.
2243 This command is allowed only immediately after a `yank' or a `yank-pop'.
2244 At such a time, the region contains a stretch of reinserted
2245 previously-killed text. `yank-pop' deletes that text and inserts in its
2246 place a different stretch of killed text.
2247
2248 With no argument, the previous kill is inserted.
2249 With argument N, insert the Nth previous kill.
2250 If N is negative, this is a more recent kill.
2251
2252 The sequence of kills wraps around, so that after the oldest one
2253 comes the newest one."
2254 (interactive "*p")
2255 (if (not (eq last-command 'yank))
2256 (error "Previous command was not a yank"))
2257 (setq this-command 'yank)
2258 (unless arg (setq arg 1))
2259 (let ((inhibit-read-only t)
2260 (before (< (point) (mark t))))
2261 (if before
2262 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2263 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
2264 (setq yank-undo-function nil)
2265 (set-marker (mark-marker) (point) (current-buffer))
2266 (insert-for-yank (current-kill arg))
2267 ;; Set the window start back where it was in the yank command,
2268 ;; if possible.
2269 (set-window-start (selected-window) yank-window-start t)
2270 (if before
2271 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2272 ;; It is cleaner to avoid activation, even though the command
2273 ;; loop would deactivate the mark because we inserted text.
2274 (goto-char (prog1 (mark t)
2275 (set-marker (mark-marker) (point) (current-buffer))))))
2276 nil)
2277
2278 (defun yank (&optional arg)
2279 "Reinsert the last stretch of killed text.
2280 More precisely, reinsert the stretch of killed text most recently
2281 killed OR yanked. Put point at end, and set mark at beginning.
2282 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
2283 With argument N, reinsert the Nth most recently killed stretch of killed
2284 text.
2285 See also the command \\[yank-pop]."
2286 (interactive "*P")
2287 (setq yank-window-start (window-start))
2288 ;; If we don't get all the way thru, make last-command indicate that
2289 ;; for the following command.
2290 (setq this-command t)
2291 (push-mark (point))
2292 (insert-for-yank (current-kill (cond
2293 ((listp arg) 0)
2294 ((eq arg '-) -2)
2295 (t (1- arg)))))
2296 (if (consp arg)
2297 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2298 ;; It is cleaner to avoid activation, even though the command
2299 ;; loop would deactivate the mark because we inserted text.
2300 (goto-char (prog1 (mark t)
2301 (set-marker (mark-marker) (point) (current-buffer)))))
2302 ;; If we do get all the way thru, make this-command indicate that.
2303 (if (eq this-command t)
2304 (setq this-command 'yank))
2305 nil)
2306
2307 (defun rotate-yank-pointer (arg)
2308 "Rotate the yanking point in the kill ring.
2309 With argument, rotate that many kills forward (or backward, if negative)."
2310 (interactive "p")
2311 (current-kill arg))
2312 \f
2313 ;; Some kill commands.
2314
2315 ;; Internal subroutine of delete-char
2316 (defun kill-forward-chars (arg)
2317 (if (listp arg) (setq arg (car arg)))
2318 (if (eq arg '-) (setq arg -1))
2319 (kill-region (point) (forward-point arg)))
2320
2321 ;; Internal subroutine of backward-delete-char
2322 (defun kill-backward-chars (arg)
2323 (if (listp arg) (setq arg (car arg)))
2324 (if (eq arg '-) (setq arg -1))
2325 (kill-region (point) (forward-point (- arg))))
2326
2327 (defcustom backward-delete-char-untabify-method 'untabify
2328 "*The method for untabifying when deleting backward.
2329 Can be `untabify' -- turn a tab to many spaces, then delete one space;
2330 `hungry' -- delete all whitespace, both tabs and spaces;
2331 `all' -- delete all whitespace, including tabs, spaces and newlines;
2332 nil -- just delete one character."
2333 :type '(choice (const untabify) (const hungry) (const all) (const nil))
2334 :version "20.3"
2335 :group 'killing)
2336
2337 (defun backward-delete-char-untabify (arg &optional killp)
2338 "Delete characters backward, changing tabs into spaces.
2339 The exact behavior depends on `backward-delete-char-untabify-method'.
2340 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
2341 Interactively, ARG is the prefix arg (default 1)
2342 and KILLP is t if a prefix arg was specified."
2343 (interactive "*p\nP")
2344 (when (eq backward-delete-char-untabify-method 'untabify)
2345 (let ((count arg))
2346 (save-excursion
2347 (while (and (> count 0) (not (bobp)))
2348 (if (= (preceding-char) ?\t)
2349 (let ((col (current-column)))
2350 (forward-char -1)
2351 (setq col (- col (current-column)))
2352 (insert-char ?\ col)
2353 (delete-char 1)))
2354 (forward-char -1)
2355 (setq count (1- count))))))
2356 (delete-backward-char
2357 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
2358 ((eq backward-delete-char-untabify-method 'all)
2359 " \t\n\r"))))
2360 (if skip
2361 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
2362 (point)))))
2363 (+ arg (if (zerop wh) 0 (1- wh))))
2364 arg))
2365 killp))
2366
2367 (defun zap-to-char (arg char)
2368 "Kill up to and including ARG'th occurrence of CHAR.
2369 Case is ignored if `case-fold-search' is non-nil in the current buffer.
2370 Goes backward if ARG is negative; error if CHAR not found."
2371 (interactive "p\ncZap to char: ")
2372 (kill-region (point) (progn
2373 (search-forward (char-to-string char) nil nil arg)
2374 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
2375 (point))))
2376
2377 ;; kill-line and its subroutines.
2378
2379 (defcustom kill-whole-line nil
2380 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
2381 :type 'boolean
2382 :group 'killing)
2383
2384 (defun kill-line (&optional arg)
2385 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
2386 With prefix argument, kill that many lines from point.
2387 Negative arguments kill lines backward.
2388 With zero argument, kills the text before point on the current line.
2389
2390 When calling from a program, nil means \"no arg\",
2391 a number counts as a prefix arg.
2392
2393 To kill a whole line, when point is not at the beginning, type \
2394 \\[beginning-of-line] \\[kill-line] \\[kill-line].
2395
2396 If `kill-whole-line' is non-nil, then this command kills the whole line
2397 including its terminating newline, when used at the beginning of a line
2398 with no argument. As a consequence, you can always kill a whole line
2399 by typing \\[beginning-of-line] \\[kill-line].
2400
2401 If you want to append the killed line to the last killed text,
2402 use \\[append-next-kill] before \\[kill-line].
2403
2404 If the buffer is read-only, Emacs will beep and refrain from deleting
2405 the line, but put the line in the kill ring anyway. This means that
2406 you can use this command to copy text from a read-only buffer.
2407 \(If the variable `kill-read-only-ok' is non-nil, then this won't
2408 even beep.)"
2409 (interactive "P")
2410 (kill-region (point)
2411 ;; It is better to move point to the other end of the kill
2412 ;; before killing. That way, in a read-only buffer, point
2413 ;; moves across the text that is copied to the kill ring.
2414 ;; The choice has no effect on undo now that undo records
2415 ;; the value of point from before the command was run.
2416 (progn
2417 (if arg
2418 (forward-visible-line (prefix-numeric-value arg))
2419 (if (eobp)
2420 (signal 'end-of-buffer nil))
2421 (let ((end
2422 (save-excursion
2423 (end-of-visible-line) (point))))
2424 (if (or (save-excursion
2425 ;; If trailing whitespace is visible,
2426 ;; don't treat it as nothing.
2427 (unless show-trailing-whitespace
2428 (skip-chars-forward " \t" end))
2429 (= (point) end))
2430 (and kill-whole-line (bolp)))
2431 (forward-visible-line 1)
2432 (goto-char end))))
2433 (point))))
2434
2435 (defun kill-whole-line (&optional arg)
2436 "Kill current line.
2437 With prefix arg, kill that many lines starting from the current line.
2438 If arg is negative, kill backward. Also kill the preceding newline.
2439 \(This is meant to make C-x z work well with negative arguments.\)
2440 If arg is zero, kill current line but exclude the trailing newline."
2441 (interactive "p")
2442 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
2443 (signal 'end-of-buffer nil))
2444 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
2445 (signal 'beginning-of-buffer nil))
2446 (unless (eq last-command 'kill-region)
2447 (kill-new "")
2448 (setq last-command 'kill-region))
2449 (cond ((zerop arg)
2450 ;; We need to kill in two steps, because the previous command
2451 ;; could have been a kill command, in which case the text
2452 ;; before point needs to be prepended to the current kill
2453 ;; ring entry and the text after point appended. Also, we
2454 ;; need to use save-excursion to avoid copying the same text
2455 ;; twice to the kill ring in read-only buffers.
2456 (save-excursion
2457 (kill-region (point) (progn (forward-visible-line 0) (point))))
2458 (kill-region (point) (progn (end-of-visible-line) (point))))
2459 ((< arg 0)
2460 (save-excursion
2461 (kill-region (point) (progn (end-of-visible-line) (point))))
2462 (kill-region (point)
2463 (progn (forward-visible-line (1+ arg))
2464 (unless (bobp) (backward-char))
2465 (point))))
2466 (t
2467 (save-excursion
2468 (kill-region (point) (progn (forward-visible-line 0) (point))))
2469 (kill-region (point)
2470 (progn (forward-visible-line arg) (point))))))
2471
2472 (defun forward-visible-line (arg)
2473 "Move forward by ARG lines, ignoring currently invisible newlines only.
2474 If ARG is negative, move backward -ARG lines.
2475 If ARG is zero, move to the beginning of the current line."
2476 (condition-case nil
2477 (if (> arg 0)
2478 (progn
2479 (while (> arg 0)
2480 (or (zerop (forward-line 1))
2481 (signal 'end-of-buffer nil))
2482 ;; If the newline we just skipped is invisible,
2483 ;; don't count it.
2484 (let ((prop
2485 (get-char-property (1- (point)) 'invisible)))
2486 (if (if (eq buffer-invisibility-spec t)
2487 prop
2488 (or (memq prop buffer-invisibility-spec)
2489 (assq prop buffer-invisibility-spec)))
2490 (setq arg (1+ arg))))
2491 (setq arg (1- arg)))
2492 ;; If invisible text follows, and it is a number of complete lines,
2493 ;; skip it.
2494 (let ((opoint (point)))
2495 (while (and (not (eobp))
2496 (let ((prop
2497 (get-char-property (point) 'invisible)))
2498 (if (eq buffer-invisibility-spec t)
2499 prop
2500 (or (memq prop buffer-invisibility-spec)
2501 (assq prop buffer-invisibility-spec)))))
2502 (goto-char
2503 (if (get-text-property (point) 'invisible)
2504 (or (next-single-property-change (point) 'invisible)
2505 (point-max))
2506 (next-overlay-change (point)))))
2507 (unless (bolp)
2508 (goto-char opoint))))
2509 (let ((first t))
2510 (while (or first (<= arg 0))
2511 (if first
2512 (beginning-of-line)
2513 (or (zerop (forward-line -1))
2514 (signal 'beginning-of-buffer nil)))
2515 ;; If the newline we just moved to is invisible,
2516 ;; don't count it.
2517 (unless (bobp)
2518 (let ((prop
2519 (get-char-property (1- (point)) 'invisible)))
2520 (unless (if (eq buffer-invisibility-spec t)
2521 prop
2522 (or (memq prop buffer-invisibility-spec)
2523 (assq prop buffer-invisibility-spec)))
2524 (setq arg (1+ arg)))))
2525 (setq first nil))
2526 ;; If invisible text follows, and it is a number of complete lines,
2527 ;; skip it.
2528 (let ((opoint (point)))
2529 (while (and (not (bobp))
2530 (let ((prop
2531 (get-char-property (1- (point)) 'invisible)))
2532 (if (eq buffer-invisibility-spec t)
2533 prop
2534 (or (memq prop buffer-invisibility-spec)
2535 (assq prop buffer-invisibility-spec)))))
2536 (goto-char
2537 (if (get-text-property (1- (point)) 'invisible)
2538 (or (previous-single-property-change (point) 'invisible)
2539 (point-min))
2540 (previous-overlay-change (point)))))
2541 (unless (bolp)
2542 (goto-char opoint)))))
2543 ((beginning-of-buffer end-of-buffer)
2544 nil)))
2545
2546 (defun end-of-visible-line ()
2547 "Move to end of current visible line."
2548 (end-of-line)
2549 ;; If the following character is currently invisible,
2550 ;; skip all characters with that same `invisible' property value,
2551 ;; then find the next newline.
2552 (while (and (not (eobp))
2553 (save-excursion
2554 (skip-chars-forward "^\n")
2555 (let ((prop
2556 (get-char-property (point) 'invisible)))
2557 (if (eq buffer-invisibility-spec t)
2558 prop
2559 (or (memq prop buffer-invisibility-spec)
2560 (assq prop buffer-invisibility-spec))))))
2561 (skip-chars-forward "^\n")
2562 (if (get-text-property (point) 'invisible)
2563 (goto-char (next-single-property-change (point) 'invisible))
2564 (goto-char (next-overlay-change (point))))
2565 (end-of-line)))
2566 \f
2567 (defun insert-buffer (buffer)
2568 "Insert after point the contents of BUFFER.
2569 Puts mark after the inserted text.
2570 BUFFER may be a buffer or a buffer name.
2571
2572 This function is meant for the user to run interactively.
2573 Don't call it from programs: use `insert-buffer-substring' instead!"
2574 (interactive
2575 (list
2576 (progn
2577 (barf-if-buffer-read-only)
2578 (read-buffer "Insert buffer: "
2579 (if (eq (selected-window) (next-window (selected-window)))
2580 (other-buffer (current-buffer))
2581 (window-buffer (next-window (selected-window))))
2582 t))))
2583 (push-mark
2584 (save-excursion
2585 (insert-buffer-substring (get-buffer buffer))
2586 (point)))
2587 nil)
2588
2589 (defun append-to-buffer (buffer start end)
2590 "Append to specified buffer the text of the region.
2591 It is inserted into that buffer before its point.
2592
2593 When calling from a program, give three arguments:
2594 BUFFER (or buffer name), START and END.
2595 START and END specify the portion of the current buffer to be copied."
2596 (interactive
2597 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
2598 (region-beginning) (region-end)))
2599 (let ((oldbuf (current-buffer)))
2600 (save-excursion
2601 (let* ((append-to (get-buffer-create buffer))
2602 (windows (get-buffer-window-list append-to t t))
2603 point)
2604 (set-buffer append-to)
2605 (setq point (point))
2606 (barf-if-buffer-read-only)
2607 (insert-buffer-substring oldbuf start end)
2608 (dolist (window windows)
2609 (when (= (window-point window) point)
2610 (set-window-point window (point))))))))
2611
2612 (defun prepend-to-buffer (buffer start end)
2613 "Prepend to specified buffer the text of the region.
2614 It is inserted into that buffer after its point.
2615
2616 When calling from a program, give three arguments:
2617 BUFFER (or buffer name), START and END.
2618 START and END specify the portion of the current buffer to be copied."
2619 (interactive "BPrepend to buffer: \nr")
2620 (let ((oldbuf (current-buffer)))
2621 (save-excursion
2622 (set-buffer (get-buffer-create buffer))
2623 (barf-if-buffer-read-only)
2624 (save-excursion
2625 (insert-buffer-substring oldbuf start end)))))
2626
2627 (defun copy-to-buffer (buffer start end)
2628 "Copy to specified buffer the text of the region.
2629 It is inserted into that buffer, replacing existing text there.
2630
2631 When calling from a program, give three arguments:
2632 BUFFER (or buffer name), START and END.
2633 START and END specify the portion of the current buffer to be copied."
2634 (interactive "BCopy to buffer: \nr")
2635 (let ((oldbuf (current-buffer)))
2636 (save-excursion
2637 (set-buffer (get-buffer-create buffer))
2638 (barf-if-buffer-read-only)
2639 (erase-buffer)
2640 (save-excursion
2641 (insert-buffer-substring oldbuf start end)))))
2642 \f
2643 (put 'mark-inactive 'error-conditions '(mark-inactive error))
2644 (put 'mark-inactive 'error-message "The mark is not active now")
2645
2646 (defun mark (&optional force)
2647 "Return this buffer's mark value as integer; error if mark inactive.
2648 If optional argument FORCE is non-nil, access the mark value
2649 even if the mark is not currently active, and return nil
2650 if there is no mark at all.
2651
2652 If you are using this in an editing command, you are most likely making
2653 a mistake; see the documentation of `set-mark'."
2654 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
2655 (marker-position (mark-marker))
2656 (signal 'mark-inactive nil)))
2657
2658 ;; Many places set mark-active directly, and several of them failed to also
2659 ;; run deactivate-mark-hook. This shorthand should simplify.
2660 (defsubst deactivate-mark ()
2661 "Deactivate the mark by setting `mark-active' to nil.
2662 \(That makes a difference only in Transient Mark mode.)
2663 Also runs the hook `deactivate-mark-hook'."
2664 (cond
2665 ((eq transient-mark-mode 'lambda)
2666 (setq transient-mark-mode nil))
2667 (transient-mark-mode
2668 (setq mark-active nil)
2669 (run-hooks 'deactivate-mark-hook))))
2670
2671 (defun set-mark (pos)
2672 "Set this buffer's mark to POS. Don't use this function!
2673 That is to say, don't use this function unless you want
2674 the user to see that the mark has moved, and you want the previous
2675 mark position to be lost.
2676
2677 Normally, when a new mark is set, the old one should go on the stack.
2678 This is why most applications should use push-mark, not set-mark.
2679
2680 Novice Emacs Lisp programmers often try to use the mark for the wrong
2681 purposes. The mark saves a location for the user's convenience.
2682 Most editing commands should not alter the mark.
2683 To remember a location for internal use in the Lisp program,
2684 store it in a Lisp variable. Example:
2685
2686 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
2687
2688 (if pos
2689 (progn
2690 (setq mark-active t)
2691 (run-hooks 'activate-mark-hook)
2692 (set-marker (mark-marker) pos (current-buffer)))
2693 ;; Normally we never clear mark-active except in Transient Mark mode.
2694 ;; But when we actually clear out the mark value too,
2695 ;; we must clear mark-active in any mode.
2696 (setq mark-active nil)
2697 (run-hooks 'deactivate-mark-hook)
2698 (set-marker (mark-marker) nil)))
2699
2700 (defvar mark-ring nil
2701 "The list of former marks of the current buffer, most recent first.")
2702 (make-variable-buffer-local 'mark-ring)
2703 (put 'mark-ring 'permanent-local t)
2704
2705 (defcustom mark-ring-max 16
2706 "*Maximum size of mark ring. Start discarding off end if gets this big."
2707 :type 'integer
2708 :group 'editing-basics)
2709
2710 (defvar global-mark-ring nil
2711 "The list of saved global marks, most recent first.")
2712
2713 (defcustom global-mark-ring-max 16
2714 "*Maximum size of global mark ring. \
2715 Start discarding off end if gets this big."
2716 :type 'integer
2717 :group 'editing-basics)
2718
2719 (defun pop-to-mark-command ()
2720 "Jump to mark, and pop a new position for mark off the ring
2721 \(does not affect global mark ring\)."
2722 (interactive)
2723 (if (null (mark t))
2724 (error "No mark set in this buffer")
2725 (goto-char (mark t))
2726 (pop-mark)))
2727
2728 (defun push-mark-command (arg &optional nomsg)
2729 "Set mark at where point is.
2730 If no prefix arg and mark is already set there, just activate it.
2731 Display `Mark set' unless the optional second arg NOMSG is non-nil."
2732 (interactive "P")
2733 (let ((mark (marker-position (mark-marker))))
2734 (if (or arg (null mark) (/= mark (point)))
2735 (push-mark nil nomsg t)
2736 (setq mark-active t)
2737 (unless nomsg
2738 (message "Mark activated")))))
2739
2740 (defun set-mark-command (arg)
2741 "Set mark at where point is, or jump to mark.
2742 With no prefix argument, set mark, and push old mark position on local
2743 mark ring; also push mark on global mark ring if last mark was set in
2744 another buffer. Immediately repeating the command activates
2745 `transient-mark-mode' temporarily.
2746
2747 With argument, e.g. \\[universal-argument] \\[set-mark-command], \
2748 jump to mark, and pop a new position
2749 for mark off the local mark ring \(this does not affect the global
2750 mark ring\). Use \\[pop-global-mark] to jump to a mark off the global
2751 mark ring \(see `pop-global-mark'\).
2752
2753 Repeating the \\[set-mark-command] command without the prefix jumps to
2754 the next position off the local (or global) mark ring.
2755
2756 With a double \\[universal-argument] prefix argument, e.g. \\[universal-argument] \
2757 \\[universal-argument] \\[set-mark-command], unconditionally
2758 set mark where point is.
2759
2760 Novice Emacs Lisp programmers often try to use the mark for the wrong
2761 purposes. See the documentation of `set-mark' for more information."
2762 (interactive "P")
2763 (if (eq transient-mark-mode 'lambda)
2764 (setq transient-mark-mode nil))
2765 (cond
2766 ((and (consp arg) (> (prefix-numeric-value arg) 4))
2767 (push-mark-command nil))
2768 ((not (eq this-command 'set-mark-command))
2769 (if arg
2770 (pop-to-mark-command)
2771 (push-mark-command t)))
2772 ((eq last-command 'pop-to-mark-command)
2773 (setq this-command 'pop-to-mark-command)
2774 (pop-to-mark-command))
2775 ((and (eq last-command 'pop-global-mark) (not arg))
2776 (setq this-command 'pop-global-mark)
2777 (pop-global-mark))
2778 (arg
2779 (setq this-command 'pop-to-mark-command)
2780 (pop-to-mark-command))
2781 ((and (eq last-command 'set-mark-command)
2782 mark-active (null transient-mark-mode))
2783 (setq transient-mark-mode 'lambda)
2784 (message "Transient-mark-mode temporarily enabled"))
2785 (t
2786 (push-mark-command nil))))
2787
2788 (defun push-mark (&optional location nomsg activate)
2789 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
2790 If the last global mark pushed was not in the current buffer,
2791 also push LOCATION on the global mark ring.
2792 Display `Mark set' unless the optional second arg NOMSG is non-nil.
2793 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
2794
2795 Novice Emacs Lisp programmers often try to use the mark for the wrong
2796 purposes. See the documentation of `set-mark' for more information.
2797
2798 In Transient Mark mode, this does not activate the mark."
2799 (unless (null (mark t))
2800 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
2801 (when (> (length mark-ring) mark-ring-max)
2802 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
2803 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
2804 (set-marker (mark-marker) (or location (point)) (current-buffer))
2805 ;; Now push the mark on the global mark ring.
2806 (if (and global-mark-ring
2807 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
2808 ;; The last global mark pushed was in this same buffer.
2809 ;; Don't push another one.
2810 nil
2811 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
2812 (when (> (length global-mark-ring) global-mark-ring-max)
2813 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
2814 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
2815 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
2816 (message "Mark set"))
2817 (if (or activate (not transient-mark-mode))
2818 (set-mark (mark t)))
2819 nil)
2820
2821 (defun pop-mark ()
2822 "Pop off mark ring into the buffer's actual mark.
2823 Does not set point. Does nothing if mark ring is empty."
2824 (when mark-ring
2825 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
2826 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
2827 (deactivate-mark)
2828 (move-marker (car mark-ring) nil)
2829 (if (null (mark t)) (ding))
2830 (setq mark-ring (cdr mark-ring))))
2831
2832 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
2833 (defun exchange-point-and-mark (&optional arg)
2834 "Put the mark where point is now, and point where the mark is now.
2835 This command works even when the mark is not active,
2836 and it reactivates the mark.
2837 With prefix arg, `transient-mark-mode' is enabled temporarily."
2838 (interactive "P")
2839 (if arg
2840 (if mark-active
2841 (if (null transient-mark-mode)
2842 (setq transient-mark-mode 'lambda))
2843 (setq arg nil)))
2844 (unless arg
2845 (let ((omark (mark t)))
2846 (if (null omark)
2847 (error "No mark set in this buffer"))
2848 (set-mark (point))
2849 (goto-char omark)
2850 nil)))
2851
2852 (define-minor-mode transient-mark-mode
2853 "Toggle Transient Mark mode.
2854 With arg, turn Transient Mark mode on if arg is positive, off otherwise.
2855
2856 In Transient Mark mode, when the mark is active, the region is highlighted.
2857 Changing the buffer \"deactivates\" the mark.
2858 So do certain other operations that set the mark
2859 but whose main purpose is something else--for example,
2860 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
2861
2862 You can also deactivate the mark by typing \\[keyboard-quit] or
2863 \\[keyboard-escape-quit].
2864
2865 Many commands change their behavior when Transient Mark mode is in effect
2866 and the mark is active, by acting on the region instead of their usual
2867 default part of the buffer's text. Examples of such commands include
2868 \\[comment-dwim], \\[flush-lines], \\[ispell], \\[keep-lines],
2869 \\[query-replace], \\[query-replace-regexp], and \\[undo]. Invoke
2870 \\[apropos-documentation] and type \"transient\" or \"mark.*active\" at
2871 the prompt, to see the documentation of commands which are sensitive to
2872 the Transient Mark mode."
2873 :global t :group 'editing-basics :require nil)
2874
2875 (defun pop-global-mark ()
2876 "Pop off global mark ring and jump to the top location."
2877 (interactive)
2878 ;; Pop entries which refer to non-existent buffers.
2879 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
2880 (setq global-mark-ring (cdr global-mark-ring)))
2881 (or global-mark-ring
2882 (error "No global mark set"))
2883 (let* ((marker (car global-mark-ring))
2884 (buffer (marker-buffer marker))
2885 (position (marker-position marker)))
2886 (setq global-mark-ring (nconc (cdr global-mark-ring)
2887 (list (car global-mark-ring))))
2888 (set-buffer buffer)
2889 (or (and (>= position (point-min))
2890 (<= position (point-max)))
2891 (widen))
2892 (goto-char position)
2893 (switch-to-buffer buffer)))
2894 \f
2895 (defcustom next-line-add-newlines nil
2896 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
2897 :type 'boolean
2898 :version "21.1"
2899 :group 'editing-basics)
2900
2901 (defun next-line (&optional arg)
2902 "Move cursor vertically down ARG lines.
2903 If there is no character in the target line exactly under the current column,
2904 the cursor is positioned after the character in that line which spans this
2905 column, or at the end of the line if it is not long enough.
2906 If there is no line in the buffer after this one, behavior depends on the
2907 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
2908 to create a line, and moves the cursor to that line. Otherwise it moves the
2909 cursor to the end of the buffer.
2910
2911 The command \\[set-goal-column] can be used to create
2912 a semipermanent goal column for this command.
2913 Then instead of trying to move exactly vertically (or as close as possible),
2914 this command moves to the specified goal column (or as close as possible).
2915 The goal column is stored in the variable `goal-column', which is nil
2916 when there is no goal column.
2917
2918 If you are thinking of using this in a Lisp program, consider
2919 using `forward-line' instead. It is usually easier to use
2920 and more reliable (no dependence on goal column, etc.)."
2921 (interactive "p")
2922 (or arg (setq arg 1))
2923 (if (and next-line-add-newlines (= arg 1))
2924 (if (save-excursion (end-of-line) (eobp))
2925 ;; When adding a newline, don't expand an abbrev.
2926 (let ((abbrev-mode nil))
2927 (end-of-line)
2928 (insert "\n"))
2929 (line-move arg))
2930 (if (interactive-p)
2931 (condition-case nil
2932 (line-move arg)
2933 ((beginning-of-buffer end-of-buffer) (ding)))
2934 (line-move arg)))
2935 nil)
2936
2937 (defun previous-line (&optional arg)
2938 "Move cursor vertically up ARG lines.
2939 If there is no character in the target line exactly over the current column,
2940 the cursor is positioned after the character in that line which spans this
2941 column, or at the end of the line if it is not long enough.
2942
2943 The command \\[set-goal-column] can be used to create
2944 a semipermanent goal column for this command.
2945 Then instead of trying to move exactly vertically (or as close as possible),
2946 this command moves to the specified goal column (or as close as possible).
2947 The goal column is stored in the variable `goal-column', which is nil
2948 when there is no goal column.
2949
2950 If you are thinking of using this in a Lisp program, consider using
2951 `forward-line' with a negative argument instead. It is usually easier
2952 to use and more reliable (no dependence on goal column, etc.)."
2953 (interactive "p")
2954 (or arg (setq arg 1))
2955 (if (interactive-p)
2956 (condition-case nil
2957 (line-move (- arg))
2958 ((beginning-of-buffer end-of-buffer) (ding)))
2959 (line-move (- arg)))
2960 nil)
2961
2962 (defcustom track-eol nil
2963 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
2964 This means moving to the end of each line moved onto.
2965 The beginning of a blank line does not count as the end of a line."
2966 :type 'boolean
2967 :group 'editing-basics)
2968
2969 (defcustom goal-column nil
2970 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
2971 :type '(choice integer
2972 (const :tag "None" nil))
2973 :group 'editing-basics)
2974 (make-variable-buffer-local 'goal-column)
2975
2976 (defvar temporary-goal-column 0
2977 "Current goal column for vertical motion.
2978 It is the column where point was
2979 at the start of current run of vertical motion commands.
2980 When the `track-eol' feature is doing its job, the value is 9999.")
2981
2982 (defcustom line-move-ignore-invisible nil
2983 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
2984 Outline mode sets this."
2985 :type 'boolean
2986 :group 'editing-basics)
2987
2988 (defun line-move-invisible (pos)
2989 "Return non-nil if the character after POS is currently invisible."
2990 (let ((prop
2991 (get-char-property pos 'invisible)))
2992 (if (eq buffer-invisibility-spec t)
2993 prop
2994 (or (memq prop buffer-invisibility-spec)
2995 (assq prop buffer-invisibility-spec)))))
2996
2997 ;; This is the guts of next-line and previous-line.
2998 ;; Arg says how many lines to move.
2999 (defun line-move (arg)
3000 ;; Don't run any point-motion hooks, and disregard intangibility,
3001 ;; for intermediate positions.
3002 (let ((inhibit-point-motion-hooks t)
3003 (opoint (point))
3004 new line-end line-beg)
3005 (unwind-protect
3006 (progn
3007 (if (not (memq last-command '(next-line previous-line)))
3008 (setq temporary-goal-column
3009 (if (and track-eol (eolp)
3010 ;; Don't count beg of empty line as end of line
3011 ;; unless we just did explicit end-of-line.
3012 (or (not (bolp)) (eq last-command 'end-of-line)))
3013 9999
3014 (current-column))))
3015 (if (and (not (integerp selective-display))
3016 (not line-move-ignore-invisible))
3017 ;; Use just newline characters.
3018 ;; Set ARG to 0 if we move as many lines as requested.
3019 (or (if (> arg 0)
3020 (progn (if (> arg 1) (forward-line (1- arg)))
3021 ;; This way of moving forward ARG lines
3022 ;; verifies that we have a newline after the last one.
3023 ;; It doesn't get confused by intangible text.
3024 (end-of-line)
3025 (if (zerop (forward-line 1))
3026 (setq arg 0)))
3027 (and (zerop (forward-line arg))
3028 (bolp)
3029 (setq arg 0)))
3030 (signal (if (< arg 0)
3031 'beginning-of-buffer
3032 'end-of-buffer)
3033 nil))
3034 ;; Move by arg lines, but ignore invisible ones.
3035 (while (> arg 0)
3036 ;; If the following character is currently invisible,
3037 ;; skip all characters with that same `invisible' property value.
3038 (while (and (not (eobp)) (line-move-invisible (point)))
3039 (goto-char (next-char-property-change (point))))
3040 ;; Now move a line.
3041 (end-of-line)
3042 (and (zerop (vertical-motion 1))
3043 (signal 'end-of-buffer nil))
3044 (setq arg (1- arg)))
3045 (while (< arg 0)
3046 (beginning-of-line)
3047 (and (zerop (vertical-motion -1))
3048 (signal 'beginning-of-buffer nil))
3049 (setq arg (1+ arg))
3050 (while (and (not (bobp)) (line-move-invisible (1- (point))))
3051 (goto-char (previous-char-property-change (point)))))))
3052
3053 (cond ((> arg 0)
3054 ;; If we did not move down as far as desired,
3055 ;; at least go to end of line.
3056 (end-of-line))
3057 ((< arg 0)
3058 ;; If we did not move down as far as desired,
3059 ;; at least go to end of line.
3060 (beginning-of-line))
3061 (t
3062 (line-move-finish (or goal-column temporary-goal-column) opoint)))))
3063 nil)
3064
3065 (defun line-move-finish (column opoint)
3066 (let ((repeat t))
3067 (while repeat
3068 ;; Set REPEAT to t to repeat the whole thing.
3069 (setq repeat nil)
3070
3071 (let (new
3072 (line-beg (save-excursion (beginning-of-line) (point)))
3073 (line-end
3074 ;; Compute the end of the line
3075 ;; ignoring effectively intangible newlines.
3076 (let ((inhibit-point-motion-hooks nil)
3077 (inhibit-field-text-motion t))
3078 (save-excursion (end-of-line) (point)))))
3079
3080 ;; Move to the desired column.
3081 (line-move-to-column column)
3082 (setq new (point))
3083
3084 ;; Process intangibility within a line.
3085 ;; Move to the chosen destination position from above,
3086 ;; with intangibility processing enabled.
3087
3088 (goto-char (point-min))
3089 (let ((inhibit-point-motion-hooks nil))
3090 (goto-char new)
3091
3092 ;; If intangibility moves us to a different (later) place
3093 ;; in the same line, use that as the destination.
3094 (if (<= (point) line-end)
3095 (setq new (point))
3096 ;; If that position is "too late",
3097 ;; try the previous allowable position.
3098 ;; See if it is ok.
3099 (backward-char)
3100 (if (<= (point) line-end)
3101 (setq new (point))
3102 ;; As a last resort, use the end of the line.
3103 (setq new line-end))))
3104
3105 ;; Now move to the updated destination, processing fields
3106 ;; as well as intangibility.
3107 (goto-char opoint)
3108 (let ((inhibit-point-motion-hooks nil))
3109 (goto-char
3110 (constrain-to-field new opoint nil t
3111 'inhibit-line-move-field-capture)))
3112
3113 ;; If all this moved us to a different line,
3114 ;; retry everything within that new line.
3115 (when (or (< (point) line-beg) (> (point) line-end))
3116 ;; Repeat the intangibility and field processing.
3117 (setq repeat t))))))
3118
3119 (defun line-move-to-column (col)
3120 "Try to find column COL, considering invisibility.
3121 This function works only in certain cases,
3122 because what we really need is for `move-to-column'
3123 and `current-column' to be able to ignore invisible text."
3124 (if (zerop col)
3125 (beginning-of-line)
3126 (move-to-column col))
3127
3128 (when (and line-move-ignore-invisible
3129 (not (bolp)) (line-move-invisible (1- (point))))
3130 (let ((normal-location (point))
3131 (normal-column (current-column)))
3132 ;; If the following character is currently invisible,
3133 ;; skip all characters with that same `invisible' property value.
3134 (while (and (not (eobp))
3135 (line-move-invisible (point)))
3136 (goto-char (next-char-property-change (point))))
3137 ;; Have we advanced to a larger column position?
3138 (if (> (current-column) normal-column)
3139 ;; We have made some progress towards the desired column.
3140 ;; See if we can make any further progress.
3141 (line-move-to-column (+ (current-column) (- col normal-column)))
3142 ;; Otherwise, go to the place we originally found
3143 ;; and move back over invisible text.
3144 ;; that will get us to the same place on the screen
3145 ;; but with a more reasonable buffer position.
3146 (goto-char normal-location)
3147 (let ((line-beg (save-excursion (beginning-of-line) (point))))
3148 (while (and (not (bolp)) (line-move-invisible (1- (point))))
3149 (goto-char (previous-char-property-change (point) line-beg))))))))
3150
3151 ;;; Many people have said they rarely use this feature, and often type
3152 ;;; it by accident. Maybe it shouldn't even be on a key.
3153 (put 'set-goal-column 'disabled t)
3154
3155 (defun set-goal-column (arg)
3156 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
3157 Those commands will move to this position in the line moved to
3158 rather than trying to keep the same horizontal position.
3159 With a non-nil argument, clears out the goal column
3160 so that \\[next-line] and \\[previous-line] resume vertical motion.
3161 The goal column is stored in the variable `goal-column'."
3162 (interactive "P")
3163 (if arg
3164 (progn
3165 (setq goal-column nil)
3166 (message "No goal column"))
3167 (setq goal-column (current-column))
3168 (message (substitute-command-keys
3169 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
3170 goal-column))
3171 nil)
3172 \f
3173
3174 (defun scroll-other-window-down (lines)
3175 "Scroll the \"other window\" down.
3176 For more details, see the documentation for `scroll-other-window'."
3177 (interactive "P")
3178 (scroll-other-window
3179 ;; Just invert the argument's meaning.
3180 ;; We can do that without knowing which window it will be.
3181 (if (eq lines '-) nil
3182 (if (null lines) '-
3183 (- (prefix-numeric-value lines))))))
3184 (define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
3185
3186 (defun beginning-of-buffer-other-window (arg)
3187 "Move point to the beginning of the buffer in the other window.
3188 Leave mark at previous position.
3189 With arg N, put point N/10 of the way from the true beginning."
3190 (interactive "P")
3191 (let ((orig-window (selected-window))
3192 (window (other-window-for-scrolling)))
3193 ;; We use unwind-protect rather than save-window-excursion
3194 ;; because the latter would preserve the things we want to change.
3195 (unwind-protect
3196 (progn
3197 (select-window window)
3198 ;; Set point and mark in that window's buffer.
3199 (beginning-of-buffer arg)
3200 ;; Set point accordingly.
3201 (recenter '(t)))
3202 (select-window orig-window))))
3203
3204 (defun end-of-buffer-other-window (arg)
3205 "Move point to the end of the buffer in the other window.
3206 Leave mark at previous position.
3207 With arg N, put point N/10 of the way from the true end."
3208 (interactive "P")
3209 ;; See beginning-of-buffer-other-window for comments.
3210 (let ((orig-window (selected-window))
3211 (window (other-window-for-scrolling)))
3212 (unwind-protect
3213 (progn
3214 (select-window window)
3215 (end-of-buffer arg)
3216 (recenter '(t)))
3217 (select-window orig-window))))
3218 \f
3219 (defun transpose-chars (arg)
3220 "Interchange characters around point, moving forward one character.
3221 With prefix arg ARG, effect is to take character before point
3222 and drag it forward past ARG other characters (backward if ARG negative).
3223 If no argument and at end of line, the previous two chars are exchanged."
3224 (interactive "*P")
3225 (and (null arg) (eolp) (forward-char -1))
3226 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3227
3228 (defun transpose-words (arg)
3229 "Interchange words around point, leaving point at end of them.
3230 With prefix arg ARG, effect is to take word before or around point
3231 and drag it forward past ARG other words (backward if ARG negative).
3232 If ARG is zero, the words around or after point and around or after mark
3233 are interchanged."
3234 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
3235 (interactive "*p")
3236 (transpose-subr 'forward-word arg))
3237
3238 (defun transpose-sexps (arg)
3239 "Like \\[transpose-words] but applies to sexps.
3240 Does not work on a sexp that point is in the middle of
3241 if it is a list or string."
3242 (interactive "*p")
3243 (transpose-subr
3244 (lambda (arg)
3245 ;; Here we should try to simulate the behavior of
3246 ;; (cons (progn (forward-sexp x) (point))
3247 ;; (progn (forward-sexp (- x)) (point)))
3248 ;; Except that we don't want to rely on the second forward-sexp
3249 ;; putting us back to where we want to be, since forward-sexp-function
3250 ;; might do funny things like infix-precedence.
3251 (if (if (> arg 0)
3252 (looking-at "\\sw\\|\\s_")
3253 (and (not (bobp))
3254 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
3255 ;; Jumping over a symbol. We might be inside it, mind you.
3256 (progn (funcall (if (> arg 0)
3257 'skip-syntax-backward 'skip-syntax-forward)
3258 "w_")
3259 (cons (save-excursion (forward-sexp arg) (point)) (point)))
3260 ;; Otherwise, we're between sexps. Take a step back before jumping
3261 ;; to make sure we'll obey the same precedence no matter which direction
3262 ;; we're going.
3263 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
3264 (cons (save-excursion (forward-sexp arg) (point))
3265 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
3266 (not (zerop (funcall (if (> arg 0)
3267 'skip-syntax-forward
3268 'skip-syntax-backward)
3269 ".")))))
3270 (point)))))
3271 arg 'special))
3272
3273 (defun transpose-lines (arg)
3274 "Exchange current line and previous line, leaving point after both.
3275 With argument ARG, takes previous line and moves it past ARG lines.
3276 With argument 0, interchanges line point is in with line mark is in."
3277 (interactive "*p")
3278 (transpose-subr (function
3279 (lambda (arg)
3280 (if (> arg 0)
3281 (progn
3282 ;; Move forward over ARG lines,
3283 ;; but create newlines if necessary.
3284 (setq arg (forward-line arg))
3285 (if (/= (preceding-char) ?\n)
3286 (setq arg (1+ arg)))
3287 (if (> arg 0)
3288 (newline arg)))
3289 (forward-line arg))))
3290 arg))
3291
3292 (defun transpose-subr (mover arg &optional special)
3293 (let ((aux (if special mover
3294 (lambda (x)
3295 (cons (progn (funcall mover x) (point))
3296 (progn (funcall mover (- x)) (point))))))
3297 pos1 pos2)
3298 (cond
3299 ((= arg 0)
3300 (save-excursion
3301 (setq pos1 (funcall aux 1))
3302 (goto-char (mark))
3303 (setq pos2 (funcall aux 1))
3304 (transpose-subr-1 pos1 pos2))
3305 (exchange-point-and-mark))
3306 ((> arg 0)
3307 (setq pos1 (funcall aux -1))
3308 (setq pos2 (funcall aux arg))
3309 (transpose-subr-1 pos1 pos2)
3310 (goto-char (car pos2)))
3311 (t
3312 (setq pos1 (funcall aux -1))
3313 (goto-char (car pos1))
3314 (setq pos2 (funcall aux arg))
3315 (transpose-subr-1 pos1 pos2)))))
3316
3317 (defun transpose-subr-1 (pos1 pos2)
3318 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
3319 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
3320 (when (> (car pos1) (car pos2))
3321 (let ((swap pos1))
3322 (setq pos1 pos2 pos2 swap)))
3323 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
3324 (atomic-change-group
3325 (let (word2)
3326 ;; FIXME: We first delete the two pieces of text, so markers that
3327 ;; used to point to after the text end up pointing to before it :-(
3328 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
3329 (goto-char (car pos2))
3330 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
3331 (goto-char (car pos1))
3332 (insert word2))))
3333 \f
3334 (defun backward-word (&optional arg)
3335 "Move backward until encountering the beginning of a word.
3336 With argument, do this that many times."
3337 (interactive "p")
3338 (forward-word (- (or arg 1))))
3339
3340 (defun mark-word (arg)
3341 "Set mark arg words away from point.
3342 If this command is repeated, it marks the next ARG words after the ones
3343 already marked."
3344 (interactive "p")
3345 (cond ((and (eq last-command this-command) (mark t))
3346 (set-mark
3347 (save-excursion
3348 (goto-char (mark))
3349 (forward-word arg)
3350 (point))))
3351 (t
3352 (push-mark
3353 (save-excursion
3354 (forward-word arg)
3355 (point))
3356 nil t))))
3357
3358 (defun kill-word (arg)
3359 "Kill characters forward until encountering the end of a word.
3360 With argument, do this that many times."
3361 (interactive "p")
3362 (kill-region (point) (progn (forward-word arg) (point))))
3363
3364 (defun backward-kill-word (arg)
3365 "Kill characters backward until encountering the end of a word.
3366 With argument, do this that many times."
3367 (interactive "p")
3368 (kill-word (- arg)))
3369
3370 (defun current-word (&optional strict really-word)
3371 "Return the symbol or word that point is on (or a nearby one) as a string.
3372 The return value includes no text properties.
3373 If optional arg STRICT is non-nil, return nil unless point is within
3374 or adjacent to a symbol or word. In all cases the value can be nil
3375 if there is no word nearby.
3376 The function, belying its name, normally finds a symbol.
3377 If optional arg REALLY-WORD is non-nil, it finds just a word."
3378 (save-excursion
3379 (let* ((oldpoint (point)) (start (point)) (end (point))
3380 (syntaxes (if really-word "w" "w_"))
3381 (not-syntaxes (concat "^" syntaxes)))
3382 (skip-syntax-backward syntaxes) (setq start (point))
3383 (goto-char oldpoint)
3384 (skip-syntax-forward syntaxes) (setq end (point))
3385 (when (and (eq start oldpoint) (eq end oldpoint)
3386 ;; Point is neither within nor adjacent to a word.
3387 (not strict))
3388 ;; Look for preceding word in same line.
3389 (skip-syntax-backward not-syntaxes
3390 (save-excursion (beginning-of-line)
3391 (point)))
3392 (if (bolp)
3393 ;; No preceding word in same line.
3394 ;; Look for following word in same line.
3395 (progn
3396 (skip-syntax-forward not-syntaxes
3397 (save-excursion (end-of-line)
3398 (point)))
3399 (setq start (point))
3400 (skip-syntax-forward syntaxes)
3401 (setq end (point)))
3402 (setq end (point))
3403 (skip-syntax-backward syntaxes)
3404 (setq start (point))))
3405 ;; If we found something nonempty, return it as a string.
3406 (unless (= start end)
3407 (buffer-substring-no-properties start end)))))
3408 \f
3409 (defcustom fill-prefix nil
3410 "*String for filling to insert at front of new line, or nil for none."
3411 :type '(choice (const :tag "None" nil)
3412 string)
3413 :group 'fill)
3414 (make-variable-buffer-local 'fill-prefix)
3415
3416 (defcustom auto-fill-inhibit-regexp nil
3417 "*Regexp to match lines which should not be auto-filled."
3418 :type '(choice (const :tag "None" nil)
3419 regexp)
3420 :group 'fill)
3421
3422 (defvar comment-line-break-function 'comment-indent-new-line
3423 "*Mode-specific function which line breaks and continues a comment.
3424
3425 This function is only called during auto-filling of a comment section.
3426 The function should take a single optional argument, which is a flag
3427 indicating whether it should use soft newlines.
3428
3429 Setting this variable automatically makes it local to the current buffer.")
3430
3431 ;; This function is used as the auto-fill-function of a buffer
3432 ;; when Auto-Fill mode is enabled.
3433 ;; It returns t if it really did any work.
3434 ;; (Actually some major modes use a different auto-fill function,
3435 ;; but this one is the default one.)
3436 (defun do-auto-fill ()
3437 (let (fc justify give-up
3438 (fill-prefix fill-prefix))
3439 (if (or (not (setq justify (current-justification)))
3440 (null (setq fc (current-fill-column)))
3441 (and (eq justify 'left)
3442 (<= (current-column) fc))
3443 (and auto-fill-inhibit-regexp
3444 (save-excursion (beginning-of-line)
3445 (looking-at auto-fill-inhibit-regexp))))
3446 nil ;; Auto-filling not required
3447 (if (memq justify '(full center right))
3448 (save-excursion (unjustify-current-line)))
3449
3450 ;; Choose a fill-prefix automatically.
3451 (when (and adaptive-fill-mode
3452 (or (null fill-prefix) (string= fill-prefix "")))
3453 (let ((prefix
3454 (fill-context-prefix
3455 (save-excursion (backward-paragraph 1) (point))
3456 (save-excursion (forward-paragraph 1) (point)))))
3457 (and prefix (not (equal prefix ""))
3458 ;; Use auto-indentation rather than a guessed empty prefix.
3459 (not (and fill-indent-according-to-mode
3460 (string-match "\\`[ \t]*\\'" prefix)))
3461 (setq fill-prefix prefix))))
3462
3463 (while (and (not give-up) (> (current-column) fc))
3464 ;; Determine where to split the line.
3465 (let* (after-prefix
3466 (fill-point
3467 (save-excursion
3468 (beginning-of-line)
3469 (setq after-prefix (point))
3470 (and fill-prefix
3471 (looking-at (regexp-quote fill-prefix))
3472 (setq after-prefix (match-end 0)))
3473 (move-to-column (1+ fc))
3474 (fill-move-to-break-point after-prefix)
3475 (point))))
3476
3477 ;; See whether the place we found is any good.
3478 (if (save-excursion
3479 (goto-char fill-point)
3480 (or (bolp)
3481 ;; There is no use breaking at end of line.
3482 (save-excursion (skip-chars-forward " ") (eolp))
3483 ;; It is futile to split at the end of the prefix
3484 ;; since we would just insert the prefix again.
3485 (and after-prefix (<= (point) after-prefix))
3486 ;; Don't split right after a comment starter
3487 ;; since we would just make another comment starter.
3488 (and comment-start-skip
3489 (let ((limit (point)))
3490 (beginning-of-line)
3491 (and (re-search-forward comment-start-skip
3492 limit t)
3493 (eq (point) limit))))))
3494 ;; No good place to break => stop trying.
3495 (setq give-up t)
3496 ;; Ok, we have a useful place to break the line. Do it.
3497 (let ((prev-column (current-column)))
3498 ;; If point is at the fill-point, do not `save-excursion'.
3499 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
3500 ;; point will end up before it rather than after it.
3501 (if (save-excursion
3502 (skip-chars-backward " \t")
3503 (= (point) fill-point))
3504 (funcall comment-line-break-function t)
3505 (save-excursion
3506 (goto-char fill-point)
3507 (funcall comment-line-break-function t)))
3508 ;; Now do justification, if required
3509 (if (not (eq justify 'left))
3510 (save-excursion
3511 (end-of-line 0)
3512 (justify-current-line justify nil t)))
3513 ;; If making the new line didn't reduce the hpos of
3514 ;; the end of the line, then give up now;
3515 ;; trying again will not help.
3516 (if (>= (current-column) prev-column)
3517 (setq give-up t))))))
3518 ;; Justify last line.
3519 (justify-current-line justify t t)
3520 t)))
3521
3522 (defvar normal-auto-fill-function 'do-auto-fill
3523 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
3524 Some major modes set this.")
3525
3526 ;; FIXME: turn into a proper minor mode.
3527 ;; Add a global minor mode version of it.
3528 (defun auto-fill-mode (&optional arg)
3529 "Toggle Auto Fill mode.
3530 With arg, turn Auto Fill mode on if and only if arg is positive.
3531 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
3532 automatically breaks the line at a previous space.
3533
3534 The value of `normal-auto-fill-function' specifies the function to use
3535 for `auto-fill-function' when turning Auto Fill mode on."
3536 (interactive "P")
3537 (prog1 (setq auto-fill-function
3538 (if (if (null arg)
3539 (not auto-fill-function)
3540 (> (prefix-numeric-value arg) 0))
3541 normal-auto-fill-function
3542 nil))
3543 (force-mode-line-update)))
3544
3545 ;; This holds a document string used to document auto-fill-mode.
3546 (defun auto-fill-function ()
3547 "Automatically break line at a previous space, in insertion of text."
3548 nil)
3549
3550 (defun turn-on-auto-fill ()
3551 "Unconditionally turn on Auto Fill mode."
3552 (auto-fill-mode 1))
3553
3554 (defun turn-off-auto-fill ()
3555 "Unconditionally turn off Auto Fill mode."
3556 (auto-fill-mode -1))
3557
3558 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
3559
3560 (defun set-fill-column (arg)
3561 "Set `fill-column' to specified argument.
3562 Use \\[universal-argument] followed by a number to specify a column.
3563 Just \\[universal-argument] as argument means to use the current column."
3564 (interactive "P")
3565 (if (consp arg)
3566 (setq arg (current-column)))
3567 (if (not (integerp arg))
3568 ;; Disallow missing argument; it's probably a typo for C-x C-f.
3569 (error "Set-fill-column requires an explicit argument")
3570 (message "Fill column set to %d (was %d)" arg fill-column)
3571 (setq fill-column arg)))
3572 \f
3573 (defun set-selective-display (arg)
3574 "Set `selective-display' to ARG; clear it if no arg.
3575 When the value of `selective-display' is a number > 0,
3576 lines whose indentation is >= that value are not displayed.
3577 The variable `selective-display' has a separate value for each buffer."
3578 (interactive "P")
3579 (if (eq selective-display t)
3580 (error "selective-display already in use for marked lines"))
3581 (let ((current-vpos
3582 (save-restriction
3583 (narrow-to-region (point-min) (point))
3584 (goto-char (window-start))
3585 (vertical-motion (window-height)))))
3586 (setq selective-display
3587 (and arg (prefix-numeric-value arg)))
3588 (recenter current-vpos))
3589 (set-window-start (selected-window) (window-start (selected-window)))
3590 (princ "selective-display set to " t)
3591 (prin1 selective-display t)
3592 (princ "." t))
3593
3594 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
3595 (defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
3596
3597 (defun toggle-truncate-lines (arg)
3598 "Toggle whether to fold or truncate long lines on the screen.
3599 With arg, truncate long lines iff arg is positive.
3600 Note that in side-by-side windows, truncation is always enabled."
3601 (interactive "P")
3602 (setq truncate-lines
3603 (if (null arg)
3604 (not truncate-lines)
3605 (> (prefix-numeric-value arg) 0)))
3606 (force-mode-line-update)
3607 (unless truncate-lines
3608 (let ((buffer (current-buffer)))
3609 (walk-windows (lambda (window)
3610 (if (eq buffer (window-buffer window))
3611 (set-window-hscroll window 0)))
3612 nil t)))
3613 (message "Truncate long lines %s"
3614 (if truncate-lines "enabled" "disabled")))
3615
3616 (defvar overwrite-mode-textual " Ovwrt"
3617 "The string displayed in the mode line when in overwrite mode.")
3618 (defvar overwrite-mode-binary " Bin Ovwrt"
3619 "The string displayed in the mode line when in binary overwrite mode.")
3620
3621 (defun overwrite-mode (arg)
3622 "Toggle overwrite mode.
3623 With arg, turn overwrite mode on iff arg is positive.
3624 In overwrite mode, printing characters typed in replace existing text
3625 on a one-for-one basis, rather than pushing it to the right. At the
3626 end of a line, such characters extend the line. Before a tab,
3627 such characters insert until the tab is filled in.
3628 \\[quoted-insert] still inserts characters in overwrite mode; this
3629 is supposed to make it easier to insert characters when necessary."
3630 (interactive "P")
3631 (setq overwrite-mode
3632 (if (if (null arg) (not overwrite-mode)
3633 (> (prefix-numeric-value arg) 0))
3634 'overwrite-mode-textual))
3635 (force-mode-line-update))
3636
3637 (defun binary-overwrite-mode (arg)
3638 "Toggle binary overwrite mode.
3639 With arg, turn binary overwrite mode on iff arg is positive.
3640 In binary overwrite mode, printing characters typed in replace
3641 existing text. Newlines are not treated specially, so typing at the
3642 end of a line joins the line to the next, with the typed character
3643 between them. Typing before a tab character simply replaces the tab
3644 with the character typed.
3645 \\[quoted-insert] replaces the text at the cursor, just as ordinary
3646 typing characters do.
3647
3648 Note that binary overwrite mode is not its own minor mode; it is a
3649 specialization of overwrite-mode, entered by setting the
3650 `overwrite-mode' variable to `overwrite-mode-binary'."
3651 (interactive "P")
3652 (setq overwrite-mode
3653 (if (if (null arg)
3654 (not (eq overwrite-mode 'overwrite-mode-binary))
3655 (> (prefix-numeric-value arg) 0))
3656 'overwrite-mode-binary))
3657 (force-mode-line-update))
3658
3659 (define-minor-mode line-number-mode
3660 "Toggle Line Number mode.
3661 With arg, turn Line Number mode on iff arg is positive.
3662 When Line Number mode is enabled, the line number appears
3663 in the mode line.
3664
3665 Line numbers do not appear for very large buffers and buffers
3666 with very long lines; see variables `line-number-display-limit'
3667 and `line-number-display-limit-width'."
3668 :init-value t :global t :group 'editing-basics :require nil)
3669
3670 (define-minor-mode column-number-mode
3671 "Toggle Column Number mode.
3672 With arg, turn Column Number mode on iff arg is positive.
3673 When Column Number mode is enabled, the column number appears
3674 in the mode line."
3675 :global t :group 'editing-basics :require nil)
3676
3677 (define-minor-mode size-indication-mode
3678 "Toggle Size Indication mode.
3679 With arg, turn Size Indication mode on iff arg is positive. When
3680 Size Indication mode is enabled, the size of the accessible part
3681 of the buffer appears in the mode line."
3682 :global t :group 'editing-basics :require nil)
3683 \f
3684 (defgroup paren-blinking nil
3685 "Blinking matching of parens and expressions."
3686 :prefix "blink-matching-"
3687 :group 'paren-matching)
3688
3689 (defcustom blink-matching-paren t
3690 "*Non-nil means show matching open-paren when close-paren is inserted."
3691 :type 'boolean
3692 :group 'paren-blinking)
3693
3694 (defcustom blink-matching-paren-on-screen t
3695 "*Non-nil means show matching open-paren when it is on screen.
3696 If nil, means don't show it (but the open-paren can still be shown
3697 when it is off screen)."
3698 :type 'boolean
3699 :group 'paren-blinking)
3700
3701 (defcustom blink-matching-paren-distance (* 25 1024)
3702 "*If non-nil, is maximum distance to search for matching open-paren."
3703 :type 'integer
3704 :group 'paren-blinking)
3705
3706 (defcustom blink-matching-delay 1
3707 "*Time in seconds to delay after showing a matching paren."
3708 :type 'number
3709 :group 'paren-blinking)
3710
3711 (defcustom blink-matching-paren-dont-ignore-comments nil
3712 "*Non-nil means `blink-matching-paren' will not ignore comments."
3713 :type 'boolean
3714 :group 'paren-blinking)
3715
3716 (defun blink-matching-open ()
3717 "Move cursor momentarily to the beginning of the sexp before point."
3718 (interactive)
3719 (and (> (point) (1+ (point-min)))
3720 blink-matching-paren
3721 ;; Verify an even number of quoting characters precede the close.
3722 (= 1 (logand 1 (- (point)
3723 (save-excursion
3724 (forward-char -1)
3725 (skip-syntax-backward "/\\")
3726 (point)))))
3727 (let* ((oldpos (point))
3728 (blinkpos)
3729 (mismatch)
3730 matching-paren)
3731 (save-excursion
3732 (save-restriction
3733 (if blink-matching-paren-distance
3734 (narrow-to-region (max (point-min)
3735 (- (point) blink-matching-paren-distance))
3736 oldpos))
3737 (condition-case ()
3738 (let ((parse-sexp-ignore-comments
3739 (and parse-sexp-ignore-comments
3740 (not blink-matching-paren-dont-ignore-comments))))
3741 (setq blinkpos (scan-sexps oldpos -1)))
3742 (error nil)))
3743 (and blinkpos
3744 (save-excursion
3745 (goto-char blinkpos)
3746 (not (looking-at "\\s$")))
3747 (setq matching-paren
3748 (or (and parse-sexp-lookup-properties
3749 (let ((prop (get-text-property blinkpos 'syntax-table)))
3750 (and (consp prop)
3751 (eq (car prop) 4)
3752 (cdr prop))))
3753 (matching-paren (char-after blinkpos)))
3754 mismatch
3755 (or (null matching-paren)
3756 (/= (char-after (1- oldpos))
3757 matching-paren))))
3758 (if mismatch (setq blinkpos nil))
3759 (if blinkpos
3760 ;; Don't log messages about paren matching.
3761 (let (message-log-max)
3762 (goto-char blinkpos)
3763 (if (pos-visible-in-window-p)
3764 (and blink-matching-paren-on-screen
3765 (sit-for blink-matching-delay))
3766 (goto-char blinkpos)
3767 (message
3768 "Matches %s"
3769 ;; Show what precedes the open in its line, if anything.
3770 (if (save-excursion
3771 (skip-chars-backward " \t")
3772 (not (bolp)))
3773 (buffer-substring (progn (beginning-of-line) (point))
3774 (1+ blinkpos))
3775 ;; Show what follows the open in its line, if anything.
3776 (if (save-excursion
3777 (forward-char 1)
3778 (skip-chars-forward " \t")
3779 (not (eolp)))
3780 (buffer-substring blinkpos
3781 (progn (end-of-line) (point)))
3782 ;; Otherwise show the previous nonblank line,
3783 ;; if there is one.
3784 (if (save-excursion
3785 (skip-chars-backward "\n \t")
3786 (not (bobp)))
3787 (concat
3788 (buffer-substring (progn
3789 (skip-chars-backward "\n \t")
3790 (beginning-of-line)
3791 (point))
3792 (progn (end-of-line)
3793 (skip-chars-backward " \t")
3794 (point)))
3795 ;; Replace the newline and other whitespace with `...'.
3796 "..."
3797 (buffer-substring blinkpos (1+ blinkpos)))
3798 ;; There is nothing to show except the char itself.
3799 (buffer-substring blinkpos (1+ blinkpos))))))))
3800 (cond (mismatch
3801 (message "Mismatched parentheses"))
3802 ((not blink-matching-paren-distance)
3803 (message "Unmatched parenthesis"))))))))
3804
3805 ;Turned off because it makes dbx bomb out.
3806 (setq blink-paren-function 'blink-matching-open)
3807 \f
3808 ;; This executes C-g typed while Emacs is waiting for a command.
3809 ;; Quitting out of a program does not go through here;
3810 ;; that happens in the QUIT macro at the C code level.
3811 (defun keyboard-quit ()
3812 "Signal a `quit' condition.
3813 During execution of Lisp code, this character causes a quit directly.
3814 At top-level, as an editor command, this simply beeps."
3815 (interactive)
3816 (deactivate-mark)
3817 (setq defining-kbd-macro nil)
3818 (signal 'quit nil))
3819
3820 (define-key global-map "\C-g" 'keyboard-quit)
3821
3822 (defvar buffer-quit-function nil
3823 "Function to call to \"quit\" the current buffer, or nil if none.
3824 \\[keyboard-escape-quit] calls this function when its more local actions
3825 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
3826
3827 (defun keyboard-escape-quit ()
3828 "Exit the current \"mode\" (in a generalized sense of the word).
3829 This command can exit an interactive command such as `query-replace',
3830 can clear out a prefix argument or a region,
3831 can get out of the minibuffer or other recursive edit,
3832 cancel the use of the current buffer (for special-purpose buffers),
3833 or go back to just one window (by deleting all but the selected window)."
3834 (interactive)
3835 (cond ((eq last-command 'mode-exited) nil)
3836 ((> (minibuffer-depth) 0)
3837 (abort-recursive-edit))
3838 (current-prefix-arg
3839 nil)
3840 ((and transient-mark-mode
3841 mark-active)
3842 (deactivate-mark))
3843 ((> (recursion-depth) 0)
3844 (exit-recursive-edit))
3845 (buffer-quit-function
3846 (funcall buffer-quit-function))
3847 ((not (one-window-p t))
3848 (delete-other-windows))
3849 ((string-match "^ \\*" (buffer-name (current-buffer)))
3850 (bury-buffer))))
3851
3852 (defun play-sound-file (file &optional volume device)
3853 "Play sound stored in FILE.
3854 VOLUME and DEVICE correspond to the keywords of the sound
3855 specification for `play-sound'."
3856 (interactive "fPlay sound file: ")
3857 (let ((sound (list :file file)))
3858 (if volume
3859 (plist-put sound :volume volume))
3860 (if device
3861 (plist-put sound :device device))
3862 (push 'sound sound)
3863 (play-sound sound)))
3864
3865 (define-key global-map "\e\e\e" 'keyboard-escape-quit)
3866
3867 (defcustom read-mail-command 'rmail
3868 "*Your preference for a mail reading package.
3869 This is used by some keybindings which support reading mail.
3870 See also `mail-user-agent' concerning sending mail."
3871 :type '(choice (function-item rmail)
3872 (function-item gnus)
3873 (function-item mh-rmail)
3874 (function :tag "Other"))
3875 :version "21.1"
3876 :group 'mail)
3877
3878 (defcustom mail-user-agent 'sendmail-user-agent
3879 "*Your preference for a mail composition package.
3880 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
3881 outgoing email message. This variable lets you specify which
3882 mail-sending package you prefer.
3883
3884 Valid values include:
3885
3886 `sendmail-user-agent' -- use the default Emacs Mail package.
3887 See Info node `(emacs)Sending Mail'.
3888 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
3889 See Info node `(mh-e)'.
3890 `message-user-agent' -- use the Gnus Message package.
3891 See Info node `(message)'.
3892 `gnus-user-agent' -- like `message-user-agent', but with Gnus
3893 paraphernalia, particularly the Gcc: header for
3894 archiving.
3895
3896 Additional valid symbols may be available; check with the author of
3897 your package for details. The function should return non-nil if it
3898 succeeds.
3899
3900 See also `read-mail-command' concerning reading mail."
3901 :type '(radio (function-item :tag "Default Emacs mail"
3902 :format "%t\n"
3903 sendmail-user-agent)
3904 (function-item :tag "Emacs interface to MH"
3905 :format "%t\n"
3906 mh-e-user-agent)
3907 (function-item :tag "Gnus Message package"
3908 :format "%t\n"
3909 message-user-agent)
3910 (function-item :tag "Gnus Message with full Gnus features"
3911 :format "%t\n"
3912 gnus-user-agent)
3913 (function :tag "Other"))
3914 :group 'mail)
3915
3916 (define-mail-user-agent 'sendmail-user-agent
3917 'sendmail-user-agent-compose
3918 'mail-send-and-exit)
3919
3920 (defun rfc822-goto-eoh ()
3921 ;; Go to header delimiter line in a mail message, following RFC822 rules
3922 (goto-char (point-min))
3923 (when (re-search-forward
3924 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
3925 (goto-char (match-beginning 0))))
3926
3927 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
3928 switch-function yank-action
3929 send-actions)
3930 (if switch-function
3931 (let ((special-display-buffer-names nil)
3932 (special-display-regexps nil)
3933 (same-window-buffer-names nil)
3934 (same-window-regexps nil))
3935 (funcall switch-function "*mail*")))
3936 (let ((cc (cdr (assoc-string "cc" other-headers t)))
3937 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
3938 (body (cdr (assoc-string "body" other-headers t))))
3939 (or (mail continue to subject in-reply-to cc yank-action send-actions)
3940 continue
3941 (error "Message aborted"))
3942 (save-excursion
3943 (rfc822-goto-eoh)
3944 (while other-headers
3945 (unless (member-ignore-case (car (car other-headers))
3946 '("in-reply-to" "cc" "body"))
3947 (insert (car (car other-headers)) ": "
3948 (cdr (car other-headers)) "\n"))
3949 (setq other-headers (cdr other-headers)))
3950 (when body
3951 (forward-line 1)
3952 (insert body))
3953 t)))
3954
3955 (define-mail-user-agent 'mh-e-user-agent
3956 'mh-smail-batch 'mh-send-letter 'mh-fully-kill-draft
3957 'mh-before-send-letter-hook)
3958
3959 (defun compose-mail (&optional to subject other-headers continue
3960 switch-function yank-action send-actions)
3961 "Start composing a mail message to send.
3962 This uses the user's chosen mail composition package
3963 as selected with the variable `mail-user-agent'.
3964 The optional arguments TO and SUBJECT specify recipients
3965 and the initial Subject field, respectively.
3966
3967 OTHER-HEADERS is an alist specifying additional
3968 header fields. Elements look like (HEADER . VALUE) where both
3969 HEADER and VALUE are strings.
3970
3971 CONTINUE, if non-nil, says to continue editing a message already
3972 being composed.
3973
3974 SWITCH-FUNCTION, if non-nil, is a function to use to
3975 switch to and display the buffer used for mail composition.
3976
3977 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
3978 to insert the raw text of the message being replied to.
3979 It has the form (FUNCTION . ARGS). The user agent will apply
3980 FUNCTION to ARGS, to insert the raw text of the original message.
3981 \(The user agent will also run `mail-citation-hook', *after* the
3982 original text has been inserted in this way.)
3983
3984 SEND-ACTIONS is a list of actions to call when the message is sent.
3985 Each action has the form (FUNCTION . ARGS)."
3986 (interactive
3987 (list nil nil nil current-prefix-arg))
3988 (let ((function (get mail-user-agent 'composefunc)))
3989 (funcall function to subject other-headers continue
3990 switch-function yank-action send-actions)))
3991
3992 (defun compose-mail-other-window (&optional to subject other-headers continue
3993 yank-action send-actions)
3994 "Like \\[compose-mail], but edit the outgoing message in another window."
3995 (interactive
3996 (list nil nil nil current-prefix-arg))
3997 (compose-mail to subject other-headers continue
3998 'switch-to-buffer-other-window yank-action send-actions))
3999
4000
4001 (defun compose-mail-other-frame (&optional to subject other-headers continue
4002 yank-action send-actions)
4003 "Like \\[compose-mail], but edit the outgoing message in another frame."
4004 (interactive
4005 (list nil nil nil current-prefix-arg))
4006 (compose-mail to subject other-headers continue
4007 'switch-to-buffer-other-frame yank-action send-actions))
4008
4009 (defvar set-variable-value-history nil
4010 "History of values entered with `set-variable'.")
4011
4012 (defun set-variable (var val &optional make-local)
4013 "Set VARIABLE to VALUE. VALUE is a Lisp object.
4014 When using this interactively, enter a Lisp object for VALUE.
4015 If you want VALUE to be a string, you must surround it with doublequotes.
4016 VALUE is used literally, not evaluated.
4017
4018 If VARIABLE has a `variable-interactive' property, that is used as if
4019 it were the arg to `interactive' (which see) to interactively read VALUE.
4020
4021 If VARIABLE has been defined with `defcustom', then the type information
4022 in the definition is used to check that VALUE is valid.
4023
4024 With a prefix argument, set VARIABLE to VALUE buffer-locally."
4025 (interactive
4026 (let* ((default-var (variable-at-point))
4027 (var (if (symbolp default-var)
4028 (read-variable (format "Set variable (default %s): " default-var)
4029 default-var)
4030 (read-variable "Set variable: ")))
4031 (minibuffer-help-form '(describe-variable var))
4032 (prop (get var 'variable-interactive))
4033 (prompt (format "Set %s%s to value: " var
4034 (cond ((local-variable-p var)
4035 " (buffer-local)")
4036 ((or current-prefix-arg
4037 (local-variable-if-set-p var))
4038 " buffer-locally")
4039 (t " globally"))))
4040 (val (if prop
4041 ;; Use VAR's `variable-interactive' property
4042 ;; as an interactive spec for prompting.
4043 (call-interactively `(lambda (arg)
4044 (interactive ,prop)
4045 arg))
4046 (read
4047 (read-string prompt nil
4048 'set-variable-value-history)))))
4049 (list var val current-prefix-arg)))
4050
4051 (and (custom-variable-p var)
4052 (not (get var 'custom-type))
4053 (custom-load-symbol var))
4054 (let ((type (get var 'custom-type)))
4055 (when type
4056 ;; Match with custom type.
4057 (require 'cus-edit)
4058 (setq type (widget-convert type))
4059 (unless (widget-apply type :match val)
4060 (error "Value `%S' does not match type %S of %S"
4061 val (car type) var))))
4062
4063 (if make-local
4064 (make-local-variable var))
4065
4066 (set var val)
4067
4068 ;; Force a thorough redisplay for the case that the variable
4069 ;; has an effect on the display, like `tab-width' has.
4070 (force-mode-line-update))
4071
4072 ;; Define the major mode for lists of completions.
4073
4074 (defvar completion-list-mode-map nil
4075 "Local map for completion list buffers.")
4076 (or completion-list-mode-map
4077 (let ((map (make-sparse-keymap)))
4078 (define-key map [mouse-2] 'mouse-choose-completion)
4079 (define-key map [down-mouse-2] nil)
4080 (define-key map "\C-m" 'choose-completion)
4081 (define-key map "\e\e\e" 'delete-completion-window)
4082 (define-key map [left] 'previous-completion)
4083 (define-key map [right] 'next-completion)
4084 (setq completion-list-mode-map map)))
4085
4086 ;; Completion mode is suitable only for specially formatted data.
4087 (put 'completion-list-mode 'mode-class 'special)
4088
4089 (defvar completion-reference-buffer nil
4090 "Record the buffer that was current when the completion list was requested.
4091 This is a local variable in the completion list buffer.
4092 Initial value is nil to avoid some compiler warnings.")
4093
4094 (defvar completion-no-auto-exit nil
4095 "Non-nil means `choose-completion-string' should never exit the minibuffer.
4096 This also applies to other functions such as `choose-completion'
4097 and `mouse-choose-completion'.")
4098
4099 (defvar completion-base-size nil
4100 "Number of chars at beginning of minibuffer not involved in completion.
4101 This is a local variable in the completion list buffer
4102 but it talks about the buffer in `completion-reference-buffer'.
4103 If this is nil, it means to compare text to determine which part
4104 of the tail end of the buffer's text is involved in completion.")
4105
4106 (defun delete-completion-window ()
4107 "Delete the completion list window.
4108 Go to the window from which completion was requested."
4109 (interactive)
4110 (let ((buf completion-reference-buffer))
4111 (if (one-window-p t)
4112 (if (window-dedicated-p (selected-window))
4113 (delete-frame (selected-frame)))
4114 (delete-window (selected-window))
4115 (if (get-buffer-window buf)
4116 (select-window (get-buffer-window buf))))))
4117
4118 (defun previous-completion (n)
4119 "Move to the previous item in the completion list."
4120 (interactive "p")
4121 (next-completion (- n)))
4122
4123 (defun next-completion (n)
4124 "Move to the next item in the completion list.
4125 With prefix argument N, move N items (negative N means move backward)."
4126 (interactive "p")
4127 (let ((beg (point-min)) (end (point-max)))
4128 (while (and (> n 0) (not (eobp)))
4129 ;; If in a completion, move to the end of it.
4130 (when (get-text-property (point) 'mouse-face)
4131 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4132 ;; Move to start of next one.
4133 (unless (get-text-property (point) 'mouse-face)
4134 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4135 (setq n (1- n)))
4136 (while (and (< n 0) (not (bobp)))
4137 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
4138 ;; If in a completion, move to the start of it.
4139 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
4140 (goto-char (previous-single-property-change
4141 (point) 'mouse-face nil beg)))
4142 ;; Move to end of the previous completion.
4143 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
4144 (goto-char (previous-single-property-change
4145 (point) 'mouse-face nil beg)))
4146 ;; Move to the start of that one.
4147 (goto-char (previous-single-property-change
4148 (point) 'mouse-face nil beg))
4149 (setq n (1+ n))))))
4150
4151 (defun choose-completion ()
4152 "Choose the completion that point is in or next to."
4153 (interactive)
4154 (let (beg end completion (buffer completion-reference-buffer)
4155 (base-size completion-base-size))
4156 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
4157 (setq end (point) beg (1+ (point))))
4158 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
4159 (setq end (1- (point)) beg (point)))
4160 (if (null beg)
4161 (error "No completion here"))
4162 (setq beg (previous-single-property-change beg 'mouse-face))
4163 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
4164 (setq completion (buffer-substring beg end))
4165 (let ((owindow (selected-window)))
4166 (if (and (one-window-p t 'selected-frame)
4167 (window-dedicated-p (selected-window)))
4168 ;; This is a special buffer's frame
4169 (iconify-frame (selected-frame))
4170 (or (window-dedicated-p (selected-window))
4171 (bury-buffer)))
4172 (select-window owindow))
4173 (choose-completion-string completion buffer base-size)))
4174
4175 ;; Delete the longest partial match for STRING
4176 ;; that can be found before POINT.
4177 (defun choose-completion-delete-max-match (string)
4178 (let ((opoint (point))
4179 len)
4180 ;; Try moving back by the length of the string.
4181 (goto-char (max (- (point) (length string))
4182 (minibuffer-prompt-end)))
4183 ;; See how far back we were actually able to move. That is the
4184 ;; upper bound on how much we can match and delete.
4185 (setq len (- opoint (point)))
4186 (if completion-ignore-case
4187 (setq string (downcase string)))
4188 (while (and (> len 0)
4189 (let ((tail (buffer-substring (point) opoint)))
4190 (if completion-ignore-case
4191 (setq tail (downcase tail)))
4192 (not (string= tail (substring string 0 len)))))
4193 (setq len (1- len))
4194 (forward-char 1))
4195 (delete-char len)))
4196
4197 (defvar choose-completion-string-functions nil
4198 "Functions that may override the normal insertion of a completion choice.
4199 These functions are called in order with four arguments:
4200 CHOICE - the string to insert in the buffer,
4201 BUFFER - the buffer in which the choice should be inserted,
4202 MINI-P - non-nil iff BUFFER is a minibuffer, and
4203 BASE-SIZE - the number of characters in BUFFER before
4204 the string being completed.
4205
4206 If a function in the list returns non-nil, that function is supposed
4207 to have inserted the CHOICE in the BUFFER, and possibly exited
4208 the minibuffer; no further functions will be called.
4209
4210 If all functions in the list return nil, that means to use
4211 the default method of inserting the completion in BUFFER.")
4212
4213 (defun choose-completion-string (choice &optional buffer base-size)
4214 "Switch to BUFFER and insert the completion choice CHOICE.
4215 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
4216 to keep. If it is nil, we call `choose-completion-delete-max-match'
4217 to decide what to delete."
4218
4219 ;; If BUFFER is the minibuffer, exit the minibuffer
4220 ;; unless it is reading a file name and CHOICE is a directory,
4221 ;; or completion-no-auto-exit is non-nil.
4222
4223 (let* ((buffer (or buffer completion-reference-buffer))
4224 (mini-p (minibufferp buffer)))
4225 ;; If BUFFER is a minibuffer, barf unless it's the currently
4226 ;; active minibuffer.
4227 (if (and mini-p
4228 (or (not (active-minibuffer-window))
4229 (not (equal buffer
4230 (window-buffer (active-minibuffer-window))))))
4231 (error "Minibuffer is not active for completion")
4232 (unless (run-hook-with-args-until-success
4233 'choose-completion-string-functions
4234 choice buffer mini-p base-size)
4235 ;; Insert the completion into the buffer where it was requested.
4236 (set-buffer buffer)
4237 (if base-size
4238 (delete-region (+ base-size (if mini-p
4239 (minibuffer-prompt-end)
4240 (point-min)))
4241 (point))
4242 (choose-completion-delete-max-match choice))
4243 (insert choice)
4244 (remove-text-properties (- (point) (length choice)) (point)
4245 '(mouse-face nil))
4246 ;; Update point in the window that BUFFER is showing in.
4247 (let ((window (get-buffer-window buffer t)))
4248 (set-window-point window (point)))
4249 ;; If completing for the minibuffer, exit it with this choice.
4250 (and (not completion-no-auto-exit)
4251 (equal buffer (window-buffer (minibuffer-window)))
4252 minibuffer-completion-table
4253 ;; If this is reading a file name, and the file name chosen
4254 ;; is a directory, don't exit the minibuffer.
4255 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
4256 (file-directory-p (field-string (point-max))))
4257 (let ((mini (active-minibuffer-window)))
4258 (select-window mini)
4259 (when minibuffer-auto-raise
4260 (raise-frame (window-frame mini))))
4261 (exit-minibuffer)))))))
4262
4263 (defun completion-list-mode ()
4264 "Major mode for buffers showing lists of possible completions.
4265 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
4266 to select the completion near point.
4267 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
4268 with the mouse."
4269 (interactive)
4270 (kill-all-local-variables)
4271 (use-local-map completion-list-mode-map)
4272 (setq mode-name "Completion List")
4273 (setq major-mode 'completion-list-mode)
4274 (make-local-variable 'completion-base-size)
4275 (setq completion-base-size nil)
4276 (run-hooks 'completion-list-mode-hook))
4277
4278 (defun completion-list-mode-finish ()
4279 "Finish setup of the completions buffer.
4280 Called from `temp-buffer-show-hook'."
4281 (when (eq major-mode 'completion-list-mode)
4282 (toggle-read-only 1)))
4283
4284 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
4285
4286 (defvar completion-setup-hook nil
4287 "Normal hook run at the end of setting up a completion list buffer.
4288 When this hook is run, the current buffer is the one in which the
4289 command to display the completion list buffer was run.
4290 The completion list buffer is available as the value of `standard-output'.")
4291
4292 ;; This function goes in completion-setup-hook, so that it is called
4293 ;; after the text of the completion list buffer is written.
4294 (defface completions-first-difference
4295 '((t (:inherit bold)))
4296 "Face put on the first uncommon character in completions in *Completions* buffer."
4297 :group 'completion)
4298
4299 (defface completions-common-part
4300 '((t (:inherit default)))
4301 "Face put on the common prefix substring in completions in *Completions* buffer.
4302 The idea of `completions-common-part' is that you can use it to
4303 make the common parts less visible than normal, so that the rest
4304 of the differing parts is, by contrast, slightly highlighted."
4305 :group 'completion)
4306
4307 ;; This is for packages that need to bind it to a non-default regexp
4308 ;; in order to make the first-differing character highlight work
4309 ;; to their liking
4310 (defvar completion-root-regexp "^/"
4311 "Regexp to use in `completion-setup-function' to find the root directory.")
4312
4313 (defun completion-setup-function ()
4314 (let ((mainbuf (current-buffer))
4315 (mbuf-contents (minibuffer-contents)))
4316 ;; When reading a file name in the minibuffer,
4317 ;; set default-directory in the minibuffer
4318 ;; so it will get copied into the completion list buffer.
4319 (if minibuffer-completing-file-name
4320 (with-current-buffer mainbuf
4321 (setq default-directory (file-name-directory mbuf-contents))))
4322 ;; If partial-completion-mode is on, point might not be after the
4323 ;; last character in the minibuffer.
4324 ;; FIXME: This still doesn't work if the text to be completed
4325 ;; starts with a `-'.
4326 (when (and partial-completion-mode (not (eobp)))
4327 (setq mbuf-contents
4328 (substring mbuf-contents 0 (- (point) (point-max)))))
4329 (with-current-buffer standard-output
4330 (completion-list-mode)
4331 (make-local-variable 'completion-reference-buffer)
4332 (setq completion-reference-buffer mainbuf)
4333 (if minibuffer-completing-file-name
4334 ;; For file name completion,
4335 ;; use the number of chars before the start of the
4336 ;; last file name component.
4337 (setq completion-base-size
4338 (with-current-buffer mainbuf
4339 (save-excursion
4340 (goto-char (point-max))
4341 (skip-chars-backward completion-root-regexp)
4342 (- (point) (minibuffer-prompt-end)))))
4343 ;; Otherwise, in minibuffer, the whole input is being completed.
4344 (if (minibufferp mainbuf)
4345 (setq completion-base-size 0)))
4346 ;; Put faces on first uncommon characters and common parts.
4347 (when completion-base-size
4348 (let* ((common-string-length
4349 (- (length mbuf-contents) completion-base-size))
4350 (element-start (next-single-property-change
4351 (point-min)
4352 'mouse-face))
4353 (element-common-end
4354 (+ (or element-start nil) common-string-length))
4355 (maxp (point-max)))
4356 (while (and element-start (< element-common-end maxp))
4357 (when (and (get-char-property element-start 'mouse-face)
4358 (get-char-property element-common-end 'mouse-face))
4359 (put-text-property element-start element-common-end
4360 'font-lock-face 'completions-common-part)
4361 (put-text-property element-common-end (1+ element-common-end)
4362 'font-lock-face 'completions-first-difference))
4363 (setq element-start (next-single-property-change
4364 element-start
4365 'mouse-face))
4366 (if element-start
4367 (setq element-common-end (+ element-start common-string-length))))))
4368 ;; Insert help string.
4369 (goto-char (point-min))
4370 (if (display-mouse-p)
4371 (insert (substitute-command-keys
4372 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
4373 (insert (substitute-command-keys
4374 "In this buffer, type \\[choose-completion] to \
4375 select the completion near point.\n\n")))))
4376
4377 (add-hook 'completion-setup-hook 'completion-setup-function)
4378
4379 (define-key minibuffer-local-completion-map [prior]
4380 'switch-to-completions)
4381 (define-key minibuffer-local-must-match-map [prior]
4382 'switch-to-completions)
4383 (define-key minibuffer-local-completion-map "\M-v"
4384 'switch-to-completions)
4385 (define-key minibuffer-local-must-match-map "\M-v"
4386 'switch-to-completions)
4387
4388 (defun switch-to-completions ()
4389 "Select the completion list window."
4390 (interactive)
4391 ;; Make sure we have a completions window.
4392 (or (get-buffer-window "*Completions*")
4393 (minibuffer-completion-help))
4394 (let ((window (get-buffer-window "*Completions*")))
4395 (when window
4396 (select-window window)
4397 (goto-char (point-min))
4398 (search-forward "\n\n")
4399 (forward-line 1))))
4400
4401 ;; Support keyboard commands to turn on various modifiers.
4402
4403 ;; These functions -- which are not commands -- each add one modifier
4404 ;; to the following event.
4405
4406 (defun event-apply-alt-modifier (ignore-prompt)
4407 "\\<function-key-map>Add the Alt modifier to the following event.
4408 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
4409 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
4410 (defun event-apply-super-modifier (ignore-prompt)
4411 "\\<function-key-map>Add the Super modifier to the following event.
4412 For example, type \\[event-apply-super-modifier] & to enter Super-&."
4413 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
4414 (defun event-apply-hyper-modifier (ignore-prompt)
4415 "\\<function-key-map>Add the Hyper modifier to the following event.
4416 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
4417 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
4418 (defun event-apply-shift-modifier (ignore-prompt)
4419 "\\<function-key-map>Add the Shift modifier to the following event.
4420 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
4421 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
4422 (defun event-apply-control-modifier (ignore-prompt)
4423 "\\<function-key-map>Add the Ctrl modifier to the following event.
4424 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
4425 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
4426 (defun event-apply-meta-modifier (ignore-prompt)
4427 "\\<function-key-map>Add the Meta modifier to the following event.
4428 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
4429 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
4430
4431 (defun event-apply-modifier (event symbol lshiftby prefix)
4432 "Apply a modifier flag to event EVENT.
4433 SYMBOL is the name of this modifier, as a symbol.
4434 LSHIFTBY is the numeric value of this modifier, in keyboard events.
4435 PREFIX is the string that represents this modifier in an event type symbol."
4436 (if (numberp event)
4437 (cond ((eq symbol 'control)
4438 (if (and (<= (downcase event) ?z)
4439 (>= (downcase event) ?a))
4440 (- (downcase event) ?a -1)
4441 (if (and (<= (downcase event) ?Z)
4442 (>= (downcase event) ?A))
4443 (- (downcase event) ?A -1)
4444 (logior (lsh 1 lshiftby) event))))
4445 ((eq symbol 'shift)
4446 (if (and (<= (downcase event) ?z)
4447 (>= (downcase event) ?a))
4448 (upcase event)
4449 (logior (lsh 1 lshiftby) event)))
4450 (t
4451 (logior (lsh 1 lshiftby) event)))
4452 (if (memq symbol (event-modifiers event))
4453 event
4454 (let ((event-type (if (symbolp event) event (car event))))
4455 (setq event-type (intern (concat prefix (symbol-name event-type))))
4456 (if (symbolp event)
4457 event-type
4458 (cons event-type (cdr event)))))))
4459
4460 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
4461 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
4462 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
4463 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
4464 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
4465 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
4466
4467 ;;;; Keypad support.
4468
4469 ;;; Make the keypad keys act like ordinary typing keys. If people add
4470 ;;; bindings for the function key symbols, then those bindings will
4471 ;;; override these, so this shouldn't interfere with any existing
4472 ;;; bindings.
4473
4474 ;; Also tell read-char how to handle these keys.
4475 (mapc
4476 (lambda (keypad-normal)
4477 (let ((keypad (nth 0 keypad-normal))
4478 (normal (nth 1 keypad-normal)))
4479 (put keypad 'ascii-character normal)
4480 (define-key function-key-map (vector keypad) (vector normal))))
4481 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
4482 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
4483 (kp-space ?\ )
4484 (kp-tab ?\t)
4485 (kp-enter ?\r)
4486 (kp-multiply ?*)
4487 (kp-add ?+)
4488 (kp-separator ?,)
4489 (kp-subtract ?-)
4490 (kp-decimal ?.)
4491 (kp-divide ?/)
4492 (kp-equal ?=)))
4493 \f
4494 ;;;;
4495 ;;;; forking a twin copy of a buffer.
4496 ;;;;
4497
4498 (defvar clone-buffer-hook nil
4499 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
4500
4501 (defun clone-process (process &optional newname)
4502 "Create a twin copy of PROCESS.
4503 If NEWNAME is nil, it defaults to PROCESS' name;
4504 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
4505 If PROCESS is associated with a buffer, the new process will be associated
4506 with the current buffer instead.
4507 Returns nil if PROCESS has already terminated."
4508 (setq newname (or newname (process-name process)))
4509 (if (string-match "<[0-9]+>\\'" newname)
4510 (setq newname (substring newname 0 (match-beginning 0))))
4511 (when (memq (process-status process) '(run stop open))
4512 (let* ((process-connection-type (process-tty-name process))
4513 (new-process
4514 (if (memq (process-status process) '(open))
4515 (let ((args (process-contact process t)))
4516 (setq args (plist-put args :name newname))
4517 (setq args (plist-put args :buffer
4518 (if (process-buffer process)
4519 (current-buffer))))
4520 (apply 'make-network-process args))
4521 (apply 'start-process newname
4522 (if (process-buffer process) (current-buffer))
4523 (process-command process)))))
4524 (set-process-query-on-exit-flag
4525 new-process (process-query-on-exit-flag process))
4526 (set-process-inherit-coding-system-flag
4527 new-process (process-inherit-coding-system-flag process))
4528 (set-process-filter new-process (process-filter process))
4529 (set-process-sentinel new-process (process-sentinel process))
4530 (set-process-plist new-process (copy-sequence (process-plist process)))
4531 new-process)))
4532
4533 ;; things to maybe add (currently partly covered by `funcall mode'):
4534 ;; - syntax-table
4535 ;; - overlays
4536 (defun clone-buffer (&optional newname display-flag)
4537 "Create and return a twin copy of the current buffer.
4538 Unlike an indirect buffer, the new buffer can be edited
4539 independently of the old one (if it is not read-only).
4540 NEWNAME is the name of the new buffer. It may be modified by
4541 adding or incrementing <N> at the end as necessary to create a
4542 unique buffer name. If nil, it defaults to the name of the
4543 current buffer, with the proper suffix. If DISPLAY-FLAG is
4544 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
4545 clone a file-visiting buffer, or a buffer whose major mode symbol
4546 has a non-nil `no-clone' property, results in an error.
4547
4548 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
4549 current buffer with appropriate suffix. However, if a prefix
4550 argument is given, then the command prompts for NEWNAME in the
4551 minibuffer.
4552
4553 This runs the normal hook `clone-buffer-hook' in the new buffer
4554 after it has been set up properly in other respects."
4555 (interactive
4556 (progn
4557 (if buffer-file-name
4558 (error "Cannot clone a file-visiting buffer"))
4559 (if (get major-mode 'no-clone)
4560 (error "Cannot clone a buffer in %s mode" mode-name))
4561 (list (if current-prefix-arg (read-string "Name: "))
4562 t)))
4563 (if buffer-file-name
4564 (error "Cannot clone a file-visiting buffer"))
4565 (if (get major-mode 'no-clone)
4566 (error "Cannot clone a buffer in %s mode" mode-name))
4567 (setq newname (or newname (buffer-name)))
4568 (if (string-match "<[0-9]+>\\'" newname)
4569 (setq newname (substring newname 0 (match-beginning 0))))
4570 (let ((buf (current-buffer))
4571 (ptmin (point-min))
4572 (ptmax (point-max))
4573 (pt (point))
4574 (mk (if mark-active (mark t)))
4575 (modified (buffer-modified-p))
4576 (mode major-mode)
4577 (lvars (buffer-local-variables))
4578 (process (get-buffer-process (current-buffer)))
4579 (new (generate-new-buffer (or newname (buffer-name)))))
4580 (save-restriction
4581 (widen)
4582 (with-current-buffer new
4583 (insert-buffer-substring buf)))
4584 (with-current-buffer new
4585 (narrow-to-region ptmin ptmax)
4586 (goto-char pt)
4587 (if mk (set-mark mk))
4588 (set-buffer-modified-p modified)
4589
4590 ;; Clone the old buffer's process, if any.
4591 (when process (clone-process process))
4592
4593 ;; Now set up the major mode.
4594 (funcall mode)
4595
4596 ;; Set up other local variables.
4597 (mapcar (lambda (v)
4598 (condition-case () ;in case var is read-only
4599 (if (symbolp v)
4600 (makunbound v)
4601 (set (make-local-variable (car v)) (cdr v)))
4602 (error nil)))
4603 lvars)
4604
4605 ;; Run any hooks (typically set up by the major mode
4606 ;; for cloning to work properly).
4607 (run-hooks 'clone-buffer-hook))
4608 (if display-flag (pop-to-buffer new))
4609 new))
4610
4611
4612 (defun clone-indirect-buffer (newname display-flag &optional norecord)
4613 "Create an indirect buffer that is a twin copy of the current buffer.
4614
4615 Give the indirect buffer name NEWNAME. Interactively, read NEW-NAME
4616 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
4617 or if not called with a prefix arg, NEWNAME defaults to the current
4618 buffer's name. The name is modified by adding a `<N>' suffix to it
4619 or by incrementing the N in an existing suffix.
4620
4621 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
4622 This is always done when called interactively.
4623
4624 Optional last arg NORECORD non-nil means do not put this buffer at the
4625 front of the list of recently selected ones."
4626 (interactive
4627 (progn
4628 (if (get major-mode 'no-clone-indirect)
4629 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
4630 (list (if current-prefix-arg
4631 (read-string "BName of indirect buffer: "))
4632 t)))
4633 (if (get major-mode 'no-clone-indirect)
4634 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
4635 (setq newname (or newname (buffer-name)))
4636 (if (string-match "<[0-9]+>\\'" newname)
4637 (setq newname (substring newname 0 (match-beginning 0))))
4638 (let* ((name (generate-new-buffer-name newname))
4639 (buffer (make-indirect-buffer (current-buffer) name t)))
4640 (when display-flag
4641 (pop-to-buffer buffer norecord))
4642 buffer))
4643
4644
4645 (defun clone-indirect-buffer-other-window (buffer &optional norecord)
4646 "Create an indirect buffer that is a twin copy of BUFFER.
4647 Select the new buffer in another window.
4648 Optional second arg NORECORD non-nil means do not put this buffer at
4649 the front of the list of recently selected ones."
4650 (interactive "bClone buffer in other window: ")
4651 (let ((pop-up-windows t))
4652 (set-buffer buffer)
4653 (clone-indirect-buffer nil t norecord)))
4654
4655 (define-key ctl-x-4-map "c" 'clone-indirect-buffer-other-window)
4656 \f
4657 ;;; Handling of Backspace and Delete keys.
4658
4659 (defcustom normal-erase-is-backspace nil
4660 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
4661
4662 On window systems, the default value of this option is chosen
4663 according to the keyboard used. If the keyboard has both a Backspace
4664 key and a Delete key, and both are mapped to their usual meanings, the
4665 option's default value is set to t, so that Backspace can be used to
4666 delete backward, and Delete can be used to delete forward.
4667
4668 If not running under a window system, customizing this option accomplishes
4669 a similar effect by mapping C-h, which is usually generated by the
4670 Backspace key, to DEL, and by mapping DEL to C-d via
4671 `keyboard-translate'. The former functionality of C-h is available on
4672 the F1 key. You should probably not use this setting if you don't
4673 have both Backspace, Delete and F1 keys.
4674
4675 Setting this variable with setq doesn't take effect. Programmatically,
4676 call `normal-erase-is-backspace-mode' (which see) instead."
4677 :type 'boolean
4678 :group 'editing-basics
4679 :version "21.1"
4680 :set (lambda (symbol value)
4681 ;; The fboundp is because of a problem with :set when
4682 ;; dumping Emacs. It doesn't really matter.
4683 (if (fboundp 'normal-erase-is-backspace-mode)
4684 (normal-erase-is-backspace-mode (or value 0))
4685 (set-default symbol value))))
4686
4687
4688 (defun normal-erase-is-backspace-mode (&optional arg)
4689 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
4690
4691 With numeric arg, turn the mode on if and only if ARG is positive.
4692
4693 On window systems, when this mode is on, Delete is mapped to C-d and
4694 Backspace is mapped to DEL; when this mode is off, both Delete and
4695 Backspace are mapped to DEL. (The remapping goes via
4696 `function-key-map', so binding Delete or Backspace in the global or
4697 local keymap will override that.)
4698
4699 In addition, on window systems, the bindings of C-Delete, M-Delete,
4700 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
4701 the global keymap in accordance with the functionality of Delete and
4702 Backspace. For example, if Delete is remapped to C-d, which deletes
4703 forward, C-Delete is bound to `kill-word', but if Delete is remapped
4704 to DEL, which deletes backward, C-Delete is bound to
4705 `backward-kill-word'.
4706
4707 If not running on a window system, a similar effect is accomplished by
4708 remapping C-h (normally produced by the Backspace key) and DEL via
4709 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
4710 to C-d; if it's off, the keys are not remapped.
4711
4712 When not running on a window system, and this mode is turned on, the
4713 former functionality of C-h is available on the F1 key. You should
4714 probably not turn on this mode on a text-only terminal if you don't
4715 have both Backspace, Delete and F1 keys.
4716
4717 See also `normal-erase-is-backspace'."
4718 (interactive "P")
4719 (setq normal-erase-is-backspace
4720 (if arg
4721 (> (prefix-numeric-value arg) 0)
4722 (not normal-erase-is-backspace)))
4723
4724 (cond ((or (memq window-system '(x w32 mac pc))
4725 (memq system-type '(ms-dos windows-nt)))
4726 (let ((bindings
4727 `(([C-delete] [C-backspace])
4728 ([M-delete] [M-backspace])
4729 ([C-M-delete] [C-M-backspace])
4730 (,esc-map
4731 [C-delete] [C-backspace])))
4732 (old-state (lookup-key function-key-map [delete])))
4733
4734 (if normal-erase-is-backspace
4735 (progn
4736 (define-key function-key-map [delete] [?\C-d])
4737 (define-key function-key-map [kp-delete] [?\C-d])
4738 (define-key function-key-map [backspace] [?\C-?]))
4739 (define-key function-key-map [delete] [?\C-?])
4740 (define-key function-key-map [kp-delete] [?\C-?])
4741 (define-key function-key-map [backspace] [?\C-?]))
4742
4743 ;; Maybe swap bindings of C-delete and C-backspace, etc.
4744 (unless (equal old-state (lookup-key function-key-map [delete]))
4745 (dolist (binding bindings)
4746 (let ((map global-map))
4747 (when (keymapp (car binding))
4748 (setq map (car binding) binding (cdr binding)))
4749 (let* ((key1 (nth 0 binding))
4750 (key2 (nth 1 binding))
4751 (binding1 (lookup-key map key1))
4752 (binding2 (lookup-key map key2)))
4753 (define-key map key1 binding2)
4754 (define-key map key2 binding1)))))))
4755 (t
4756 (if normal-erase-is-backspace
4757 (progn
4758 (keyboard-translate ?\C-h ?\C-?)
4759 (keyboard-translate ?\C-? ?\C-d))
4760 (keyboard-translate ?\C-h ?\C-h)
4761 (keyboard-translate ?\C-? ?\C-?))))
4762
4763 (run-hooks 'normal-erase-is-backspace-hook)
4764 (if (interactive-p)
4765 (message "Delete key deletes %s"
4766 (if normal-erase-is-backspace "forward" "backward"))))
4767 \f
4768 (defcustom idle-update-delay 0.5
4769 "*Idle time delay before updating various things on the screen.
4770 Various Emacs features that update auxiliary information when point moves
4771 wait this many seconds after Emacs becomes idle before doing an update."
4772 :type 'number
4773 :group 'display
4774 :version "21.4")
4775 \f
4776 (defvar vis-mode-saved-buffer-invisibility-spec nil
4777 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
4778
4779 (define-minor-mode visible-mode
4780 "Toggle Visible mode.
4781 With argument ARG turn Visible mode on iff ARG is positive.
4782
4783 Enabling Visible mode makes all invisible text temporarily visible.
4784 Disabling Visible mode turns off that effect. Visible mode
4785 works by saving the value of `buffer-invisibility-spec' and setting it to nil."
4786 :lighter " Vis"
4787 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
4788 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
4789 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
4790 (when visible-mode
4791 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
4792 buffer-invisibility-spec)
4793 (setq buffer-invisibility-spec nil)))
4794 \f
4795 ;; Minibuffer prompt stuff.
4796
4797 ;(defun minibuffer-prompt-modification (start end)
4798 ; (error "You cannot modify the prompt"))
4799 ;
4800 ;
4801 ;(defun minibuffer-prompt-insertion (start end)
4802 ; (let ((inhibit-modification-hooks t))
4803 ; (delete-region start end)
4804 ; ;; Discard undo information for the text insertion itself
4805 ; ;; and for the text deletion.above.
4806 ; (when (consp buffer-undo-list)
4807 ; (setq buffer-undo-list (cddr buffer-undo-list)))
4808 ; (message "You cannot modify the prompt")))
4809 ;
4810 ;
4811 ;(setq minibuffer-prompt-properties
4812 ; (list 'modification-hooks '(minibuffer-prompt-modification)
4813 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
4814 ;
4815
4816 (provide 'simple)
4817
4818 ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
4819 ;;; simple.el ends here