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