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