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