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