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