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