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