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