]> code.delx.au - gnu-emacs/blob - lisp/simple.el
*** empty log message ***
[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.1
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, use persistent overlays fontified in `next-error' face.
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 "Delay")
138 (const :tag "Persistent overlay" 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.1
145 "*Highlighting of locations in non-selected source buffers.
146 If number, highlight the locus in `next-error' face for given time in seconds.
147 If t, use persistent overlays fontified in `next-error' face.
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 "Delay")
151 (const :tag "Persistent overlay" 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 transient-mark-mode mark-active
1505 " for region"))))
1506 (let ((undo-in-progress t))
1507 (setq pending-undo-list (primitive-undo n pending-undo-list))
1508 (if (null pending-undo-list)
1509 (setq pending-undo-list t))))
1510
1511 ;; Deep copy of a list
1512 (defun undo-copy-list (list)
1513 "Make a copy of undo list LIST."
1514 (mapcar 'undo-copy-list-1 list))
1515
1516 (defun undo-copy-list-1 (elt)
1517 (if (consp elt)
1518 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1519 elt))
1520
1521 (defun undo-start (&optional beg end)
1522 "Set `pending-undo-list' to the front of the undo list.
1523 The next call to `undo-more' will undo the most recently made change.
1524 If BEG and END are specified, then only undo elements
1525 that apply to text between BEG and END are used; other undo elements
1526 are ignored. If BEG and END are nil, all undo elements are used."
1527 (if (eq buffer-undo-list t)
1528 (error "No undo information in this buffer"))
1529 (setq pending-undo-list
1530 (if (and beg end (not (= beg end)))
1531 (undo-make-selective-list (min beg end) (max beg end))
1532 buffer-undo-list)))
1533
1534 (defvar undo-adjusted-markers)
1535
1536 (defun undo-make-selective-list (start end)
1537 "Return a list of undo elements for the region START to END.
1538 The elements come from `buffer-undo-list', but we keep only
1539 the elements inside this region, and discard those outside this region.
1540 If we find an element that crosses an edge of this region,
1541 we stop and ignore all further elements."
1542 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1543 (undo-list (list nil))
1544 undo-adjusted-markers
1545 some-rejected
1546 undo-elt undo-elt temp-undo-list delta)
1547 (while undo-list-copy
1548 (setq undo-elt (car undo-list-copy))
1549 (let ((keep-this
1550 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1551 ;; This is a "was unmodified" element.
1552 ;; Keep it if we have kept everything thus far.
1553 (not some-rejected))
1554 (t
1555 (undo-elt-in-region undo-elt start end)))))
1556 (if keep-this
1557 (progn
1558 (setq end (+ end (cdr (undo-delta undo-elt))))
1559 ;; Don't put two nils together in the list
1560 (if (not (and (eq (car undo-list) nil)
1561 (eq undo-elt nil)))
1562 (setq undo-list (cons undo-elt undo-list))))
1563 (if (undo-elt-crosses-region undo-elt start end)
1564 (setq undo-list-copy nil)
1565 (setq some-rejected t)
1566 (setq temp-undo-list (cdr undo-list-copy))
1567 (setq delta (undo-delta undo-elt))
1568
1569 (when (/= (cdr delta) 0)
1570 (let ((position (car delta))
1571 (offset (cdr delta)))
1572
1573 ;; Loop down the earlier events adjusting their buffer
1574 ;; positions to reflect the fact that a change to the buffer
1575 ;; isn't being undone. We only need to process those element
1576 ;; types which undo-elt-in-region will return as being in
1577 ;; the region since only those types can ever get into the
1578 ;; output
1579
1580 (while temp-undo-list
1581 (setq undo-elt (car temp-undo-list))
1582 (cond ((integerp undo-elt)
1583 (if (>= undo-elt position)
1584 (setcar temp-undo-list (- undo-elt offset))))
1585 ((atom undo-elt) nil)
1586 ((stringp (car undo-elt))
1587 ;; (TEXT . POSITION)
1588 (let ((text-pos (abs (cdr undo-elt)))
1589 (point-at-end (< (cdr undo-elt) 0 )))
1590 (if (>= text-pos position)
1591 (setcdr undo-elt (* (if point-at-end -1 1)
1592 (- text-pos offset))))))
1593 ((integerp (car undo-elt))
1594 ;; (BEGIN . END)
1595 (when (>= (car undo-elt) position)
1596 (setcar undo-elt (- (car undo-elt) offset))
1597 (setcdr undo-elt (- (cdr undo-elt) offset))))
1598 ((null (car undo-elt))
1599 ;; (nil PROPERTY VALUE BEG . END)
1600 (let ((tail (nthcdr 3 undo-elt)))
1601 (when (>= (car tail) position)
1602 (setcar tail (- (car tail) offset))
1603 (setcdr tail (- (cdr tail) offset))))))
1604 (setq temp-undo-list (cdr temp-undo-list))))))))
1605 (setq undo-list-copy (cdr undo-list-copy)))
1606 (nreverse undo-list)))
1607
1608 (defun undo-elt-in-region (undo-elt start end)
1609 "Determine whether UNDO-ELT falls inside the region START ... END.
1610 If it crosses the edge, we return nil."
1611 (cond ((integerp undo-elt)
1612 (and (>= undo-elt start)
1613 (<= undo-elt end)))
1614 ((eq undo-elt nil)
1615 t)
1616 ((atom undo-elt)
1617 nil)
1618 ((stringp (car undo-elt))
1619 ;; (TEXT . POSITION)
1620 (and (>= (abs (cdr undo-elt)) start)
1621 (< (abs (cdr undo-elt)) end)))
1622 ((and (consp undo-elt) (markerp (car undo-elt)))
1623 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1624 ;; See if MARKER is inside the region.
1625 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1626 (unless alist-elt
1627 (setq alist-elt (cons (car undo-elt)
1628 (marker-position (car undo-elt))))
1629 (setq undo-adjusted-markers
1630 (cons alist-elt undo-adjusted-markers)))
1631 (and (cdr alist-elt)
1632 (>= (cdr alist-elt) start)
1633 (<= (cdr alist-elt) end))))
1634 ((null (car undo-elt))
1635 ;; (nil PROPERTY VALUE BEG . END)
1636 (let ((tail (nthcdr 3 undo-elt)))
1637 (and (>= (car tail) start)
1638 (<= (cdr tail) end))))
1639 ((integerp (car undo-elt))
1640 ;; (BEGIN . END)
1641 (and (>= (car undo-elt) start)
1642 (<= (cdr undo-elt) end)))))
1643
1644 (defun undo-elt-crosses-region (undo-elt start end)
1645 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1646 This assumes we have already decided that UNDO-ELT
1647 is not *inside* the region START...END."
1648 (cond ((atom undo-elt) nil)
1649 ((null (car undo-elt))
1650 ;; (nil PROPERTY VALUE BEG . END)
1651 (let ((tail (nthcdr 3 undo-elt)))
1652 (not (or (< (car tail) end)
1653 (> (cdr tail) start)))))
1654 ((integerp (car undo-elt))
1655 ;; (BEGIN . END)
1656 (not (or (< (car undo-elt) end)
1657 (> (cdr undo-elt) start))))))
1658
1659 ;; Return the first affected buffer position and the delta for an undo element
1660 ;; delta is defined as the change in subsequent buffer positions if we *did*
1661 ;; the undo.
1662 (defun undo-delta (undo-elt)
1663 (if (consp undo-elt)
1664 (cond ((stringp (car undo-elt))
1665 ;; (TEXT . POSITION)
1666 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1667 ((integerp (car undo-elt))
1668 ;; (BEGIN . END)
1669 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1670 (t
1671 '(0 . 0)))
1672 '(0 . 0)))
1673
1674 (defcustom undo-ask-before-discard nil
1675 "If non-nil ask about discarding undo info for the current command.
1676 Normally, Emacs discards the undo info for the current command if
1677 it exceeds `undo-outer-limit'. But if you set this option
1678 non-nil, it asks in the echo area whether to discard the info.
1679 If you answer no, there a slight risk that Emacs might crash, so
1680 only do it if you really want to undo the command.
1681
1682 This option is mainly intended for debugging. You have to be
1683 careful if you use it for other purposes. Garbage collection is
1684 inhibited while the question is asked, meaning that Emacs might
1685 leak memory. So you should make sure that you do not wait
1686 excessively long before answering the question."
1687 :type 'boolean
1688 :group 'undo
1689 :version "22.1")
1690
1691 (defvar undo-extra-outer-limit nil
1692 "If non-nil, an extra level of size that's ok in an undo item.
1693 We don't ask the user about truncating the undo list until the
1694 current item gets bigger than this amount.
1695
1696 This variable only matters if `undo-ask-before-discard' is non-nil.")
1697 (make-variable-buffer-local 'undo-extra-outer-limit)
1698
1699 ;; When the first undo batch in an undo list is longer than
1700 ;; undo-outer-limit, this function gets called to warn the user that
1701 ;; the undo info for the current command was discarded. Garbage
1702 ;; collection is inhibited around the call, so it had better not do a
1703 ;; lot of consing.
1704 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
1705 (defun undo-outer-limit-truncate (size)
1706 (if undo-ask-before-discard
1707 (when (or (null undo-extra-outer-limit)
1708 (> size undo-extra-outer-limit))
1709 ;; Don't ask the question again unless it gets even bigger.
1710 ;; This applies, in particular, if the user quits from the question.
1711 ;; Such a quit quits out of GC, but something else will call GC
1712 ;; again momentarily. It will call this function again,
1713 ;; but we don't want to ask the question again.
1714 (setq undo-extra-outer-limit (+ size 50000))
1715 (if (let (use-dialog-box track-mouse executing-kbd-macro )
1716 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
1717 (buffer-name) size)))
1718 (progn (setq buffer-undo-list nil)
1719 (setq undo-extra-outer-limit nil)
1720 t)
1721 nil))
1722 (display-warning '(undo discard-info)
1723 (concat
1724 (format "Buffer `%s' undo info was %d bytes long.\n"
1725 (buffer-name) size)
1726 "The undo info was discarded because it exceeded \
1727 `undo-outer-limit'.
1728
1729 This is normal if you executed a command that made a huge change
1730 to the buffer. In that case, to prevent similar problems in the
1731 future, set `undo-outer-limit' to a value that is large enough to
1732 cover the maximum size of normal changes you expect a single
1733 command to make, but not so large that it might exceed the
1734 maximum memory allotted to Emacs.
1735
1736 If you did not execute any such command, the situation is
1737 probably due to a bug and you should report it.
1738
1739 You can disable the popping up of this buffer by adding the entry
1740 \(undo discard-info) to the user option `warning-suppress-types'.\n")
1741 :warning)
1742 (setq buffer-undo-list nil)
1743 t))
1744 \f
1745 (defvar shell-command-history nil
1746 "History list for some commands that read shell commands.")
1747
1748 (defvar shell-command-switch "-c"
1749 "Switch used to have the shell execute its command line argument.")
1750
1751 (defvar shell-command-default-error-buffer nil
1752 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1753 This buffer is used when `shell-command' or `shell-command-on-region'
1754 is run interactively. A value of nil means that output to stderr and
1755 stdout will be intermixed in the output stream.")
1756
1757 (defun shell-command (command &optional output-buffer error-buffer)
1758 "Execute string COMMAND in inferior shell; display output, if any.
1759 With prefix argument, insert the COMMAND's output at point.
1760
1761 If COMMAND ends in ampersand, execute it asynchronously.
1762 The output appears in the buffer `*Async Shell Command*'.
1763 That buffer is in shell mode.
1764
1765 Otherwise, COMMAND is executed synchronously. The output appears in
1766 the buffer `*Shell Command Output*'. If the output is short enough to
1767 display in the echo area (which is determined by the variables
1768 `resize-mini-windows' and `max-mini-window-height'), it is shown
1769 there, but it is nonetheless available in buffer `*Shell Command
1770 Output*' even though that buffer is not automatically displayed.
1771
1772 To specify a coding system for converting non-ASCII characters
1773 in the shell command output, use \\[universal-coding-system-argument]
1774 before this command.
1775
1776 Noninteractive callers can specify coding systems by binding
1777 `coding-system-for-read' and `coding-system-for-write'.
1778
1779 The optional second argument OUTPUT-BUFFER, if non-nil,
1780 says to put the output in some other buffer.
1781 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1782 If OUTPUT-BUFFER is not a buffer and not nil,
1783 insert output in current buffer. (This cannot be done asynchronously.)
1784 In either case, the output is inserted after point (leaving mark after it).
1785
1786 If the command terminates without error, but generates output,
1787 and you did not specify \"insert it in the current buffer\",
1788 the output can be displayed in the echo area or in its buffer.
1789 If the output is short enough to display in the echo area
1790 \(determined by the variable `max-mini-window-height' if
1791 `resize-mini-windows' is non-nil), it is shown there. Otherwise,
1792 the buffer containing the output is displayed.
1793
1794 If there is output and an error, and you did not specify \"insert it
1795 in the current buffer\", a message about the error goes at the end
1796 of the output.
1797
1798 If there is no output, or if output is inserted in the current buffer,
1799 then `*Shell Command Output*' is deleted.
1800
1801 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
1802 or buffer name to which to direct the command's standard error output.
1803 If it is nil, error output is mingled with regular output.
1804 In an interactive call, the variable `shell-command-default-error-buffer'
1805 specifies the value of ERROR-BUFFER."
1806
1807 (interactive (list (read-from-minibuffer "Shell command: "
1808 nil nil nil 'shell-command-history)
1809 current-prefix-arg
1810 shell-command-default-error-buffer))
1811 ;; Look for a handler in case default-directory is a remote file name.
1812 (let ((handler
1813 (find-file-name-handler (directory-file-name default-directory)
1814 'shell-command)))
1815 (if handler
1816 (funcall handler 'shell-command command output-buffer error-buffer)
1817 (if (and output-buffer
1818 (not (or (bufferp output-buffer) (stringp output-buffer))))
1819 ;; Output goes in current buffer.
1820 (let ((error-file
1821 (if error-buffer
1822 (make-temp-file
1823 (expand-file-name "scor"
1824 (or small-temporary-file-directory
1825 temporary-file-directory)))
1826 nil)))
1827 (barf-if-buffer-read-only)
1828 (push-mark nil t)
1829 ;; We do not use -f for csh; we will not support broken use of
1830 ;; .cshrcs. Even the BSD csh manual says to use
1831 ;; "if ($?prompt) exit" before things which are not useful
1832 ;; non-interactively. Besides, if someone wants their other
1833 ;; aliases for shell commands then they can still have them.
1834 (call-process shell-file-name nil
1835 (if error-file
1836 (list t error-file)
1837 t)
1838 nil shell-command-switch command)
1839 (when (and error-file (file-exists-p error-file))
1840 (if (< 0 (nth 7 (file-attributes error-file)))
1841 (with-current-buffer (get-buffer-create error-buffer)
1842 (let ((pos-from-end (- (point-max) (point))))
1843 (or (bobp)
1844 (insert "\f\n"))
1845 ;; Do no formatting while reading error file,
1846 ;; because that can run a shell command, and we
1847 ;; don't want that to cause an infinite recursion.
1848 (format-insert-file error-file nil)
1849 ;; Put point after the inserted errors.
1850 (goto-char (- (point-max) pos-from-end)))
1851 (display-buffer (current-buffer))))
1852 (delete-file error-file))
1853 ;; This is like exchange-point-and-mark, but doesn't
1854 ;; activate the mark. It is cleaner to avoid activation,
1855 ;; even though the command loop would deactivate the mark
1856 ;; because we inserted text.
1857 (goto-char (prog1 (mark t)
1858 (set-marker (mark-marker) (point)
1859 (current-buffer)))))
1860 ;; Output goes in a separate buffer.
1861 ;; Preserve the match data in case called from a program.
1862 (save-match-data
1863 (if (string-match "[ \t]*&[ \t]*\\'" command)
1864 ;; Command ending with ampersand means asynchronous.
1865 (let ((buffer (get-buffer-create
1866 (or output-buffer "*Async Shell Command*")))
1867 (directory default-directory)
1868 proc)
1869 ;; Remove the ampersand.
1870 (setq command (substring command 0 (match-beginning 0)))
1871 ;; If will kill a process, query first.
1872 (setq proc (get-buffer-process buffer))
1873 (if proc
1874 (if (yes-or-no-p "A command is running. Kill it? ")
1875 (kill-process proc)
1876 (error "Shell command in progress")))
1877 (with-current-buffer buffer
1878 (setq buffer-read-only nil)
1879 (erase-buffer)
1880 (display-buffer buffer)
1881 (setq default-directory directory)
1882 (setq proc (start-process "Shell" buffer shell-file-name
1883 shell-command-switch command))
1884 (setq mode-line-process '(":%s"))
1885 (require 'shell) (shell-mode)
1886 (set-process-sentinel proc 'shell-command-sentinel)
1887 ))
1888 (shell-command-on-region (point) (point) command
1889 output-buffer nil error-buffer)))))))
1890
1891 (defun display-message-or-buffer (message
1892 &optional buffer-name not-this-window frame)
1893 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
1894 MESSAGE may be either a string or a buffer.
1895
1896 A buffer is displayed using `display-buffer' if MESSAGE is too long for
1897 the maximum height of the echo area, as defined by `max-mini-window-height'
1898 if `resize-mini-windows' is non-nil.
1899
1900 Returns either the string shown in the echo area, or when a pop-up
1901 buffer is used, the window used to display it.
1902
1903 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
1904 name of the buffer used to display it in the case where a pop-up buffer
1905 is used, defaulting to `*Message*'. In the case where MESSAGE is a
1906 string and it is displayed in the echo area, it is not specified whether
1907 the contents are inserted into the buffer anyway.
1908
1909 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
1910 and only used if a buffer is displayed."
1911 (cond ((and (stringp message)
1912 (not (string-match "\n" message))
1913 (<= (length message) (frame-width)))
1914 ;; Trivial case where we can use the echo area
1915 (message "%s" message))
1916 ((and (stringp message)
1917 (= (string-match "\n" message) (1- (length message)))
1918 (<= (1- (length message)) (frame-width)))
1919 ;; Trivial case where we can just remove single trailing newline
1920 (message "%s" (substring message 0 (1- (length message)))))
1921 (t
1922 ;; General case
1923 (with-current-buffer
1924 (if (bufferp message)
1925 message
1926 (get-buffer-create (or buffer-name "*Message*")))
1927
1928 (unless (bufferp message)
1929 (erase-buffer)
1930 (insert message))
1931
1932 (let ((lines
1933 (if (= (buffer-size) 0)
1934 0
1935 (count-screen-lines nil nil nil (minibuffer-window)))))
1936 (cond ((= lines 0))
1937 ((and (or (<= lines 1)
1938 (<= lines
1939 (if resize-mini-windows
1940 (cond ((floatp max-mini-window-height)
1941 (* (frame-height)
1942 max-mini-window-height))
1943 ((integerp max-mini-window-height)
1944 max-mini-window-height)
1945 (t
1946 1))
1947 1)))
1948 ;; Don't use the echo area if the output buffer is
1949 ;; already dispayed in the selected frame.
1950 (not (get-buffer-window (current-buffer))))
1951 ;; Echo area
1952 (goto-char (point-max))
1953 (when (bolp)
1954 (backward-char 1))
1955 (message "%s" (buffer-substring (point-min) (point))))
1956 (t
1957 ;; Buffer
1958 (goto-char (point-min))
1959 (display-buffer (current-buffer)
1960 not-this-window frame))))))))
1961
1962
1963 ;; We have a sentinel to prevent insertion of a termination message
1964 ;; in the buffer itself.
1965 (defun shell-command-sentinel (process signal)
1966 (if (memq (process-status process) '(exit signal))
1967 (message "%s: %s."
1968 (car (cdr (cdr (process-command process))))
1969 (substring signal 0 -1))))
1970
1971 (defun shell-command-on-region (start end command
1972 &optional output-buffer replace
1973 error-buffer display-error-buffer)
1974 "Execute string COMMAND in inferior shell with region as input.
1975 Normally display output (if any) in temp buffer `*Shell Command Output*';
1976 Prefix arg means replace the region with it. Return the exit code of
1977 COMMAND.
1978
1979 To specify a coding system for converting non-ASCII characters
1980 in the input and output to the shell command, use \\[universal-coding-system-argument]
1981 before this command. By default, the input (from the current buffer)
1982 is encoded in the same coding system that will be used to save the file,
1983 `buffer-file-coding-system'. If the output is going to replace the region,
1984 then it is decoded from that same coding system.
1985
1986 The noninteractive arguments are START, END, COMMAND,
1987 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
1988 Noninteractive callers can specify coding systems by binding
1989 `coding-system-for-read' and `coding-system-for-write'.
1990
1991 If the command generates output, the output may be displayed
1992 in the echo area or in a buffer.
1993 If the output is short enough to display in the echo area
1994 \(determined by the variable `max-mini-window-height' if
1995 `resize-mini-windows' is non-nil), it is shown there. Otherwise
1996 it is displayed in the buffer `*Shell Command Output*'. The output
1997 is available in that buffer in both cases.
1998
1999 If there is output and an error, a message about the error
2000 appears at the end of the output.
2001
2002 If there is no output, or if output is inserted in the current buffer,
2003 then `*Shell Command Output*' is deleted.
2004
2005 If the optional fourth argument OUTPUT-BUFFER is non-nil,
2006 that says to put the output in some other buffer.
2007 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2008 If OUTPUT-BUFFER is not a buffer and not nil,
2009 insert output in the current buffer.
2010 In either case, the output is inserted after point (leaving mark after it).
2011
2012 If REPLACE, the optional fifth argument, is non-nil, that means insert
2013 the output in place of text from START to END, putting point and mark
2014 around it.
2015
2016 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
2017 or buffer name to which to direct the command's standard error output.
2018 If it is nil, error output is mingled with regular output.
2019 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2020 were any errors. (This is always t, interactively.)
2021 In an interactive call, the variable `shell-command-default-error-buffer'
2022 specifies the value of ERROR-BUFFER."
2023 (interactive (let (string)
2024 (unless (mark)
2025 (error "The mark is not set now, so there is no region"))
2026 ;; Do this before calling region-beginning
2027 ;; and region-end, in case subprocess output
2028 ;; relocates them while we are in the minibuffer.
2029 (setq string (read-from-minibuffer "Shell command on region: "
2030 nil nil nil
2031 'shell-command-history))
2032 ;; call-interactively recognizes region-beginning and
2033 ;; region-end specially, leaving them in the history.
2034 (list (region-beginning) (region-end)
2035 string
2036 current-prefix-arg
2037 current-prefix-arg
2038 shell-command-default-error-buffer
2039 t)))
2040 (let ((error-file
2041 (if error-buffer
2042 (make-temp-file
2043 (expand-file-name "scor"
2044 (or small-temporary-file-directory
2045 temporary-file-directory)))
2046 nil))
2047 exit-status)
2048 (if (or replace
2049 (and output-buffer
2050 (not (or (bufferp output-buffer) (stringp output-buffer)))))
2051 ;; Replace specified region with output from command.
2052 (let ((swap (and replace (< start end))))
2053 ;; Don't muck with mark unless REPLACE says we should.
2054 (goto-char start)
2055 (and replace (push-mark (point) 'nomsg))
2056 (setq exit-status
2057 (call-process-region start end shell-file-name t
2058 (if error-file
2059 (list t error-file)
2060 t)
2061 nil shell-command-switch command))
2062 ;; It is rude to delete a buffer which the command is not using.
2063 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2064 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2065 ;; (kill-buffer shell-buffer)))
2066 ;; Don't muck with mark unless REPLACE says we should.
2067 (and replace swap (exchange-point-and-mark)))
2068 ;; No prefix argument: put the output in a temp buffer,
2069 ;; replacing its entire contents.
2070 (let ((buffer (get-buffer-create
2071 (or output-buffer "*Shell Command Output*"))))
2072 (unwind-protect
2073 (if (eq buffer (current-buffer))
2074 ;; If the input is the same buffer as the output,
2075 ;; delete everything but the specified region,
2076 ;; then replace that region with the output.
2077 (progn (setq buffer-read-only nil)
2078 (delete-region (max start end) (point-max))
2079 (delete-region (point-min) (min start end))
2080 (setq exit-status
2081 (call-process-region (point-min) (point-max)
2082 shell-file-name t
2083 (if error-file
2084 (list t error-file)
2085 t)
2086 nil shell-command-switch
2087 command)))
2088 ;; Clear the output buffer, then run the command with
2089 ;; output there.
2090 (let ((directory default-directory))
2091 (save-excursion
2092 (set-buffer buffer)
2093 (setq buffer-read-only nil)
2094 (if (not output-buffer)
2095 (setq default-directory directory))
2096 (erase-buffer)))
2097 (setq exit-status
2098 (call-process-region start end shell-file-name nil
2099 (if error-file
2100 (list buffer error-file)
2101 buffer)
2102 nil shell-command-switch command)))
2103 ;; Report the output.
2104 (with-current-buffer buffer
2105 (setq mode-line-process
2106 (cond ((null exit-status)
2107 " - Error")
2108 ((stringp exit-status)
2109 (format " - Signal [%s]" exit-status))
2110 ((not (equal 0 exit-status))
2111 (format " - Exit [%d]" exit-status)))))
2112 (if (with-current-buffer buffer (> (point-max) (point-min)))
2113 ;; There's some output, display it
2114 (display-message-or-buffer buffer)
2115 ;; No output; error?
2116 (let ((output
2117 (if (and error-file
2118 (< 0 (nth 7 (file-attributes error-file))))
2119 "some error output"
2120 "no output")))
2121 (cond ((null exit-status)
2122 (message "(Shell command failed with error)"))
2123 ((equal 0 exit-status)
2124 (message "(Shell command succeeded with %s)"
2125 output))
2126 ((stringp exit-status)
2127 (message "(Shell command killed by signal %s)"
2128 exit-status))
2129 (t
2130 (message "(Shell command failed with code %d and %s)"
2131 exit-status output))))
2132 ;; Don't kill: there might be useful info in the undo-log.
2133 ;; (kill-buffer buffer)
2134 ))))
2135
2136 (when (and error-file (file-exists-p error-file))
2137 (if (< 0 (nth 7 (file-attributes error-file)))
2138 (with-current-buffer (get-buffer-create error-buffer)
2139 (let ((pos-from-end (- (point-max) (point))))
2140 (or (bobp)
2141 (insert "\f\n"))
2142 ;; Do no formatting while reading error file,
2143 ;; because that can run a shell command, and we
2144 ;; don't want that to cause an infinite recursion.
2145 (format-insert-file error-file nil)
2146 ;; Put point after the inserted errors.
2147 (goto-char (- (point-max) pos-from-end)))
2148 (and display-error-buffer
2149 (display-buffer (current-buffer)))))
2150 (delete-file error-file))
2151 exit-status))
2152
2153 (defun shell-command-to-string (command)
2154 "Execute shell command COMMAND and return its output as a string."
2155 (with-output-to-string
2156 (with-current-buffer
2157 standard-output
2158 (call-process shell-file-name nil t nil shell-command-switch command))))
2159
2160 (defun process-file (program &optional infile buffer display &rest args)
2161 "Process files synchronously in a separate process.
2162 Similar to `call-process', but may invoke a file handler based on
2163 `default-directory'. The current working directory of the
2164 subprocess is `default-directory'.
2165
2166 File names in INFILE and BUFFER are handled normally, but file
2167 names in ARGS should be relative to `default-directory', as they
2168 are passed to the process verbatim. \(This is a difference to
2169 `call-process' which does not support file handlers for INFILE
2170 and BUFFER.\)
2171
2172 Some file handlers might not support all variants, for example
2173 they might behave as if DISPLAY was nil, regardless of the actual
2174 value passed."
2175 (let ((fh (find-file-name-handler default-directory 'process-file))
2176 lc stderr-file)
2177 (unwind-protect
2178 (if fh (apply fh 'process-file program infile buffer display args)
2179 (when infile (setq lc (file-local-copy infile)))
2180 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
2181 (make-temp-file "emacs")))
2182 (prog1
2183 (apply 'call-process program
2184 (or lc infile)
2185 (if stderr-file (list (car buffer) stderr-file) buffer)
2186 display args)
2187 (when stderr-file (copy-file stderr-file (cadr buffer)))))
2188 (when stderr-file (delete-file stderr-file))
2189 (when lc (delete-file lc)))))
2190
2191
2192 \f
2193 (defvar universal-argument-map
2194 (let ((map (make-sparse-keymap)))
2195 (define-key map [t] 'universal-argument-other-key)
2196 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2197 (define-key map [switch-frame] nil)
2198 (define-key map [?\C-u] 'universal-argument-more)
2199 (define-key map [?-] 'universal-argument-minus)
2200 (define-key map [?0] 'digit-argument)
2201 (define-key map [?1] 'digit-argument)
2202 (define-key map [?2] 'digit-argument)
2203 (define-key map [?3] 'digit-argument)
2204 (define-key map [?4] 'digit-argument)
2205 (define-key map [?5] 'digit-argument)
2206 (define-key map [?6] 'digit-argument)
2207 (define-key map [?7] 'digit-argument)
2208 (define-key map [?8] 'digit-argument)
2209 (define-key map [?9] 'digit-argument)
2210 (define-key map [kp-0] 'digit-argument)
2211 (define-key map [kp-1] 'digit-argument)
2212 (define-key map [kp-2] 'digit-argument)
2213 (define-key map [kp-3] 'digit-argument)
2214 (define-key map [kp-4] 'digit-argument)
2215 (define-key map [kp-5] 'digit-argument)
2216 (define-key map [kp-6] 'digit-argument)
2217 (define-key map [kp-7] 'digit-argument)
2218 (define-key map [kp-8] 'digit-argument)
2219 (define-key map [kp-9] 'digit-argument)
2220 (define-key map [kp-subtract] 'universal-argument-minus)
2221 map)
2222 "Keymap used while processing \\[universal-argument].")
2223
2224 (defvar universal-argument-num-events nil
2225 "Number of argument-specifying events read by `universal-argument'.
2226 `universal-argument-other-key' uses this to discard those events
2227 from (this-command-keys), and reread only the final command.")
2228
2229 (defvar overriding-map-is-bound nil
2230 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2231
2232 (defvar saved-overriding-map nil
2233 "The saved value of `overriding-terminal-local-map'.
2234 That variable gets restored to this value on exiting \"universal
2235 argument mode\".")
2236
2237 (defun ensure-overriding-map-is-bound ()
2238 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2239 (unless overriding-map-is-bound
2240 (setq saved-overriding-map overriding-terminal-local-map)
2241 (setq overriding-terminal-local-map universal-argument-map)
2242 (setq overriding-map-is-bound t)))
2243
2244 (defun restore-overriding-map ()
2245 "Restore `overriding-terminal-local-map' to its saved value."
2246 (setq overriding-terminal-local-map saved-overriding-map)
2247 (setq overriding-map-is-bound nil))
2248
2249 (defun universal-argument ()
2250 "Begin a numeric argument for the following command.
2251 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2252 \\[universal-argument] following the digits or minus sign ends the argument.
2253 \\[universal-argument] without digits or minus sign provides 4 as argument.
2254 Repeating \\[universal-argument] without digits or minus sign
2255 multiplies the argument by 4 each time.
2256 For some commands, just \\[universal-argument] by itself serves as a flag
2257 which is different in effect from any particular numeric argument.
2258 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2259 (interactive)
2260 (setq prefix-arg (list 4))
2261 (setq universal-argument-num-events (length (this-command-keys)))
2262 (ensure-overriding-map-is-bound))
2263
2264 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2265 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2266 (defun universal-argument-more (arg)
2267 (interactive "P")
2268 (if (consp arg)
2269 (setq prefix-arg (list (* 4 (car arg))))
2270 (if (eq arg '-)
2271 (setq prefix-arg (list -4))
2272 (setq prefix-arg arg)
2273 (restore-overriding-map)))
2274 (setq universal-argument-num-events (length (this-command-keys))))
2275
2276 (defun negative-argument (arg)
2277 "Begin a negative numeric argument for the next command.
2278 \\[universal-argument] following digits or minus sign ends the argument."
2279 (interactive "P")
2280 (cond ((integerp arg)
2281 (setq prefix-arg (- arg)))
2282 ((eq arg '-)
2283 (setq prefix-arg nil))
2284 (t
2285 (setq prefix-arg '-)))
2286 (setq universal-argument-num-events (length (this-command-keys)))
2287 (ensure-overriding-map-is-bound))
2288
2289 (defun digit-argument (arg)
2290 "Part of the numeric argument for the next command.
2291 \\[universal-argument] following digits or minus sign ends the argument."
2292 (interactive "P")
2293 (let* ((char (if (integerp last-command-char)
2294 last-command-char
2295 (get last-command-char 'ascii-character)))
2296 (digit (- (logand char ?\177) ?0)))
2297 (cond ((integerp arg)
2298 (setq prefix-arg (+ (* arg 10)
2299 (if (< arg 0) (- digit) digit))))
2300 ((eq arg '-)
2301 ;; Treat -0 as just -, so that -01 will work.
2302 (setq prefix-arg (if (zerop digit) '- (- digit))))
2303 (t
2304 (setq prefix-arg digit))))
2305 (setq universal-argument-num-events (length (this-command-keys)))
2306 (ensure-overriding-map-is-bound))
2307
2308 ;; For backward compatibility, minus with no modifiers is an ordinary
2309 ;; command if digits have already been entered.
2310 (defun universal-argument-minus (arg)
2311 (interactive "P")
2312 (if (integerp arg)
2313 (universal-argument-other-key arg)
2314 (negative-argument arg)))
2315
2316 ;; Anything else terminates the argument and is left in the queue to be
2317 ;; executed as a command.
2318 (defun universal-argument-other-key (arg)
2319 (interactive "P")
2320 (setq prefix-arg arg)
2321 (let* ((key (this-command-keys))
2322 (keylist (listify-key-sequence key)))
2323 (setq unread-command-events
2324 (append (nthcdr universal-argument-num-events keylist)
2325 unread-command-events)))
2326 (reset-this-command-lengths)
2327 (restore-overriding-map))
2328 \f
2329 (defvar buffer-substring-filters nil
2330 "List of filter functions for `filter-buffer-substring'.
2331 Each function must accept a single argument, a string, and return
2332 a string. The buffer substring is passed to the first function
2333 in the list, and the return value of each function is passed to
2334 the next. The return value of the last function is used as the
2335 return value of `filter-buffer-substring'.
2336
2337 If this variable is nil, no filtering is performed.")
2338
2339 (defun filter-buffer-substring (beg end &optional delete noprops)
2340 "Return the buffer substring between BEG and END, after filtering.
2341 The buffer substring is passed through each of the filter
2342 functions in `buffer-substring-filters', and the value from the
2343 last filter function is returned. If `buffer-substring-filters'
2344 is nil, the buffer substring is returned unaltered.
2345
2346 If DELETE is non-nil, the text between BEG and END is deleted
2347 from the buffer.
2348
2349 If NOPROPS is non-nil, final string returned does not include
2350 text properties, while the string passed to the filters still
2351 includes text properties from the buffer text.
2352
2353 Point is temporarily set to BEG before calling
2354 `buffer-substring-filters', in case the functions need to know
2355 where the text came from.
2356
2357 This function should be used instead of `buffer-substring',
2358 `buffer-substring-no-properties', or `delete-and-extract-region'
2359 when you want to allow filtering to take place. For example,
2360 major or minor modes can use `buffer-substring-filters' to
2361 extract characters that are special to a buffer, and should not
2362 be copied into other buffers."
2363 (cond
2364 ((or delete buffer-substring-filters)
2365 (save-excursion
2366 (goto-char beg)
2367 (let ((string (if delete (delete-and-extract-region beg end)
2368 (buffer-substring beg end))))
2369 (dolist (filter buffer-substring-filters)
2370 (setq string (funcall filter string)))
2371 (if noprops
2372 (set-text-properties 0 (length string) nil string))
2373 string)))
2374 (noprops
2375 (buffer-substring-no-properties beg end))
2376 (t
2377 (buffer-substring beg end))))
2378
2379
2380 ;;;; Window system cut and paste hooks.
2381
2382 (defvar interprogram-cut-function nil
2383 "Function to call to make a killed region available to other programs.
2384
2385 Most window systems provide some sort of facility for cutting and
2386 pasting text between the windows of different programs.
2387 This variable holds a function that Emacs calls whenever text
2388 is put in the kill ring, to make the new kill available to other
2389 programs.
2390
2391 The function takes one or two arguments.
2392 The first argument, TEXT, is a string containing
2393 the text which should be made available.
2394 The second, optional, argument PUSH, has the same meaning as the
2395 similar argument to `x-set-cut-buffer', which see.")
2396
2397 (defvar interprogram-paste-function nil
2398 "Function to call to get text cut from other programs.
2399
2400 Most window systems provide some sort of facility for cutting and
2401 pasting text between the windows of different programs.
2402 This variable holds a function that Emacs calls to obtain
2403 text that other programs have provided for pasting.
2404
2405 The function should be called with no arguments. If the function
2406 returns nil, then no other program has provided such text, and the top
2407 of the Emacs kill ring should be used. If the function returns a
2408 string, then the caller of the function \(usually `current-kill')
2409 should put this string in the kill ring as the latest kill.
2410
2411 Note that the function should return a string only if a program other
2412 than Emacs has provided a string for pasting; if Emacs provided the
2413 most recent string, the function should return nil. If it is
2414 difficult to tell whether Emacs or some other program provided the
2415 current string, it is probably good enough to return nil if the string
2416 is equal (according to `string=') to the last text Emacs provided.")
2417 \f
2418
2419
2420 ;;;; The kill ring data structure.
2421
2422 (defvar kill-ring nil
2423 "List of killed text sequences.
2424 Since the kill ring is supposed to interact nicely with cut-and-paste
2425 facilities offered by window systems, use of this variable should
2426 interact nicely with `interprogram-cut-function' and
2427 `interprogram-paste-function'. The functions `kill-new',
2428 `kill-append', and `current-kill' are supposed to implement this
2429 interaction; you may want to use them instead of manipulating the kill
2430 ring directly.")
2431
2432 (defcustom kill-ring-max 60
2433 "*Maximum length of kill ring before oldest elements are thrown away."
2434 :type 'integer
2435 :group 'killing)
2436
2437 (defvar kill-ring-yank-pointer nil
2438 "The tail of the kill ring whose car is the last thing yanked.")
2439
2440 (defun kill-new (string &optional replace yank-handler)
2441 "Make STRING the latest kill in the kill ring.
2442 Set `kill-ring-yank-pointer' to point to it.
2443 If `interprogram-cut-function' is non-nil, apply it to STRING.
2444 Optional second argument REPLACE non-nil means that STRING will replace
2445 the front of the kill ring, rather than being added to the list.
2446
2447 Optional third arguments YANK-HANDLER controls how the STRING is later
2448 inserted into a buffer; see `insert-for-yank' for details.
2449 When a yank handler is specified, STRING must be non-empty (the yank
2450 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2451
2452 When the yank handler has a non-nil PARAM element, the original STRING
2453 argument is not used by `insert-for-yank'. However, since Lisp code
2454 may access and use elements from the kill ring directly, the STRING
2455 argument should still be a \"useful\" string for such uses."
2456 (if (> (length string) 0)
2457 (if yank-handler
2458 (put-text-property 0 (length string)
2459 'yank-handler yank-handler string))
2460 (if yank-handler
2461 (signal 'args-out-of-range
2462 (list string "yank-handler specified for empty string"))))
2463 (if (fboundp 'menu-bar-update-yank-menu)
2464 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
2465 (if (and replace kill-ring)
2466 (setcar kill-ring string)
2467 (push string kill-ring)
2468 (if (> (length kill-ring) kill-ring-max)
2469 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
2470 (setq kill-ring-yank-pointer kill-ring)
2471 (if interprogram-cut-function
2472 (funcall interprogram-cut-function string (not replace))))
2473
2474 (defun kill-append (string before-p &optional yank-handler)
2475 "Append STRING to the end of the latest kill in the kill ring.
2476 If BEFORE-P is non-nil, prepend STRING to the kill.
2477 Optional third argument YANK-HANDLER, if non-nil, specifies the
2478 yank-handler text property to be set on the combined kill ring
2479 string. If the specified yank-handler arg differs from the
2480 yank-handler property of the latest kill string, this function
2481 adds the combined string to the kill ring as a new element,
2482 instead of replacing the last kill with it.
2483 If `interprogram-cut-function' is set, pass the resulting kill to it."
2484 (let* ((cur (car kill-ring)))
2485 (kill-new (if before-p (concat string cur) (concat cur string))
2486 (or (= (length cur) 0)
2487 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2488 yank-handler)))
2489
2490 (defun current-kill (n &optional do-not-move)
2491 "Rotate the yanking point by N places, and then return that kill.
2492 If N is zero, `interprogram-paste-function' is set, and calling it
2493 returns a string, then that string is added to the front of the
2494 kill ring and returned as the latest kill.
2495 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
2496 yanking point; just return the Nth kill forward."
2497 (let ((interprogram-paste (and (= n 0)
2498 interprogram-paste-function
2499 (funcall interprogram-paste-function))))
2500 (if interprogram-paste
2501 (progn
2502 ;; Disable the interprogram cut function when we add the new
2503 ;; text to the kill ring, so Emacs doesn't try to own the
2504 ;; selection, with identical text.
2505 (let ((interprogram-cut-function nil))
2506 (kill-new interprogram-paste))
2507 interprogram-paste)
2508 (or kill-ring (error "Kill ring is empty"))
2509 (let ((ARGth-kill-element
2510 (nthcdr (mod (- n (length kill-ring-yank-pointer))
2511 (length kill-ring))
2512 kill-ring)))
2513 (or do-not-move
2514 (setq kill-ring-yank-pointer ARGth-kill-element))
2515 (car ARGth-kill-element)))))
2516
2517
2518
2519 ;;;; Commands for manipulating the kill ring.
2520
2521 (defcustom kill-read-only-ok nil
2522 "*Non-nil means don't signal an error for killing read-only text."
2523 :type 'boolean
2524 :group 'killing)
2525
2526 (put 'text-read-only 'error-conditions
2527 '(text-read-only buffer-read-only error))
2528 (put 'text-read-only 'error-message "Text is read-only")
2529
2530 (defun kill-region (beg end &optional yank-handler)
2531 "Kill (\"cut\") text between point and mark.
2532 This deletes the text from the buffer and saves it in the kill ring.
2533 The command \\[yank] can retrieve it from there.
2534 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
2535
2536 If you want to append the killed region to the last killed text,
2537 use \\[append-next-kill] before \\[kill-region].
2538
2539 If the buffer is read-only, Emacs will beep and refrain from deleting
2540 the text, but put the text in the kill ring anyway. This means that
2541 you can use the killing commands to copy text from a read-only buffer.
2542
2543 This is the primitive for programs to kill text (as opposed to deleting it).
2544 Supply two arguments, character positions indicating the stretch of text
2545 to be killed.
2546 Any command that calls this function is a \"kill command\".
2547 If the previous command was also a kill command,
2548 the text killed this time appends to the text killed last time
2549 to make one entry in the kill ring.
2550
2551 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
2552 specifies the yank-handler text property to be set on the killed
2553 text. See `insert-for-yank'."
2554 ;; Pass point first, then mark, because the order matters
2555 ;; when calling kill-append.
2556 (interactive (list (point) (mark)))
2557 (condition-case nil
2558 (let ((string (filter-buffer-substring beg end t)))
2559 (when string ;STRING is nil if BEG = END
2560 ;; Add that string to the kill ring, one way or another.
2561 (if (eq last-command 'kill-region)
2562 (kill-append string (< end beg) yank-handler)
2563 (kill-new string nil yank-handler)))
2564 (when (or string (eq last-command 'kill-region))
2565 (setq this-command 'kill-region))
2566 nil)
2567 ((buffer-read-only text-read-only)
2568 ;; The code above failed because the buffer, or some of the characters
2569 ;; in the region, are read-only.
2570 ;; We should beep, in case the user just isn't aware of this.
2571 ;; However, there's no harm in putting
2572 ;; the region's text in the kill ring, anyway.
2573 (copy-region-as-kill beg end)
2574 ;; Set this-command now, so it will be set even if we get an error.
2575 (setq this-command 'kill-region)
2576 ;; This should barf, if appropriate, and give us the correct error.
2577 (if kill-read-only-ok
2578 (progn (message "Read only text copied to kill ring") nil)
2579 ;; Signal an error if the buffer is read-only.
2580 (barf-if-buffer-read-only)
2581 ;; If the buffer isn't read-only, the text is.
2582 (signal 'text-read-only (list (current-buffer)))))))
2583
2584 ;; copy-region-as-kill no longer sets this-command, because it's confusing
2585 ;; to get two copies of the text when the user accidentally types M-w and
2586 ;; then corrects it with the intended C-w.
2587 (defun copy-region-as-kill (beg end)
2588 "Save the region as if killed, but don't kill it.
2589 In Transient Mark mode, deactivate the mark.
2590 If `interprogram-cut-function' is non-nil, also save the text for a window
2591 system cut and paste."
2592 (interactive "r")
2593 (if (eq last-command 'kill-region)
2594 (kill-append (filter-buffer-substring beg end) (< end beg))
2595 (kill-new (filter-buffer-substring beg end)))
2596 (if transient-mark-mode
2597 (setq deactivate-mark t))
2598 nil)
2599
2600 (defun kill-ring-save (beg end)
2601 "Save the region as if killed, but don't kill it.
2602 In Transient Mark mode, deactivate the mark.
2603 If `interprogram-cut-function' is non-nil, also save the text for a window
2604 system cut and paste.
2605
2606 If you want to append the killed line to the last killed text,
2607 use \\[append-next-kill] before \\[kill-ring-save].
2608
2609 This command is similar to `copy-region-as-kill', except that it gives
2610 visual feedback indicating the extent of the region being copied."
2611 (interactive "r")
2612 (copy-region-as-kill beg end)
2613 ;; This use of interactive-p is correct
2614 ;; because the code it controls just gives the user visual feedback.
2615 (if (interactive-p)
2616 (let ((other-end (if (= (point) beg) end beg))
2617 (opoint (point))
2618 ;; Inhibit quitting so we can make a quit here
2619 ;; look like a C-g typed as a command.
2620 (inhibit-quit t))
2621 (if (pos-visible-in-window-p other-end (selected-window))
2622 (unless (and transient-mark-mode
2623 (face-background 'region))
2624 ;; Swap point and mark.
2625 (set-marker (mark-marker) (point) (current-buffer))
2626 (goto-char other-end)
2627 (sit-for blink-matching-delay)
2628 ;; Swap back.
2629 (set-marker (mark-marker) other-end (current-buffer))
2630 (goto-char opoint)
2631 ;; If user quit, deactivate the mark
2632 ;; as C-g would as a command.
2633 (and quit-flag mark-active
2634 (deactivate-mark)))
2635 (let* ((killed-text (current-kill 0))
2636 (message-len (min (length killed-text) 40)))
2637 (if (= (point) beg)
2638 ;; Don't say "killed"; that is misleading.
2639 (message "Saved text until \"%s\""
2640 (substring killed-text (- message-len)))
2641 (message "Saved text from \"%s\""
2642 (substring killed-text 0 message-len))))))))
2643
2644 (defun append-next-kill (&optional interactive)
2645 "Cause following command, if it kills, to append to previous kill.
2646 The argument is used for internal purposes; do not supply one."
2647 (interactive "p")
2648 ;; We don't use (interactive-p), since that breaks kbd macros.
2649 (if interactive
2650 (progn
2651 (setq this-command 'kill-region)
2652 (message "If the next command is a kill, it will append"))
2653 (setq last-command 'kill-region)))
2654 \f
2655 ;; Yanking.
2656
2657 ;; This is actually used in subr.el but defcustom does not work there.
2658 (defcustom yank-excluded-properties
2659 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2660 yank-handler follow-link)
2661 "*Text properties to discard when yanking.
2662 The value should be a list of text properties to discard or t,
2663 which means to discard all text properties."
2664 :type '(choice (const :tag "All" t) (repeat symbol))
2665 :group 'killing
2666 :version "22.1")
2667
2668 (defvar yank-window-start nil)
2669 (defvar yank-undo-function nil
2670 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2671 Function is called with two parameters, START and END corresponding to
2672 the value of the mark and point; it is guaranteed that START <= END.
2673 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
2674
2675 (defun yank-pop (&optional arg)
2676 "Replace just-yanked stretch of killed text with a different stretch.
2677 This command is allowed only immediately after a `yank' or a `yank-pop'.
2678 At such a time, the region contains a stretch of reinserted
2679 previously-killed text. `yank-pop' deletes that text and inserts in its
2680 place a different stretch of killed text.
2681
2682 With no argument, the previous kill is inserted.
2683 With argument N, insert the Nth previous kill.
2684 If N is negative, this is a more recent kill.
2685
2686 The sequence of kills wraps around, so that after the oldest one
2687 comes the newest one.
2688
2689 When this command inserts killed text into the buffer, it honors
2690 `yank-excluded-properties' and `yank-handler' as described in the
2691 doc string for `insert-for-yank-1', which see."
2692 (interactive "*p")
2693 (if (not (eq last-command 'yank))
2694 (error "Previous command was not a yank"))
2695 (setq this-command 'yank)
2696 (unless arg (setq arg 1))
2697 (let ((inhibit-read-only t)
2698 (before (< (point) (mark t))))
2699 (if before
2700 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2701 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
2702 (setq yank-undo-function nil)
2703 (set-marker (mark-marker) (point) (current-buffer))
2704 (insert-for-yank (current-kill arg))
2705 ;; Set the window start back where it was in the yank command,
2706 ;; if possible.
2707 (set-window-start (selected-window) yank-window-start t)
2708 (if before
2709 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2710 ;; It is cleaner to avoid activation, even though the command
2711 ;; loop would deactivate the mark because we inserted text.
2712 (goto-char (prog1 (mark t)
2713 (set-marker (mark-marker) (point) (current-buffer))))))
2714 nil)
2715
2716 (defun yank (&optional arg)
2717 "Reinsert (\"paste\") the last stretch of killed text.
2718 More precisely, reinsert the stretch of killed text most recently
2719 killed OR yanked. Put point at end, and set mark at beginning.
2720 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
2721 With argument N, reinsert the Nth most recently killed stretch of killed
2722 text.
2723
2724 When this command inserts killed text into the buffer, it honors
2725 `yank-excluded-properties' and `yank-handler' as described in the
2726 doc string for `insert-for-yank-1', which see.
2727
2728 See also the command \\[yank-pop]."
2729 (interactive "*P")
2730 (setq yank-window-start (window-start))
2731 ;; If we don't get all the way thru, make last-command indicate that
2732 ;; for the following command.
2733 (setq this-command t)
2734 (push-mark (point))
2735 (insert-for-yank (current-kill (cond
2736 ((listp arg) 0)
2737 ((eq arg '-) -2)
2738 (t (1- arg)))))
2739 (if (consp arg)
2740 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2741 ;; It is cleaner to avoid activation, even though the command
2742 ;; loop would deactivate the mark because we inserted text.
2743 (goto-char (prog1 (mark t)
2744 (set-marker (mark-marker) (point) (current-buffer)))))
2745 ;; If we do get all the way thru, make this-command indicate that.
2746 (if (eq this-command t)
2747 (setq this-command 'yank))
2748 nil)
2749
2750 (defun rotate-yank-pointer (arg)
2751 "Rotate the yanking point in the kill ring.
2752 With argument, rotate that many kills forward (or backward, if negative)."
2753 (interactive "p")
2754 (current-kill arg))
2755 \f
2756 ;; Some kill commands.
2757
2758 ;; Internal subroutine of delete-char
2759 (defun kill-forward-chars (arg)
2760 (if (listp arg) (setq arg (car arg)))
2761 (if (eq arg '-) (setq arg -1))
2762 (kill-region (point) (forward-point arg)))
2763
2764 ;; Internal subroutine of backward-delete-char
2765 (defun kill-backward-chars (arg)
2766 (if (listp arg) (setq arg (car arg)))
2767 (if (eq arg '-) (setq arg -1))
2768 (kill-region (point) (forward-point (- arg))))
2769
2770 (defcustom backward-delete-char-untabify-method 'untabify
2771 "*The method for untabifying when deleting backward.
2772 Can be `untabify' -- turn a tab to many spaces, then delete one space;
2773 `hungry' -- delete all whitespace, both tabs and spaces;
2774 `all' -- delete all whitespace, including tabs, spaces and newlines;
2775 nil -- just delete one character."
2776 :type '(choice (const untabify) (const hungry) (const all) (const nil))
2777 :version "20.3"
2778 :group 'killing)
2779
2780 (defun backward-delete-char-untabify (arg &optional killp)
2781 "Delete characters backward, changing tabs into spaces.
2782 The exact behavior depends on `backward-delete-char-untabify-method'.
2783 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
2784 Interactively, ARG is the prefix arg (default 1)
2785 and KILLP is t if a prefix arg was specified."
2786 (interactive "*p\nP")
2787 (when (eq backward-delete-char-untabify-method 'untabify)
2788 (let ((count arg))
2789 (save-excursion
2790 (while (and (> count 0) (not (bobp)))
2791 (if (= (preceding-char) ?\t)
2792 (let ((col (current-column)))
2793 (forward-char -1)
2794 (setq col (- col (current-column)))
2795 (insert-char ?\s col)
2796 (delete-char 1)))
2797 (forward-char -1)
2798 (setq count (1- count))))))
2799 (delete-backward-char
2800 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
2801 ((eq backward-delete-char-untabify-method 'all)
2802 " \t\n\r"))))
2803 (if skip
2804 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
2805 (point)))))
2806 (+ arg (if (zerop wh) 0 (1- wh))))
2807 arg))
2808 killp))
2809
2810 (defun zap-to-char (arg char)
2811 "Kill up to and including ARG'th occurrence of CHAR.
2812 Case is ignored if `case-fold-search' is non-nil in the current buffer.
2813 Goes backward if ARG is negative; error if CHAR not found."
2814 (interactive "p\ncZap to char: ")
2815 (if (char-table-p translation-table-for-input)
2816 (setq char (or (aref translation-table-for-input char) char)))
2817 (kill-region (point) (progn
2818 (search-forward (char-to-string char) nil nil arg)
2819 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
2820 (point))))
2821
2822 ;; kill-line and its subroutines.
2823
2824 (defcustom kill-whole-line nil
2825 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
2826 :type 'boolean
2827 :group 'killing)
2828
2829 (defun kill-line (&optional arg)
2830 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
2831 With prefix argument, kill that many lines from point.
2832 Negative arguments kill lines backward.
2833 With zero argument, kills the text before point on the current line.
2834
2835 When calling from a program, nil means \"no arg\",
2836 a number counts as a prefix arg.
2837
2838 To kill a whole line, when point is not at the beginning, type \
2839 \\[beginning-of-line] \\[kill-line] \\[kill-line].
2840
2841 If `kill-whole-line' is non-nil, then this command kills the whole line
2842 including its terminating newline, when used at the beginning of a line
2843 with no argument. As a consequence, you can always kill a whole line
2844 by typing \\[beginning-of-line] \\[kill-line].
2845
2846 If you want to append the killed line to the last killed text,
2847 use \\[append-next-kill] before \\[kill-line].
2848
2849 If the buffer is read-only, Emacs will beep and refrain from deleting
2850 the line, but put the line in the kill ring anyway. This means that
2851 you can use this command to copy text from a read-only buffer.
2852 \(If the variable `kill-read-only-ok' is non-nil, then this won't
2853 even beep.)"
2854 (interactive "P")
2855 (kill-region (point)
2856 ;; It is better to move point to the other end of the kill
2857 ;; before killing. That way, in a read-only buffer, point
2858 ;; moves across the text that is copied to the kill ring.
2859 ;; The choice has no effect on undo now that undo records
2860 ;; the value of point from before the command was run.
2861 (progn
2862 (if arg
2863 (forward-visible-line (prefix-numeric-value arg))
2864 (if (eobp)
2865 (signal 'end-of-buffer nil))
2866 (let ((end
2867 (save-excursion
2868 (end-of-visible-line) (point))))
2869 (if (or (save-excursion
2870 ;; If trailing whitespace is visible,
2871 ;; don't treat it as nothing.
2872 (unless show-trailing-whitespace
2873 (skip-chars-forward " \t" end))
2874 (= (point) end))
2875 (and kill-whole-line (bolp)))
2876 (forward-visible-line 1)
2877 (goto-char end))))
2878 (point))))
2879
2880 (defun kill-whole-line (&optional arg)
2881 "Kill current line.
2882 With prefix arg, kill that many lines starting from the current line.
2883 If arg is negative, kill backward. Also kill the preceding newline.
2884 \(This is meant to make \\[repeat] work well with negative arguments.\)
2885 If arg is zero, kill current line but exclude the trailing newline."
2886 (interactive "p")
2887 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
2888 (signal 'end-of-buffer nil))
2889 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
2890 (signal 'beginning-of-buffer nil))
2891 (unless (eq last-command 'kill-region)
2892 (kill-new "")
2893 (setq last-command 'kill-region))
2894 (cond ((zerop arg)
2895 ;; We need to kill in two steps, because the previous command
2896 ;; could have been a kill command, in which case the text
2897 ;; before point needs to be prepended to the current kill
2898 ;; ring entry and the text after point appended. Also, we
2899 ;; need to use save-excursion to avoid copying the same text
2900 ;; twice to the kill ring in read-only buffers.
2901 (save-excursion
2902 (kill-region (point) (progn (forward-visible-line 0) (point))))
2903 (kill-region (point) (progn (end-of-visible-line) (point))))
2904 ((< arg 0)
2905 (save-excursion
2906 (kill-region (point) (progn (end-of-visible-line) (point))))
2907 (kill-region (point)
2908 (progn (forward-visible-line (1+ arg))
2909 (unless (bobp) (backward-char))
2910 (point))))
2911 (t
2912 (save-excursion
2913 (kill-region (point) (progn (forward-visible-line 0) (point))))
2914 (kill-region (point)
2915 (progn (forward-visible-line arg) (point))))))
2916
2917 (defun forward-visible-line (arg)
2918 "Move forward by ARG lines, ignoring currently invisible newlines only.
2919 If ARG is negative, move backward -ARG lines.
2920 If ARG is zero, move to the beginning of the current line."
2921 (condition-case nil
2922 (if (> arg 0)
2923 (progn
2924 (while (> arg 0)
2925 (or (zerop (forward-line 1))
2926 (signal 'end-of-buffer nil))
2927 ;; If the newline we just skipped is invisible,
2928 ;; don't count it.
2929 (let ((prop
2930 (get-char-property (1- (point)) 'invisible)))
2931 (if (if (eq buffer-invisibility-spec t)
2932 prop
2933 (or (memq prop buffer-invisibility-spec)
2934 (assq prop buffer-invisibility-spec)))
2935 (setq arg (1+ arg))))
2936 (setq arg (1- arg)))
2937 ;; If invisible text follows, and it is a number of complete lines,
2938 ;; skip it.
2939 (let ((opoint (point)))
2940 (while (and (not (eobp))
2941 (let ((prop
2942 (get-char-property (point) 'invisible)))
2943 (if (eq buffer-invisibility-spec t)
2944 prop
2945 (or (memq prop buffer-invisibility-spec)
2946 (assq prop buffer-invisibility-spec)))))
2947 (goto-char
2948 (if (get-text-property (point) 'invisible)
2949 (or (next-single-property-change (point) 'invisible)
2950 (point-max))
2951 (next-overlay-change (point)))))
2952 (unless (bolp)
2953 (goto-char opoint))))
2954 (let ((first t))
2955 (while (or first (<= arg 0))
2956 (if first
2957 (beginning-of-line)
2958 (or (zerop (forward-line -1))
2959 (signal 'beginning-of-buffer nil)))
2960 ;; If the newline we just moved to is invisible,
2961 ;; don't count it.
2962 (unless (bobp)
2963 (let ((prop
2964 (get-char-property (1- (point)) 'invisible)))
2965 (unless (if (eq buffer-invisibility-spec t)
2966 prop
2967 (or (memq prop buffer-invisibility-spec)
2968 (assq prop buffer-invisibility-spec)))
2969 (setq arg (1+ arg)))))
2970 (setq first nil))
2971 ;; If invisible text follows, and it is a number of complete lines,
2972 ;; skip it.
2973 (let ((opoint (point)))
2974 (while (and (not (bobp))
2975 (let ((prop
2976 (get-char-property (1- (point)) 'invisible)))
2977 (if (eq buffer-invisibility-spec t)
2978 prop
2979 (or (memq prop buffer-invisibility-spec)
2980 (assq prop buffer-invisibility-spec)))))
2981 (goto-char
2982 (if (get-text-property (1- (point)) 'invisible)
2983 (or (previous-single-property-change (point) 'invisible)
2984 (point-min))
2985 (previous-overlay-change (point)))))
2986 (unless (bolp)
2987 (goto-char opoint)))))
2988 ((beginning-of-buffer end-of-buffer)
2989 nil)))
2990
2991 (defun end-of-visible-line ()
2992 "Move to end of current visible line."
2993 (end-of-line)
2994 ;; If the following character is currently invisible,
2995 ;; skip all characters with that same `invisible' property value,
2996 ;; then find the next newline.
2997 (while (and (not (eobp))
2998 (save-excursion
2999 (skip-chars-forward "^\n")
3000 (let ((prop
3001 (get-char-property (point) 'invisible)))
3002 (if (eq buffer-invisibility-spec t)
3003 prop
3004 (or (memq prop buffer-invisibility-spec)
3005 (assq prop buffer-invisibility-spec))))))
3006 (skip-chars-forward "^\n")
3007 (if (get-text-property (point) 'invisible)
3008 (goto-char (next-single-property-change (point) 'invisible))
3009 (goto-char (next-overlay-change (point))))
3010 (end-of-line)))
3011 \f
3012 (defun insert-buffer (buffer)
3013 "Insert after point the contents of BUFFER.
3014 Puts mark after the inserted text.
3015 BUFFER may be a buffer or a buffer name.
3016
3017 This function is meant for the user to run interactively.
3018 Don't call it from programs: use `insert-buffer-substring' instead!"
3019 (interactive
3020 (list
3021 (progn
3022 (barf-if-buffer-read-only)
3023 (read-buffer "Insert buffer: "
3024 (if (eq (selected-window) (next-window (selected-window)))
3025 (other-buffer (current-buffer))
3026 (window-buffer (next-window (selected-window))))
3027 t))))
3028 (push-mark
3029 (save-excursion
3030 (insert-buffer-substring (get-buffer buffer))
3031 (point)))
3032 nil)
3033
3034 (defun append-to-buffer (buffer start end)
3035 "Append to specified buffer the text of the region.
3036 It is inserted into that buffer before its point.
3037
3038 When calling from a program, give three arguments:
3039 BUFFER (or buffer name), START and END.
3040 START and END specify the portion of the current buffer to be copied."
3041 (interactive
3042 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
3043 (region-beginning) (region-end)))
3044 (let ((oldbuf (current-buffer)))
3045 (save-excursion
3046 (let* ((append-to (get-buffer-create buffer))
3047 (windows (get-buffer-window-list append-to t t))
3048 point)
3049 (set-buffer append-to)
3050 (setq point (point))
3051 (barf-if-buffer-read-only)
3052 (insert-buffer-substring oldbuf start end)
3053 (dolist (window windows)
3054 (when (= (window-point window) point)
3055 (set-window-point window (point))))))))
3056
3057 (defun prepend-to-buffer (buffer start end)
3058 "Prepend to specified buffer the text of the region.
3059 It is inserted into that buffer after its point.
3060
3061 When calling from a program, give three arguments:
3062 BUFFER (or buffer name), START and END.
3063 START and END specify the portion of the current buffer to be copied."
3064 (interactive "BPrepend to buffer: \nr")
3065 (let ((oldbuf (current-buffer)))
3066 (save-excursion
3067 (set-buffer (get-buffer-create buffer))
3068 (barf-if-buffer-read-only)
3069 (save-excursion
3070 (insert-buffer-substring oldbuf start end)))))
3071
3072 (defun copy-to-buffer (buffer start end)
3073 "Copy to specified buffer the text of the region.
3074 It is inserted into that buffer, replacing existing text there.
3075
3076 When calling from a program, give three arguments:
3077 BUFFER (or buffer name), START and END.
3078 START and END specify the portion of the current buffer to be copied."
3079 (interactive "BCopy to buffer: \nr")
3080 (let ((oldbuf (current-buffer)))
3081 (with-current-buffer (get-buffer-create buffer)
3082 (barf-if-buffer-read-only)
3083 (erase-buffer)
3084 (save-excursion
3085 (insert-buffer-substring oldbuf start end)))))
3086 \f
3087 (put 'mark-inactive 'error-conditions '(mark-inactive error))
3088 (put 'mark-inactive 'error-message "The mark is not active now")
3089
3090 (defvar activate-mark-hook nil
3091 "Hook run when the mark becomes active.
3092 It is also run at the end of a command, if the mark is active and
3093 it is possible that the region may have changed")
3094
3095 (defvar deactivate-mark-hook nil
3096 "Hook run when the mark becomes inactive.")
3097
3098 (defun mark (&optional force)
3099 "Return this buffer's mark value as integer, or nil if never set.
3100
3101 In Transient Mark mode, this function signals an error if
3102 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3103 or the argument FORCE is non-nil, it disregards whether the mark
3104 is active, and returns an integer or nil in the usual way.
3105
3106 If you are using this in an editing command, you are most likely making
3107 a mistake; see the documentation of `set-mark'."
3108 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
3109 (marker-position (mark-marker))
3110 (signal 'mark-inactive nil)))
3111
3112 ;; Many places set mark-active directly, and several of them failed to also
3113 ;; run deactivate-mark-hook. This shorthand should simplify.
3114 (defsubst deactivate-mark ()
3115 "Deactivate the mark by setting `mark-active' to nil.
3116 \(That makes a difference only in Transient Mark mode.)
3117 Also runs the hook `deactivate-mark-hook'."
3118 (cond
3119 ((eq transient-mark-mode 'lambda)
3120 (setq transient-mark-mode nil))
3121 (transient-mark-mode
3122 (setq mark-active nil)
3123 (run-hooks 'deactivate-mark-hook))))
3124
3125 (defun set-mark (pos)
3126 "Set this buffer's mark to POS. Don't use this function!
3127 That is to say, don't use this function unless you want
3128 the user to see that the mark has moved, and you want the previous
3129 mark position to be lost.
3130
3131 Normally, when a new mark is set, the old one should go on the stack.
3132 This is why most applications should use `push-mark', not `set-mark'.
3133
3134 Novice Emacs Lisp programmers often try to use the mark for the wrong
3135 purposes. The mark saves a location for the user's convenience.
3136 Most editing commands should not alter the mark.
3137 To remember a location for internal use in the Lisp program,
3138 store it in a Lisp variable. Example:
3139
3140 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3141
3142 (if pos
3143 (progn
3144 (setq mark-active t)
3145 (run-hooks 'activate-mark-hook)
3146 (set-marker (mark-marker) pos (current-buffer)))
3147 ;; Normally we never clear mark-active except in Transient Mark mode.
3148 ;; But when we actually clear out the mark value too,
3149 ;; we must clear mark-active in any mode.
3150 (setq mark-active nil)
3151 (run-hooks 'deactivate-mark-hook)
3152 (set-marker (mark-marker) nil)))
3153
3154 (defvar mark-ring nil
3155 "The list of former marks of the current buffer, most recent first.")
3156 (make-variable-buffer-local 'mark-ring)
3157 (put 'mark-ring 'permanent-local t)
3158
3159 (defcustom mark-ring-max 16
3160 "*Maximum size of mark ring. Start discarding off end if gets this big."
3161 :type 'integer
3162 :group 'editing-basics)
3163
3164 (defvar global-mark-ring nil
3165 "The list of saved global marks, most recent first.")
3166
3167 (defcustom global-mark-ring-max 16
3168 "*Maximum size of global mark ring. \
3169 Start discarding off end if gets this big."
3170 :type 'integer
3171 :group 'editing-basics)
3172
3173 (defun pop-to-mark-command ()
3174 "Jump to mark, and pop a new position for mark off the ring
3175 \(does not affect global mark ring\)."
3176 (interactive)
3177 (if (null (mark t))
3178 (error "No mark set in this buffer")
3179 (goto-char (mark t))
3180 (pop-mark)))
3181
3182 (defun push-mark-command (arg &optional nomsg)
3183 "Set mark at where point is.
3184 If no prefix arg and mark is already set there, just activate it.
3185 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3186 (interactive "P")
3187 (let ((mark (marker-position (mark-marker))))
3188 (if (or arg (null mark) (/= mark (point)))
3189 (push-mark nil nomsg t)
3190 (setq mark-active t)
3191 (run-hooks 'activate-mark-hook)
3192 (unless nomsg
3193 (message "Mark activated")))))
3194
3195 (defcustom set-mark-command-repeat-pop nil
3196 "*Non-nil means that repeating \\[set-mark-command] after popping will pop.
3197 This means that if you type C-u \\[set-mark-command] \\[set-mark-command]
3198 will pop twice."
3199 :type 'boolean
3200 :group 'editing)
3201
3202 (defun set-mark-command (arg)
3203 "Set mark at where point is, or jump to mark.
3204 With no prefix argument, set mark, and push old mark position on local
3205 mark ring; also push mark on global mark ring if last mark was set in
3206 another buffer. Immediately repeating the command activates
3207 `transient-mark-mode' temporarily.
3208
3209 With argument, e.g. \\[universal-argument] \\[set-mark-command], \
3210 jump to mark, and pop a new position
3211 for mark off the local mark ring \(this does not affect the global
3212 mark ring\). Use \\[pop-global-mark] to jump to a mark off the global
3213 mark ring \(see `pop-global-mark'\).
3214
3215 If `set-mark-command-repeat-pop' is non-nil, repeating
3216 the \\[set-mark-command] command with no prefix pops the next position
3217 off the local (or global) mark ring and jumps there.
3218
3219 With a double \\[universal-argument] prefix argument, e.g. \\[universal-argument] \
3220 \\[universal-argument] \\[set-mark-command], unconditionally
3221 set mark where point is.
3222
3223 Setting the mark also sets the \"region\", which is the closest
3224 equivalent in Emacs to what some editors call the \"selection\".
3225
3226 Novice Emacs Lisp programmers often try to use the mark for the wrong
3227 purposes. See the documentation of `set-mark' for more information."
3228 (interactive "P")
3229 (if (eq transient-mark-mode 'lambda)
3230 (setq transient-mark-mode nil))
3231 (cond
3232 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3233 (push-mark-command nil))
3234 ((not (eq this-command 'set-mark-command))
3235 (if arg
3236 (pop-to-mark-command)
3237 (push-mark-command t)))
3238 ((and set-mark-command-repeat-pop
3239 (eq last-command 'pop-to-mark-command))
3240 (setq this-command 'pop-to-mark-command)
3241 (pop-to-mark-command))
3242 ((and set-mark-command-repeat-pop
3243 (eq last-command 'pop-global-mark)
3244 (not arg))
3245 (setq this-command 'pop-global-mark)
3246 (pop-global-mark))
3247 (arg
3248 (setq this-command 'pop-to-mark-command)
3249 (pop-to-mark-command))
3250 ((and (eq last-command 'set-mark-command)
3251 mark-active (null transient-mark-mode))
3252 (setq transient-mark-mode 'lambda)
3253 (message "Transient-mark-mode temporarily enabled"))
3254 (t
3255 (push-mark-command nil))))
3256
3257 (defun push-mark (&optional location nomsg activate)
3258 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3259 If the last global mark pushed was not in the current buffer,
3260 also push LOCATION on the global mark ring.
3261 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3262 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
3263
3264 Novice Emacs Lisp programmers often try to use the mark for the wrong
3265 purposes. See the documentation of `set-mark' for more information.
3266
3267 In Transient Mark mode, this does not activate the mark."
3268 (unless (null (mark t))
3269 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3270 (when (> (length mark-ring) mark-ring-max)
3271 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3272 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3273 (set-marker (mark-marker) (or location (point)) (current-buffer))
3274 ;; Now push the mark on the global mark ring.
3275 (if (and global-mark-ring
3276 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3277 ;; The last global mark pushed was in this same buffer.
3278 ;; Don't push another one.
3279 nil
3280 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3281 (when (> (length global-mark-ring) global-mark-ring-max)
3282 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3283 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3284 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3285 (message "Mark set"))
3286 (if (or activate (not transient-mark-mode))
3287 (set-mark (mark t)))
3288 nil)
3289
3290 (defun pop-mark ()
3291 "Pop off mark ring into the buffer's actual mark.
3292 Does not set point. Does nothing if mark ring is empty."
3293 (when mark-ring
3294 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3295 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3296 (move-marker (car mark-ring) nil)
3297 (if (null (mark t)) (ding))
3298 (setq mark-ring (cdr mark-ring)))
3299 (deactivate-mark))
3300
3301 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
3302 (defun exchange-point-and-mark (&optional arg)
3303 "Put the mark where point is now, and point where the mark is now.
3304 This command works even when the mark is not active,
3305 and it reactivates the mark.
3306 With prefix arg, `transient-mark-mode' is enabled temporarily."
3307 (interactive "P")
3308 (if arg
3309 (if mark-active
3310 (if (null transient-mark-mode)
3311 (setq transient-mark-mode 'lambda))
3312 (setq arg nil)))
3313 (unless arg
3314 (let ((omark (mark t)))
3315 (if (null omark)
3316 (error "No mark set in this buffer"))
3317 (set-mark (point))
3318 (goto-char omark)
3319 nil)))
3320
3321 (define-minor-mode transient-mark-mode
3322 "Toggle Transient Mark mode.
3323 With arg, turn Transient Mark mode on if arg is positive, off otherwise.
3324
3325 In Transient Mark mode, when the mark is active, the region is highlighted.
3326 Changing the buffer \"deactivates\" the mark.
3327 So do certain other operations that set the mark
3328 but whose main purpose is something else--for example,
3329 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3330
3331 You can also deactivate the mark by typing \\[keyboard-quit] or
3332 \\[keyboard-escape-quit].
3333
3334 Many commands change their behavior when Transient Mark mode is in effect
3335 and the mark is active, by acting on the region instead of their usual
3336 default part of the buffer's text. Examples of such commands include
3337 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3338 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3339 Invoke \\[apropos-documentation] and type \"transient\" or
3340 \"mark.*active\" at the prompt, to see the documentation of
3341 commands which are sensitive to the Transient Mark mode."
3342 :global t :group 'editing-basics)
3343
3344 (defvar widen-automatically t
3345 "Non-nil means it is ok for commands to call `widen' when they want to.
3346 Some commands will do this in order to go to positions outside
3347 the current accessible part of the buffer.
3348
3349 If `widen-automatically' is nil, these commands will do something else
3350 as a fallback, and won't change the buffer bounds.")
3351
3352 (defun pop-global-mark ()
3353 "Pop off global mark ring and jump to the top location."
3354 (interactive)
3355 ;; Pop entries which refer to non-existent buffers.
3356 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
3357 (setq global-mark-ring (cdr global-mark-ring)))
3358 (or global-mark-ring
3359 (error "No global mark set"))
3360 (let* ((marker (car global-mark-ring))
3361 (buffer (marker-buffer marker))
3362 (position (marker-position marker)))
3363 (setq global-mark-ring (nconc (cdr global-mark-ring)
3364 (list (car global-mark-ring))))
3365 (set-buffer buffer)
3366 (or (and (>= position (point-min))
3367 (<= position (point-max)))
3368 (if widen-automatically
3369 (widen)
3370 (error "Global mark position is outside accessible part of buffer")))
3371 (goto-char position)
3372 (switch-to-buffer buffer)))
3373 \f
3374 (defcustom next-line-add-newlines nil
3375 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
3376 :type 'boolean
3377 :version "21.1"
3378 :group 'editing-basics)
3379
3380 (defun next-line (&optional arg try-vscroll)
3381 "Move cursor vertically down ARG lines.
3382 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3383 If there is no character in the target line exactly under the current column,
3384 the cursor is positioned after the character in that line which spans this
3385 column, or at the end of the line if it is not long enough.
3386 If there is no line in the buffer after this one, behavior depends on the
3387 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
3388 to create a line, and moves the cursor to that line. Otherwise it moves the
3389 cursor to the end of the buffer.
3390
3391 The command \\[set-goal-column] can be used to create
3392 a semipermanent goal column for this command.
3393 Then instead of trying to move exactly vertically (or as close as possible),
3394 this command moves to the specified goal column (or as close as possible).
3395 The goal column is stored in the variable `goal-column', which is nil
3396 when there is no goal column.
3397
3398 If you are thinking of using this in a Lisp program, consider
3399 using `forward-line' instead. It is usually easier to use
3400 and more reliable (no dependence on goal column, etc.)."
3401 (interactive "p\np")
3402 (or arg (setq arg 1))
3403 (if (and next-line-add-newlines (= arg 1))
3404 (if (save-excursion (end-of-line) (eobp))
3405 ;; When adding a newline, don't expand an abbrev.
3406 (let ((abbrev-mode nil))
3407 (end-of-line)
3408 (insert (if use-hard-newlines hard-newline "\n")))
3409 (line-move arg nil nil try-vscroll))
3410 (if (interactive-p)
3411 (condition-case nil
3412 (line-move arg nil nil try-vscroll)
3413 ((beginning-of-buffer end-of-buffer) (ding)))
3414 (line-move arg nil nil try-vscroll)))
3415 nil)
3416
3417 (defun previous-line (&optional arg try-vscroll)
3418 "Move cursor vertically up ARG lines.
3419 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3420 If there is no character in the target line exactly over the current column,
3421 the cursor is positioned after the character in that line which spans this
3422 column, or at the end of the line if it is not long enough.
3423
3424 The command \\[set-goal-column] can be used to create
3425 a semipermanent goal column for this command.
3426 Then instead of trying to move exactly vertically (or as close as possible),
3427 this command moves to the specified goal column (or as close as possible).
3428 The goal column is stored in the variable `goal-column', which is nil
3429 when there is no goal column.
3430
3431 If you are thinking of using this in a Lisp program, consider using
3432 `forward-line' with a negative argument instead. It is usually easier
3433 to use and more reliable (no dependence on goal column, etc.)."
3434 (interactive "p\np")
3435 (or arg (setq arg 1))
3436 (if (interactive-p)
3437 (condition-case nil
3438 (line-move (- arg) nil nil try-vscroll)
3439 ((beginning-of-buffer end-of-buffer) (ding)))
3440 (line-move (- arg) nil nil try-vscroll))
3441 nil)
3442
3443 (defcustom track-eol nil
3444 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
3445 This means moving to the end of each line moved onto.
3446 The beginning of a blank line does not count as the end of a line."
3447 :type 'boolean
3448 :group 'editing-basics)
3449
3450 (defcustom goal-column nil
3451 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
3452 :type '(choice integer
3453 (const :tag "None" nil))
3454 :group 'editing-basics)
3455 (make-variable-buffer-local 'goal-column)
3456
3457 (defvar temporary-goal-column 0
3458 "Current goal column for vertical motion.
3459 It is the column where point was
3460 at the start of current run of vertical motion commands.
3461 When the `track-eol' feature is doing its job, the value is 9999.")
3462
3463 (defcustom line-move-ignore-invisible t
3464 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
3465 Outline mode sets this."
3466 :type 'boolean
3467 :group 'editing-basics)
3468
3469 (defun line-move-invisible-p (pos)
3470 "Return non-nil if the character after POS is currently invisible."
3471 (let ((prop
3472 (get-char-property pos 'invisible)))
3473 (if (eq buffer-invisibility-spec t)
3474 prop
3475 (or (memq prop buffer-invisibility-spec)
3476 (assq prop buffer-invisibility-spec)))))
3477
3478 ;; This is like line-move-1 except that it also performs
3479 ;; vertical scrolling of tall images if appropriate.
3480 ;; That is not really a clean thing to do, since it mixes
3481 ;; scrolling with cursor motion. But so far we don't have
3482 ;; a cleaner solution to the problem of making C-n do something
3483 ;; useful given a tall image.
3484 (defun line-move (arg &optional noerror to-end try-vscroll)
3485 (if (and auto-window-vscroll try-vscroll
3486 ;; But don't vscroll in a keyboard macro.
3487 (not defining-kbd-macro)
3488 (not executing-kbd-macro))
3489 (let ((forward (> arg 0))
3490 (part (nth 2 (pos-visible-in-window-p (point) nil t))))
3491 (if (and (consp part)
3492 (> (if forward (cdr part) (car part)) 0))
3493 (set-window-vscroll nil
3494 (if forward
3495 (+ (window-vscroll nil t)
3496 (min (cdr part)
3497 (* (frame-char-height) arg)))
3498 (max 0
3499 (- (window-vscroll nil t)
3500 (min (car part)
3501 (* (frame-char-height) (- arg))))))
3502 t)
3503 (set-window-vscroll nil 0)
3504 (when (line-move-1 arg noerror to-end)
3505 (when (not forward)
3506 ;; Update display before calling pos-visible-in-window-p,
3507 ;; because it depends on window-start being up-to-date.
3508 (sit-for 0)
3509 ;; If the current line is partly hidden at the bottom,
3510 ;; scroll it partially up so as to unhide the bottom.
3511 (if (and (setq part (nth 2 (pos-visible-in-window-p
3512 (line-beginning-position) nil t)))
3513 (> (cdr part) 0))
3514 (set-window-vscroll nil (cdr part) t)))
3515 t)))
3516 (line-move-1 arg noerror to-end)))
3517
3518 ;; This is the guts of next-line and previous-line.
3519 ;; Arg says how many lines to move.
3520 ;; The value is t if we can move the specified number of lines.
3521 (defun line-move-1 (arg &optional noerror to-end)
3522 ;; Don't run any point-motion hooks, and disregard intangibility,
3523 ;; for intermediate positions.
3524 (let ((inhibit-point-motion-hooks t)
3525 (opoint (point))
3526 (forward (> arg 0)))
3527 (unwind-protect
3528 (progn
3529 (if (not (memq last-command '(next-line previous-line)))
3530 (setq temporary-goal-column
3531 (if (and track-eol (eolp)
3532 ;; Don't count beg of empty line as end of line
3533 ;; unless we just did explicit end-of-line.
3534 (or (not (bolp)) (eq last-command 'move-end-of-line)))
3535 9999
3536 (current-column))))
3537
3538 (if (and (not (integerp selective-display))
3539 (not line-move-ignore-invisible))
3540 ;; Use just newline characters.
3541 ;; Set ARG to 0 if we move as many lines as requested.
3542 (or (if (> arg 0)
3543 (progn (if (> arg 1) (forward-line (1- arg)))
3544 ;; This way of moving forward ARG lines
3545 ;; verifies that we have a newline after the last one.
3546 ;; It doesn't get confused by intangible text.
3547 (end-of-line)
3548 (if (zerop (forward-line 1))
3549 (setq arg 0)))
3550 (and (zerop (forward-line arg))
3551 (bolp)
3552 (setq arg 0)))
3553 (unless noerror
3554 (signal (if (< arg 0)
3555 'beginning-of-buffer
3556 'end-of-buffer)
3557 nil)))
3558 ;; Move by arg lines, but ignore invisible ones.
3559 (let (done)
3560 (while (and (> arg 0) (not done))
3561 ;; If the following character is currently invisible,
3562 ;; skip all characters with that same `invisible' property value.
3563 (while (and (not (eobp)) (line-move-invisible-p (point)))
3564 (goto-char (next-char-property-change (point))))
3565 ;; Now move a line.
3566 (end-of-line)
3567 ;; If there's no invisibility here, move over the newline.
3568 (cond
3569 ((eobp)
3570 (if (not noerror)
3571 (signal 'end-of-buffer nil)
3572 (setq done t)))
3573 ((and (> arg 1) ;; Use vertical-motion for last move
3574 (not (integerp selective-display))
3575 (not (line-move-invisible-p (point))))
3576 ;; We avoid vertical-motion when possible
3577 ;; because that has to fontify.
3578 (forward-line 1))
3579 ;; Otherwise move a more sophisticated way.
3580 ((zerop (vertical-motion 1))
3581 (if (not noerror)
3582 (signal 'end-of-buffer nil)
3583 (setq done t))))
3584 (unless done
3585 (setq arg (1- arg))))
3586 ;; The logic of this is the same as the loop above,
3587 ;; it just goes in the other direction.
3588 (while (and (< arg 0) (not done))
3589 (beginning-of-line)
3590 (cond
3591 ((bobp)
3592 (if (not noerror)
3593 (signal 'beginning-of-buffer nil)
3594 (setq done t)))
3595 ((and (< arg -1) ;; Use vertical-motion for last move
3596 (not (integerp selective-display))
3597 (not (line-move-invisible-p (1- (point)))))
3598 (forward-line -1))
3599 ((zerop (vertical-motion -1))
3600 (if (not noerror)
3601 (signal 'beginning-of-buffer nil)
3602 (setq done t))))
3603 (unless done
3604 (setq arg (1+ arg))
3605 (while (and ;; Don't move over previous invis lines
3606 ;; if our target is the middle of this line.
3607 (or (zerop (or goal-column temporary-goal-column))
3608 (< arg 0))
3609 (not (bobp)) (line-move-invisible-p (1- (point))))
3610 (goto-char (previous-char-property-change (point))))))))
3611 ;; This is the value the function returns.
3612 (= arg 0))
3613
3614 (cond ((> arg 0)
3615 ;; If we did not move down as far as desired,
3616 ;; at least go to end of line.
3617 (end-of-line))
3618 ((< arg 0)
3619 ;; If we did not move up as far as desired,
3620 ;; at least go to beginning of line.
3621 (beginning-of-line))
3622 (t
3623 (line-move-finish (or goal-column temporary-goal-column)
3624 opoint forward))))))
3625
3626 (defun line-move-finish (column opoint forward)
3627 (let ((repeat t))
3628 (while repeat
3629 ;; Set REPEAT to t to repeat the whole thing.
3630 (setq repeat nil)
3631
3632 (let (new
3633 (line-beg (save-excursion (beginning-of-line) (point)))
3634 (line-end
3635 ;; Compute the end of the line
3636 ;; ignoring effectively invisible newlines.
3637 (save-excursion
3638 ;; Like end-of-line but ignores fields.
3639 (skip-chars-forward "^\n")
3640 (while (and (not (eobp)) (line-move-invisible-p (point)))
3641 (goto-char (next-char-property-change (point)))
3642 (skip-chars-forward "^\n"))
3643 (point))))
3644
3645 ;; Move to the desired column.
3646 (line-move-to-column column)
3647 (setq new (point))
3648
3649 ;; Process intangibility within a line.
3650 ;; With inhibit-point-motion-hooks bound to nil, a call to
3651 ;; goto-char moves point past intangible text.
3652
3653 ;; However, inhibit-point-motion-hooks controls both the
3654 ;; intangibility and the point-entered/point-left hooks. The
3655 ;; following hack avoids calling the point-* hooks
3656 ;; unnecessarily. Note that we move *forward* past intangible
3657 ;; text when the initial and final points are the same.
3658 (goto-char new)
3659 (let ((inhibit-point-motion-hooks nil))
3660 (goto-char new)
3661
3662 ;; If intangibility moves us to a different (later) place
3663 ;; in the same line, use that as the destination.
3664 (if (<= (point) line-end)
3665 (setq new (point))
3666 ;; If that position is "too late",
3667 ;; try the previous allowable position.
3668 ;; See if it is ok.
3669 (backward-char)
3670 (if (if forward
3671 ;; If going forward, don't accept the previous
3672 ;; allowable position if it is before the target line.
3673 (< line-beg (point))
3674 ;; If going backward, don't accept the previous
3675 ;; allowable position if it is still after the target line.
3676 (<= (point) line-end))
3677 (setq new (point))
3678 ;; As a last resort, use the end of the line.
3679 (setq new line-end))))
3680
3681 ;; Now move to the updated destination, processing fields
3682 ;; as well as intangibility.
3683 (goto-char opoint)
3684 (let ((inhibit-point-motion-hooks nil))
3685 (goto-char
3686 (constrain-to-field new opoint nil t
3687 'inhibit-line-move-field-capture)))
3688
3689 ;; If all this moved us to a different line,
3690 ;; retry everything within that new line.
3691 (when (or (< (point) line-beg) (> (point) line-end))
3692 ;; Repeat the intangibility and field processing.
3693 (setq repeat t))))))
3694
3695 (defun line-move-to-column (col)
3696 "Try to find column COL, considering invisibility.
3697 This function works only in certain cases,
3698 because what we really need is for `move-to-column'
3699 and `current-column' to be able to ignore invisible text."
3700 (if (zerop col)
3701 (beginning-of-line)
3702 (let ((opoint (point)))
3703 (move-to-column col)
3704 ;; move-to-column doesn't respect field boundaries.
3705 (goto-char (constrain-to-field (point) opoint))))
3706
3707 (when (and line-move-ignore-invisible
3708 (not (bolp)) (line-move-invisible-p (1- (point))))
3709 (let ((normal-location (point))
3710 (normal-column (current-column)))
3711 ;; If the following character is currently invisible,
3712 ;; skip all characters with that same `invisible' property value.
3713 (while (and (not (eobp))
3714 (line-move-invisible-p (point)))
3715 (goto-char (next-char-property-change (point))))
3716 ;; Have we advanced to a larger column position?
3717 (if (> (current-column) normal-column)
3718 ;; We have made some progress towards the desired column.
3719 ;; See if we can make any further progress.
3720 (line-move-to-column (+ (current-column) (- col normal-column)))
3721 ;; Otherwise, go to the place we originally found
3722 ;; and move back over invisible text.
3723 ;; that will get us to the same place on the screen
3724 ;; but with a more reasonable buffer position.
3725 (goto-char normal-location)
3726 (let ((line-beg (save-excursion (beginning-of-line) (point))))
3727 (while (and (not (bolp)) (line-move-invisible-p (1- (point))))
3728 (goto-char (previous-char-property-change (point) line-beg))))))))
3729
3730 (defun move-end-of-line (arg)
3731 "Move point to end of current line as displayed.
3732 \(If there's an image in the line, this disregards newlines
3733 which are part of the text that the image rests on.)
3734
3735 With argument ARG not nil or 1, move forward ARG - 1 lines first.
3736 If point reaches the beginning or end of buffer, it stops there.
3737 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
3738 (interactive "p")
3739 (or arg (setq arg 1))
3740 (let (done)
3741 (while (not done)
3742 (let ((newpos
3743 (save-excursion
3744 (let ((goal-column 0))
3745 (and (line-move arg t)
3746 (not (bobp))
3747 (progn
3748 (while (and (not (bobp)) (line-move-invisible-p (1- (point))))
3749 (goto-char (previous-char-property-change (point))))
3750 (backward-char 1)))
3751 (point)))))
3752 (goto-char newpos)
3753 (if (and (> (point) newpos)
3754 (eq (preceding-char) ?\n))
3755 (backward-char 1)
3756 (if (and (> (point) newpos) (not (eobp))
3757 (not (eq (following-char) ?\n)))
3758 ;; If we skipped something intangible
3759 ;; and now we're not really at eol,
3760 ;; keep going.
3761 (setq arg 1)
3762 (setq done t)))))))
3763
3764 (defun move-beginning-of-line (arg)
3765 "Move point to beginning of current line as displayed.
3766 \(If there's an image in the line, this disregards newlines
3767 which are part of the text that the image rests on.)
3768
3769 With argument ARG not nil or 1, move forward ARG - 1 lines first.
3770 If point reaches the beginning or end of buffer, it stops there.
3771 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
3772 (interactive "p")
3773 (or arg (setq arg 1))
3774
3775 (let ((orig (point))
3776 start first-vis first-vis-field-value)
3777
3778 ;; Move by lines, if ARG is not 1 (the default).
3779 (if (/= arg 1)
3780 (line-move (1- arg) t))
3781
3782 ;; Move to beginning-of-line, ignoring fields and invisibles.
3783 (skip-chars-backward "^\n")
3784 (while (and (not (bobp)) (line-move-invisible-p (1- (point))))
3785 (goto-char (previous-char-property-change (point)))
3786 (skip-chars-backward "^\n"))
3787 (setq start (point))
3788
3789 ;; Now find first visible char in the line
3790 (while (and (not (eobp)) (line-move-invisible-p (point)))
3791 (goto-char (next-char-property-change (point))))
3792 (setq first-vis (point))
3793
3794 ;; See if fields would stop us from reaching FIRST-VIS.
3795 (setq first-vis-field-value
3796 (constrain-to-field first-vis orig (/= arg 1) t nil))
3797
3798 (goto-char (if (/= first-vis-field-value first-vis)
3799 ;; If yes, obey them.
3800 first-vis-field-value
3801 ;; Otherwise, move to START with attention to fields.
3802 ;; (It is possible that fields never matter in this case.)
3803 (constrain-to-field (point) orig
3804 (/= arg 1) t nil)))))
3805
3806
3807 ;;; Many people have said they rarely use this feature, and often type
3808 ;;; it by accident. Maybe it shouldn't even be on a key.
3809 (put 'set-goal-column 'disabled t)
3810
3811 (defun set-goal-column (arg)
3812 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
3813 Those commands will move to this position in the line moved to
3814 rather than trying to keep the same horizontal position.
3815 With a non-nil argument, clears out the goal column
3816 so that \\[next-line] and \\[previous-line] resume vertical motion.
3817 The goal column is stored in the variable `goal-column'."
3818 (interactive "P")
3819 (if arg
3820 (progn
3821 (setq goal-column nil)
3822 (message "No goal column"))
3823 (setq goal-column (current-column))
3824 ;; The older method below can be erroneous if `set-goal-column' is bound
3825 ;; to a sequence containing %
3826 ;;(message (substitute-command-keys
3827 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
3828 ;;goal-column)
3829 (message "%s"
3830 (concat
3831 (format "Goal column %d " goal-column)
3832 (substitute-command-keys
3833 "(use \\[set-goal-column] with an arg to unset it)")))
3834
3835 )
3836 nil)
3837 \f
3838
3839 (defun scroll-other-window-down (lines)
3840 "Scroll the \"other window\" down.
3841 For more details, see the documentation for `scroll-other-window'."
3842 (interactive "P")
3843 (scroll-other-window
3844 ;; Just invert the argument's meaning.
3845 ;; We can do that without knowing which window it will be.
3846 (if (eq lines '-) nil
3847 (if (null lines) '-
3848 (- (prefix-numeric-value lines))))))
3849
3850 (defun beginning-of-buffer-other-window (arg)
3851 "Move point to the beginning of the buffer in the other window.
3852 Leave mark at previous position.
3853 With arg N, put point N/10 of the way from the true beginning."
3854 (interactive "P")
3855 (let ((orig-window (selected-window))
3856 (window (other-window-for-scrolling)))
3857 ;; We use unwind-protect rather than save-window-excursion
3858 ;; because the latter would preserve the things we want to change.
3859 (unwind-protect
3860 (progn
3861 (select-window window)
3862 ;; Set point and mark in that window's buffer.
3863 (with-no-warnings
3864 (beginning-of-buffer arg))
3865 ;; Set point accordingly.
3866 (recenter '(t)))
3867 (select-window orig-window))))
3868
3869 (defun end-of-buffer-other-window (arg)
3870 "Move point to the end of the buffer in the other window.
3871 Leave mark at previous position.
3872 With arg N, put point N/10 of the way from the true end."
3873 (interactive "P")
3874 ;; See beginning-of-buffer-other-window for comments.
3875 (let ((orig-window (selected-window))
3876 (window (other-window-for-scrolling)))
3877 (unwind-protect
3878 (progn
3879 (select-window window)
3880 (with-no-warnings
3881 (end-of-buffer arg))
3882 (recenter '(t)))
3883 (select-window orig-window))))
3884 \f
3885 (defun transpose-chars (arg)
3886 "Interchange characters around point, moving forward one character.
3887 With prefix arg ARG, effect is to take character before point
3888 and drag it forward past ARG other characters (backward if ARG negative).
3889 If no argument and at end of line, the previous two chars are exchanged."
3890 (interactive "*P")
3891 (and (null arg) (eolp) (forward-char -1))
3892 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3893
3894 (defun transpose-words (arg)
3895 "Interchange words around point, leaving point at end of them.
3896 With prefix arg ARG, effect is to take word before or around point
3897 and drag it forward past ARG other words (backward if ARG negative).
3898 If ARG is zero, the words around or after point and around or after mark
3899 are interchanged."
3900 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
3901 (interactive "*p")
3902 (transpose-subr 'forward-word arg))
3903
3904 (defun transpose-sexps (arg)
3905 "Like \\[transpose-words] but applies to sexps.
3906 Does not work on a sexp that point is in the middle of
3907 if it is a list or string."
3908 (interactive "*p")
3909 (transpose-subr
3910 (lambda (arg)
3911 ;; Here we should try to simulate the behavior of
3912 ;; (cons (progn (forward-sexp x) (point))
3913 ;; (progn (forward-sexp (- x)) (point)))
3914 ;; Except that we don't want to rely on the second forward-sexp
3915 ;; putting us back to where we want to be, since forward-sexp-function
3916 ;; might do funny things like infix-precedence.
3917 (if (if (> arg 0)
3918 (looking-at "\\sw\\|\\s_")
3919 (and (not (bobp))
3920 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
3921 ;; Jumping over a symbol. We might be inside it, mind you.
3922 (progn (funcall (if (> arg 0)
3923 'skip-syntax-backward 'skip-syntax-forward)
3924 "w_")
3925 (cons (save-excursion (forward-sexp arg) (point)) (point)))
3926 ;; Otherwise, we're between sexps. Take a step back before jumping
3927 ;; to make sure we'll obey the same precedence no matter which direction
3928 ;; we're going.
3929 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
3930 (cons (save-excursion (forward-sexp arg) (point))
3931 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
3932 (not (zerop (funcall (if (> arg 0)
3933 'skip-syntax-forward
3934 'skip-syntax-backward)
3935 ".")))))
3936 (point)))))
3937 arg 'special))
3938
3939 (defun transpose-lines (arg)
3940 "Exchange current line and previous line, leaving point after both.
3941 With argument ARG, takes previous line and moves it past ARG lines.
3942 With argument 0, interchanges line point is in with line mark is in."
3943 (interactive "*p")
3944 (transpose-subr (function
3945 (lambda (arg)
3946 (if (> arg 0)
3947 (progn
3948 ;; Move forward over ARG lines,
3949 ;; but create newlines if necessary.
3950 (setq arg (forward-line arg))
3951 (if (/= (preceding-char) ?\n)
3952 (setq arg (1+ arg)))
3953 (if (> arg 0)
3954 (newline arg)))
3955 (forward-line arg))))
3956 arg))
3957
3958 (defun transpose-subr (mover arg &optional special)
3959 (let ((aux (if special mover
3960 (lambda (x)
3961 (cons (progn (funcall mover x) (point))
3962 (progn (funcall mover (- x)) (point))))))
3963 pos1 pos2)
3964 (cond
3965 ((= arg 0)
3966 (save-excursion
3967 (setq pos1 (funcall aux 1))
3968 (goto-char (mark))
3969 (setq pos2 (funcall aux 1))
3970 (transpose-subr-1 pos1 pos2))
3971 (exchange-point-and-mark))
3972 ((> arg 0)
3973 (setq pos1 (funcall aux -1))
3974 (setq pos2 (funcall aux arg))
3975 (transpose-subr-1 pos1 pos2)
3976 (goto-char (car pos2)))
3977 (t
3978 (setq pos1 (funcall aux -1))
3979 (goto-char (car pos1))
3980 (setq pos2 (funcall aux arg))
3981 (transpose-subr-1 pos1 pos2)))))
3982
3983 (defun transpose-subr-1 (pos1 pos2)
3984 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
3985 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
3986 (when (> (car pos1) (car pos2))
3987 (let ((swap pos1))
3988 (setq pos1 pos2 pos2 swap)))
3989 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
3990 (atomic-change-group
3991 (let (word2)
3992 ;; FIXME: We first delete the two pieces of text, so markers that
3993 ;; used to point to after the text end up pointing to before it :-(
3994 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
3995 (goto-char (car pos2))
3996 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
3997 (goto-char (car pos1))
3998 (insert word2))))
3999 \f
4000 (defun backward-word (&optional arg)
4001 "Move backward until encountering the beginning of a word.
4002 With argument, do this that many times."
4003 (interactive "p")
4004 (forward-word (- (or arg 1))))
4005
4006 (defun mark-word (&optional arg allow-extend)
4007 "Set mark ARG words away from point.
4008 The place mark goes is the same place \\[forward-word] would
4009 move to with the same argument.
4010 Interactively, if this command is repeated
4011 or (in Transient Mark mode) if the mark is active,
4012 it marks the next ARG words after the ones already marked."
4013 (interactive "P\np")
4014 (cond ((and allow-extend
4015 (or (and (eq last-command this-command) (mark t))
4016 (and transient-mark-mode mark-active)))
4017 (setq arg (if arg (prefix-numeric-value arg)
4018 (if (< (mark) (point)) -1 1)))
4019 (set-mark
4020 (save-excursion
4021 (goto-char (mark))
4022 (forward-word arg)
4023 (point))))
4024 (t
4025 (push-mark
4026 (save-excursion
4027 (forward-word (prefix-numeric-value arg))
4028 (point))
4029 nil t))))
4030
4031 (defun kill-word (arg)
4032 "Kill characters forward until encountering the end of a word.
4033 With argument, do this that many times."
4034 (interactive "p")
4035 (kill-region (point) (progn (forward-word arg) (point))))
4036
4037 (defun backward-kill-word (arg)
4038 "Kill characters backward until encountering the end of a word.
4039 With argument, do this that many times."
4040 (interactive "p")
4041 (kill-word (- arg)))
4042
4043 (defun current-word (&optional strict really-word)
4044 "Return the symbol or word that point is on (or a nearby one) as a string.
4045 The return value includes no text properties.
4046 If optional arg STRICT is non-nil, return nil unless point is within
4047 or adjacent to a symbol or word. In all cases the value can be nil
4048 if there is no word nearby.
4049 The function, belying its name, normally finds a symbol.
4050 If optional arg REALLY-WORD is non-nil, it finds just a word."
4051 (save-excursion
4052 (let* ((oldpoint (point)) (start (point)) (end (point))
4053 (syntaxes (if really-word "w" "w_"))
4054 (not-syntaxes (concat "^" syntaxes)))
4055 (skip-syntax-backward syntaxes) (setq start (point))
4056 (goto-char oldpoint)
4057 (skip-syntax-forward syntaxes) (setq end (point))
4058 (when (and (eq start oldpoint) (eq end oldpoint)
4059 ;; Point is neither within nor adjacent to a word.
4060 (not strict))
4061 ;; Look for preceding word in same line.
4062 (skip-syntax-backward not-syntaxes
4063 (save-excursion (beginning-of-line)
4064 (point)))
4065 (if (bolp)
4066 ;; No preceding word in same line.
4067 ;; Look for following word in same line.
4068 (progn
4069 (skip-syntax-forward not-syntaxes
4070 (save-excursion (end-of-line)
4071 (point)))
4072 (setq start (point))
4073 (skip-syntax-forward syntaxes)
4074 (setq end (point)))
4075 (setq end (point))
4076 (skip-syntax-backward syntaxes)
4077 (setq start (point))))
4078 ;; If we found something nonempty, return it as a string.
4079 (unless (= start end)
4080 (buffer-substring-no-properties start end)))))
4081 \f
4082 (defcustom fill-prefix nil
4083 "*String for filling to insert at front of new line, or nil for none."
4084 :type '(choice (const :tag "None" nil)
4085 string)
4086 :group 'fill)
4087 (make-variable-buffer-local 'fill-prefix)
4088 ;;;###autoload(put 'fill-prefix 'safe-local-variable 'string-or-null-p)
4089
4090 (defcustom auto-fill-inhibit-regexp nil
4091 "*Regexp to match lines which should not be auto-filled."
4092 :type '(choice (const :tag "None" nil)
4093 regexp)
4094 :group 'fill)
4095
4096 (defvar comment-line-break-function 'comment-indent-new-line
4097 "*Mode-specific function which line breaks and continues a comment.
4098
4099 This function is only called during auto-filling of a comment section.
4100 The function should take a single optional argument, which is a flag
4101 indicating whether it should use soft newlines.")
4102
4103 ;; This function is used as the auto-fill-function of a buffer
4104 ;; when Auto-Fill mode is enabled.
4105 ;; It returns t if it really did any work.
4106 ;; (Actually some major modes use a different auto-fill function,
4107 ;; but this one is the default one.)
4108 (defun do-auto-fill ()
4109 (let (fc justify give-up
4110 (fill-prefix fill-prefix))
4111 (if (or (not (setq justify (current-justification)))
4112 (null (setq fc (current-fill-column)))
4113 (and (eq justify 'left)
4114 (<= (current-column) fc))
4115 (and auto-fill-inhibit-regexp
4116 (save-excursion (beginning-of-line)
4117 (looking-at auto-fill-inhibit-regexp))))
4118 nil ;; Auto-filling not required
4119 (if (memq justify '(full center right))
4120 (save-excursion (unjustify-current-line)))
4121
4122 ;; Choose a fill-prefix automatically.
4123 (when (and adaptive-fill-mode
4124 (or (null fill-prefix) (string= fill-prefix "")))
4125 (let ((prefix
4126 (fill-context-prefix
4127 (save-excursion (backward-paragraph 1) (point))
4128 (save-excursion (forward-paragraph 1) (point)))))
4129 (and prefix (not (equal prefix ""))
4130 ;; Use auto-indentation rather than a guessed empty prefix.
4131 (not (and fill-indent-according-to-mode
4132 (string-match "\\`[ \t]*\\'" prefix)))
4133 (setq fill-prefix prefix))))
4134
4135 (while (and (not give-up) (> (current-column) fc))
4136 ;; Determine where to split the line.
4137 (let* (after-prefix
4138 (fill-point
4139 (save-excursion
4140 (beginning-of-line)
4141 (setq after-prefix (point))
4142 (and fill-prefix
4143 (looking-at (regexp-quote fill-prefix))
4144 (setq after-prefix (match-end 0)))
4145 (move-to-column (1+ fc))
4146 (fill-move-to-break-point after-prefix)
4147 (point))))
4148
4149 ;; See whether the place we found is any good.
4150 (if (save-excursion
4151 (goto-char fill-point)
4152 (or (bolp)
4153 ;; There is no use breaking at end of line.
4154 (save-excursion (skip-chars-forward " ") (eolp))
4155 ;; It is futile to split at the end of the prefix
4156 ;; since we would just insert the prefix again.
4157 (and after-prefix (<= (point) after-prefix))
4158 ;; Don't split right after a comment starter
4159 ;; since we would just make another comment starter.
4160 (and comment-start-skip
4161 (let ((limit (point)))
4162 (beginning-of-line)
4163 (and (re-search-forward comment-start-skip
4164 limit t)
4165 (eq (point) limit))))))
4166 ;; No good place to break => stop trying.
4167 (setq give-up t)
4168 ;; Ok, we have a useful place to break the line. Do it.
4169 (let ((prev-column (current-column)))
4170 ;; If point is at the fill-point, do not `save-excursion'.
4171 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
4172 ;; point will end up before it rather than after it.
4173 (if (save-excursion
4174 (skip-chars-backward " \t")
4175 (= (point) fill-point))
4176 (funcall comment-line-break-function t)
4177 (save-excursion
4178 (goto-char fill-point)
4179 (funcall comment-line-break-function t)))
4180 ;; Now do justification, if required
4181 (if (not (eq justify 'left))
4182 (save-excursion
4183 (end-of-line 0)
4184 (justify-current-line justify nil t)))
4185 ;; If making the new line didn't reduce the hpos of
4186 ;; the end of the line, then give up now;
4187 ;; trying again will not help.
4188 (if (>= (current-column) prev-column)
4189 (setq give-up t))))))
4190 ;; Justify last line.
4191 (justify-current-line justify t t)
4192 t)))
4193
4194 (defvar normal-auto-fill-function 'do-auto-fill
4195 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
4196 Some major modes set this.")
4197
4198 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
4199 ;; FIXME: turn into a proper minor mode.
4200 ;; Add a global minor mode version of it.
4201 (defun auto-fill-mode (&optional arg)
4202 "Toggle Auto Fill mode.
4203 With arg, turn Auto Fill mode on if and only if arg is positive.
4204 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
4205 automatically breaks the line at a previous space.
4206
4207 The value of `normal-auto-fill-function' specifies the function to use
4208 for `auto-fill-function' when turning Auto Fill mode on."
4209 (interactive "P")
4210 (prog1 (setq auto-fill-function
4211 (if (if (null arg)
4212 (not auto-fill-function)
4213 (> (prefix-numeric-value arg) 0))
4214 normal-auto-fill-function
4215 nil))
4216 (force-mode-line-update)))
4217
4218 ;; This holds a document string used to document auto-fill-mode.
4219 (defun auto-fill-function ()
4220 "Automatically break line at a previous space, in insertion of text."
4221 nil)
4222
4223 (defun turn-on-auto-fill ()
4224 "Unconditionally turn on Auto Fill mode."
4225 (auto-fill-mode 1))
4226
4227 (defun turn-off-auto-fill ()
4228 "Unconditionally turn off Auto Fill mode."
4229 (auto-fill-mode -1))
4230
4231 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
4232
4233 (defun set-fill-column (arg)
4234 "Set `fill-column' to specified argument.
4235 Use \\[universal-argument] followed by a number to specify a column.
4236 Just \\[universal-argument] as argument means to use the current column."
4237 (interactive "P")
4238 (if (consp arg)
4239 (setq arg (current-column)))
4240 (if (not (integerp arg))
4241 ;; Disallow missing argument; it's probably a typo for C-x C-f.
4242 (error "set-fill-column requires an explicit argument")
4243 (message "Fill column set to %d (was %d)" arg fill-column)
4244 (setq fill-column arg)))
4245 \f
4246 (defun set-selective-display (arg)
4247 "Set `selective-display' to ARG; clear it if no arg.
4248 When the value of `selective-display' is a number > 0,
4249 lines whose indentation is >= that value are not displayed.
4250 The variable `selective-display' has a separate value for each buffer."
4251 (interactive "P")
4252 (if (eq selective-display t)
4253 (error "selective-display already in use for marked lines"))
4254 (let ((current-vpos
4255 (save-restriction
4256 (narrow-to-region (point-min) (point))
4257 (goto-char (window-start))
4258 (vertical-motion (window-height)))))
4259 (setq selective-display
4260 (and arg (prefix-numeric-value arg)))
4261 (recenter current-vpos))
4262 (set-window-start (selected-window) (window-start (selected-window)))
4263 (princ "selective-display set to " t)
4264 (prin1 selective-display t)
4265 (princ "." t))
4266
4267 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
4268 (defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
4269
4270 (defun toggle-truncate-lines (&optional arg)
4271 "Toggle whether to fold or truncate long lines on the screen.
4272 With arg, truncate long lines iff arg is positive.
4273 Note that in side-by-side windows, truncation is always enabled."
4274 (interactive "P")
4275 (setq truncate-lines
4276 (if (null arg)
4277 (not truncate-lines)
4278 (> (prefix-numeric-value arg) 0)))
4279 (force-mode-line-update)
4280 (unless truncate-lines
4281 (let ((buffer (current-buffer)))
4282 (walk-windows (lambda (window)
4283 (if (eq buffer (window-buffer window))
4284 (set-window-hscroll window 0)))
4285 nil t)))
4286 (message "Truncate long lines %s"
4287 (if truncate-lines "enabled" "disabled")))
4288
4289 (defvar overwrite-mode-textual " Ovwrt"
4290 "The string displayed in the mode line when in overwrite mode.")
4291 (defvar overwrite-mode-binary " Bin Ovwrt"
4292 "The string displayed in the mode line when in binary overwrite mode.")
4293
4294 (defun overwrite-mode (arg)
4295 "Toggle overwrite mode.
4296 With arg, turn overwrite mode on iff arg is positive.
4297 In overwrite mode, printing characters typed in replace existing text
4298 on a one-for-one basis, rather than pushing it to the right. At the
4299 end of a line, such characters extend the line. Before a tab,
4300 such characters insert until the tab is filled in.
4301 \\[quoted-insert] still inserts characters in overwrite mode; this
4302 is supposed to make it easier to insert characters when necessary."
4303 (interactive "P")
4304 (setq overwrite-mode
4305 (if (if (null arg) (not overwrite-mode)
4306 (> (prefix-numeric-value arg) 0))
4307 'overwrite-mode-textual))
4308 (force-mode-line-update))
4309
4310 (defun binary-overwrite-mode (arg)
4311 "Toggle binary overwrite mode.
4312 With arg, turn binary overwrite mode on iff arg is positive.
4313 In binary overwrite mode, printing characters typed in replace
4314 existing text. Newlines are not treated specially, so typing at the
4315 end of a line joins the line to the next, with the typed character
4316 between them. Typing before a tab character simply replaces the tab
4317 with the character typed.
4318 \\[quoted-insert] replaces the text at the cursor, just as ordinary
4319 typing characters do.
4320
4321 Note that binary overwrite mode is not its own minor mode; it is a
4322 specialization of overwrite mode, entered by setting the
4323 `overwrite-mode' variable to `overwrite-mode-binary'."
4324 (interactive "P")
4325 (setq overwrite-mode
4326 (if (if (null arg)
4327 (not (eq overwrite-mode 'overwrite-mode-binary))
4328 (> (prefix-numeric-value arg) 0))
4329 'overwrite-mode-binary))
4330 (force-mode-line-update))
4331
4332 (define-minor-mode line-number-mode
4333 "Toggle Line Number mode.
4334 With arg, turn Line Number mode on iff arg is positive.
4335 When Line Number mode is enabled, the line number appears
4336 in the mode line.
4337
4338 Line numbers do not appear for very large buffers and buffers
4339 with very long lines; see variables `line-number-display-limit'
4340 and `line-number-display-limit-width'."
4341 :init-value t :global t :group 'editing-basics)
4342
4343 (define-minor-mode column-number-mode
4344 "Toggle Column Number mode.
4345 With arg, turn Column Number mode on iff arg is positive.
4346 When Column Number mode is enabled, the column number appears
4347 in the mode line."
4348 :global t :group 'editing-basics)
4349
4350 (define-minor-mode size-indication-mode
4351 "Toggle Size Indication mode.
4352 With arg, turn Size Indication mode on iff arg is positive. When
4353 Size Indication mode is enabled, the size of the accessible part
4354 of the buffer appears in the mode line."
4355 :global t :group 'editing-basics)
4356 \f
4357 (defgroup paren-blinking nil
4358 "Blinking matching of parens and expressions."
4359 :prefix "blink-matching-"
4360 :group 'paren-matching)
4361
4362 (defcustom blink-matching-paren t
4363 "*Non-nil means show matching open-paren when close-paren is inserted."
4364 :type 'boolean
4365 :group 'paren-blinking)
4366
4367 (defcustom blink-matching-paren-on-screen t
4368 "*Non-nil means show matching open-paren when it is on screen.
4369 If nil, means don't show it (but the open-paren can still be shown
4370 when it is off screen).
4371
4372 This variable has no effect if `blink-matching-paren' is nil.
4373 \(In that case, the open-paren is never shown.)
4374 It is also ignored if `show-paren-mode' is enabled."
4375 :type 'boolean
4376 :group 'paren-blinking)
4377
4378 (defcustom blink-matching-paren-distance (* 25 1024)
4379 "*If non-nil, maximum distance to search backwards for matching open-paren.
4380 If nil, search stops at the beginning of the accessible portion of the buffer."
4381 :type '(choice (const nil) integer)
4382 :group 'paren-blinking)
4383
4384 (defcustom blink-matching-delay 1
4385 "*Time in seconds to delay after showing a matching paren."
4386 :type 'number
4387 :group 'paren-blinking)
4388
4389 (defcustom blink-matching-paren-dont-ignore-comments nil
4390 "*nil means `blink-matching-paren' ignores comments.
4391 More precisely, when looking for the matching parenthesis,
4392 it skips the contents of comments that end before point."
4393 :type 'boolean
4394 :group 'paren-blinking)
4395
4396 (defun blink-matching-open ()
4397 "Move cursor momentarily to the beginning of the sexp before point."
4398 (interactive)
4399 (when (and (> (point) (point-min))
4400 blink-matching-paren
4401 ;; Verify an even number of quoting characters precede the close.
4402 (= 1 (logand 1 (- (point)
4403 (save-excursion
4404 (forward-char -1)
4405 (skip-syntax-backward "/\\")
4406 (point))))))
4407 (let* ((oldpos (point))
4408 blinkpos
4409 message-log-max ; Don't log messages about paren matching.
4410 matching-paren
4411 open-paren-line-string)
4412 (save-excursion
4413 (save-restriction
4414 (if blink-matching-paren-distance
4415 (narrow-to-region (max (point-min)
4416 (- (point) blink-matching-paren-distance))
4417 oldpos))
4418 (condition-case ()
4419 (let ((parse-sexp-ignore-comments
4420 (and parse-sexp-ignore-comments
4421 (not blink-matching-paren-dont-ignore-comments))))
4422 (setq blinkpos (scan-sexps oldpos -1)))
4423 (error nil)))
4424 (and blinkpos
4425 ;; Not syntax '$'.
4426 (not (eq (syntax-class (syntax-after blinkpos)) 8))
4427 (setq matching-paren
4428 (let ((syntax (syntax-after blinkpos)))
4429 (and (consp syntax)
4430 (eq (syntax-class syntax) 4)
4431 (cdr syntax)))))
4432 (cond
4433 ((not (or (eq matching-paren (char-before oldpos))
4434 ;; The cdr might hold a new paren-class info rather than
4435 ;; a matching-char info, in which case the two CDRs
4436 ;; should match.
4437 (eq matching-paren (cdr (syntax-after (1- oldpos))))))
4438 (message "Mismatched parentheses"))
4439 ((not blinkpos)
4440 (if (not blink-matching-paren-distance)
4441 (message "Unmatched parenthesis")))
4442 ((pos-visible-in-window-p blinkpos)
4443 ;; Matching open within window, temporarily move to blinkpos but only
4444 ;; if `blink-matching-paren-on-screen' is non-nil.
4445 (and blink-matching-paren-on-screen
4446 (not show-paren-mode)
4447 (save-excursion
4448 (goto-char blinkpos)
4449 (sit-for blink-matching-delay))))
4450 (t
4451 (save-excursion
4452 (goto-char blinkpos)
4453 (setq open-paren-line-string
4454 ;; Show what precedes the open in its line, if anything.
4455 (if (save-excursion
4456 (skip-chars-backward " \t")
4457 (not (bolp)))
4458 (buffer-substring (line-beginning-position)
4459 (1+ blinkpos))
4460 ;; Show what follows the open in its line, if anything.
4461 (if (save-excursion
4462 (forward-char 1)
4463 (skip-chars-forward " \t")
4464 (not (eolp)))
4465 (buffer-substring blinkpos
4466 (line-end-position))
4467 ;; Otherwise show the previous nonblank line,
4468 ;; if there is one.
4469 (if (save-excursion
4470 (skip-chars-backward "\n \t")
4471 (not (bobp)))
4472 (concat
4473 (buffer-substring (progn
4474 (skip-chars-backward "\n \t")
4475 (line-beginning-position))
4476 (progn (end-of-line)
4477 (skip-chars-backward " \t")
4478 (point)))
4479 ;; Replace the newline and other whitespace with `...'.
4480 "..."
4481 (buffer-substring blinkpos (1+ blinkpos)))
4482 ;; There is nothing to show except the char itself.
4483 (buffer-substring blinkpos (1+ blinkpos)))))))
4484 (message "Matches %s"
4485 (substring-no-properties open-paren-line-string))))))))
4486
4487 ;Turned off because it makes dbx bomb out.
4488 (setq blink-paren-function 'blink-matching-open)
4489 \f
4490 ;; This executes C-g typed while Emacs is waiting for a command.
4491 ;; Quitting out of a program does not go through here;
4492 ;; that happens in the QUIT macro at the C code level.
4493 (defun keyboard-quit ()
4494 "Signal a `quit' condition.
4495 During execution of Lisp code, this character causes a quit directly.
4496 At top-level, as an editor command, this simply beeps."
4497 (interactive)
4498 (deactivate-mark)
4499 (if (fboundp 'kmacro-keyboard-quit)
4500 (kmacro-keyboard-quit))
4501 (setq defining-kbd-macro nil)
4502 (signal 'quit nil))
4503
4504 (defvar buffer-quit-function nil
4505 "Function to call to \"quit\" the current buffer, or nil if none.
4506 \\[keyboard-escape-quit] calls this function when its more local actions
4507 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
4508
4509 (defun keyboard-escape-quit ()
4510 "Exit the current \"mode\" (in a generalized sense of the word).
4511 This command can exit an interactive command such as `query-replace',
4512 can clear out a prefix argument or a region,
4513 can get out of the minibuffer or other recursive edit,
4514 cancel the use of the current buffer (for special-purpose buffers),
4515 or go back to just one window (by deleting all but the selected window)."
4516 (interactive)
4517 (cond ((eq last-command 'mode-exited) nil)
4518 ((> (minibuffer-depth) 0)
4519 (abort-recursive-edit))
4520 (current-prefix-arg
4521 nil)
4522 ((and transient-mark-mode mark-active)
4523 (deactivate-mark))
4524 ((> (recursion-depth) 0)
4525 (exit-recursive-edit))
4526 (buffer-quit-function
4527 (funcall buffer-quit-function))
4528 ((not (one-window-p t))
4529 (delete-other-windows))
4530 ((string-match "^ \\*" (buffer-name (current-buffer)))
4531 (bury-buffer))))
4532
4533 (defun play-sound-file (file &optional volume device)
4534 "Play sound stored in FILE.
4535 VOLUME and DEVICE correspond to the keywords of the sound
4536 specification for `play-sound'."
4537 (interactive "fPlay sound file: ")
4538 (let ((sound (list :file file)))
4539 (if volume
4540 (plist-put sound :volume volume))
4541 (if device
4542 (plist-put sound :device device))
4543 (push 'sound sound)
4544 (play-sound sound)))
4545
4546 \f
4547 (defcustom read-mail-command 'rmail
4548 "*Your preference for a mail reading package.
4549 This is used by some keybindings which support reading mail.
4550 See also `mail-user-agent' concerning sending mail."
4551 :type '(choice (function-item rmail)
4552 (function-item gnus)
4553 (function-item mh-rmail)
4554 (function :tag "Other"))
4555 :version "21.1"
4556 :group 'mail)
4557
4558 (defcustom mail-user-agent 'sendmail-user-agent
4559 "*Your preference for a mail composition package.
4560 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
4561 outgoing email message. This variable lets you specify which
4562 mail-sending package you prefer.
4563
4564 Valid values include:
4565
4566 `sendmail-user-agent' -- use the default Emacs Mail package.
4567 See Info node `(emacs)Sending Mail'.
4568 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
4569 See Info node `(mh-e)'.
4570 `message-user-agent' -- use the Gnus Message package.
4571 See Info node `(message)'.
4572 `gnus-user-agent' -- like `message-user-agent', but with Gnus
4573 paraphernalia, particularly the Gcc: header for
4574 archiving.
4575
4576 Additional valid symbols may be available; check with the author of
4577 your package for details. The function should return non-nil if it
4578 succeeds.
4579
4580 See also `read-mail-command' concerning reading mail."
4581 :type '(radio (function-item :tag "Default Emacs mail"
4582 :format "%t\n"
4583 sendmail-user-agent)
4584 (function-item :tag "Emacs interface to MH"
4585 :format "%t\n"
4586 mh-e-user-agent)
4587 (function-item :tag "Gnus Message package"
4588 :format "%t\n"
4589 message-user-agent)
4590 (function-item :tag "Gnus Message with full Gnus features"
4591 :format "%t\n"
4592 gnus-user-agent)
4593 (function :tag "Other"))
4594 :group 'mail)
4595
4596 (define-mail-user-agent 'sendmail-user-agent
4597 'sendmail-user-agent-compose
4598 'mail-send-and-exit)
4599
4600 (defun rfc822-goto-eoh ()
4601 ;; Go to header delimiter line in a mail message, following RFC822 rules
4602 (goto-char (point-min))
4603 (when (re-search-forward
4604 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
4605 (goto-char (match-beginning 0))))
4606
4607 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
4608 switch-function yank-action
4609 send-actions)
4610 (if switch-function
4611 (let ((special-display-buffer-names nil)
4612 (special-display-regexps nil)
4613 (same-window-buffer-names nil)
4614 (same-window-regexps nil))
4615 (funcall switch-function "*mail*")))
4616 (let ((cc (cdr (assoc-string "cc" other-headers t)))
4617 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
4618 (body (cdr (assoc-string "body" other-headers t))))
4619 (or (mail continue to subject in-reply-to cc yank-action send-actions)
4620 continue
4621 (error "Message aborted"))
4622 (save-excursion
4623 (rfc822-goto-eoh)
4624 (while other-headers
4625 (unless (member-ignore-case (car (car other-headers))
4626 '("in-reply-to" "cc" "body"))
4627 (insert (car (car other-headers)) ": "
4628 (cdr (car other-headers))
4629 (if use-hard-newlines hard-newline "\n")))
4630 (setq other-headers (cdr other-headers)))
4631 (when body
4632 (forward-line 1)
4633 (insert body))
4634 t)))
4635
4636 (defun compose-mail (&optional to subject other-headers continue
4637 switch-function yank-action send-actions)
4638 "Start composing a mail message to send.
4639 This uses the user's chosen mail composition package
4640 as selected with the variable `mail-user-agent'.
4641 The optional arguments TO and SUBJECT specify recipients
4642 and the initial Subject field, respectively.
4643
4644 OTHER-HEADERS is an alist specifying additional
4645 header fields. Elements look like (HEADER . VALUE) where both
4646 HEADER and VALUE are strings.
4647
4648 CONTINUE, if non-nil, says to continue editing a message already
4649 being composed.
4650
4651 SWITCH-FUNCTION, if non-nil, is a function to use to
4652 switch to and display the buffer used for mail composition.
4653
4654 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
4655 to insert the raw text of the message being replied to.
4656 It has the form (FUNCTION . ARGS). The user agent will apply
4657 FUNCTION to ARGS, to insert the raw text of the original message.
4658 \(The user agent will also run `mail-citation-hook', *after* the
4659 original text has been inserted in this way.)
4660
4661 SEND-ACTIONS is a list of actions to call when the message is sent.
4662 Each action has the form (FUNCTION . ARGS)."
4663 (interactive
4664 (list nil nil nil current-prefix-arg))
4665 (let ((function (get mail-user-agent 'composefunc)))
4666 (funcall function to subject other-headers continue
4667 switch-function yank-action send-actions)))
4668
4669 (defun compose-mail-other-window (&optional to subject other-headers continue
4670 yank-action send-actions)
4671 "Like \\[compose-mail], but edit the outgoing message in another window."
4672 (interactive
4673 (list nil nil nil current-prefix-arg))
4674 (compose-mail to subject other-headers continue
4675 'switch-to-buffer-other-window yank-action send-actions))
4676
4677
4678 (defun compose-mail-other-frame (&optional to subject other-headers continue
4679 yank-action send-actions)
4680 "Like \\[compose-mail], but edit the outgoing message in another frame."
4681 (interactive
4682 (list nil nil nil current-prefix-arg))
4683 (compose-mail to subject other-headers continue
4684 'switch-to-buffer-other-frame yank-action send-actions))
4685 \f
4686 (defvar set-variable-value-history nil
4687 "History of values entered with `set-variable'.")
4688
4689 (defun set-variable (variable value &optional make-local)
4690 "Set VARIABLE to VALUE. VALUE is a Lisp object.
4691 VARIABLE should be a user option variable name, a Lisp variable
4692 meant to be customized by users. You should enter VALUE in Lisp syntax,
4693 so if you want VALUE to be a string, you must surround it with doublequotes.
4694 VALUE is used literally, not evaluated.
4695
4696 If VARIABLE has a `variable-interactive' property, that is used as if
4697 it were the arg to `interactive' (which see) to interactively read VALUE.
4698
4699 If VARIABLE has been defined with `defcustom', then the type information
4700 in the definition is used to check that VALUE is valid.
4701
4702 With a prefix argument, set VARIABLE to VALUE buffer-locally."
4703 (interactive
4704 (let* ((default-var (variable-at-point))
4705 (var (if (user-variable-p default-var)
4706 (read-variable (format "Set variable (default %s): " default-var)
4707 default-var)
4708 (read-variable "Set variable: ")))
4709 (minibuffer-help-form '(describe-variable var))
4710 (prop (get var 'variable-interactive))
4711 (obsolete (car (get var 'byte-obsolete-variable)))
4712 (prompt (format "Set %s %s to value: " var
4713 (cond ((local-variable-p var)
4714 "(buffer-local)")
4715 ((or current-prefix-arg
4716 (local-variable-if-set-p var))
4717 "buffer-locally")
4718 (t "globally"))))
4719 (val (progn
4720 (when obsolete
4721 (message (concat "`%S' is obsolete; "
4722 (if (symbolp obsolete) "use `%S' instead" "%s"))
4723 var obsolete)
4724 (sit-for 3))
4725 (if prop
4726 ;; Use VAR's `variable-interactive' property
4727 ;; as an interactive spec for prompting.
4728 (call-interactively `(lambda (arg)
4729 (interactive ,prop)
4730 arg))
4731 (read
4732 (read-string prompt nil
4733 'set-variable-value-history
4734 (format "%S" (symbol-value var))))))))
4735 (list var val current-prefix-arg)))
4736
4737 (and (custom-variable-p variable)
4738 (not (get variable 'custom-type))
4739 (custom-load-symbol variable))
4740 (let ((type (get variable 'custom-type)))
4741 (when type
4742 ;; Match with custom type.
4743 (require 'cus-edit)
4744 (setq type (widget-convert type))
4745 (unless (widget-apply type :match value)
4746 (error "Value `%S' does not match type %S of %S"
4747 value (car type) variable))))
4748
4749 (if make-local
4750 (make-local-variable variable))
4751
4752 (set variable value)
4753
4754 ;; Force a thorough redisplay for the case that the variable
4755 ;; has an effect on the display, like `tab-width' has.
4756 (force-mode-line-update))
4757 \f
4758 ;; Define the major mode for lists of completions.
4759
4760 (defvar completion-list-mode-map nil
4761 "Local map for completion list buffers.")
4762 (or completion-list-mode-map
4763 (let ((map (make-sparse-keymap)))
4764 (define-key map [mouse-2] 'mouse-choose-completion)
4765 (define-key map [follow-link] 'mouse-face)
4766 (define-key map [down-mouse-2] nil)
4767 (define-key map "\C-m" 'choose-completion)
4768 (define-key map "\e\e\e" 'delete-completion-window)
4769 (define-key map [left] 'previous-completion)
4770 (define-key map [right] 'next-completion)
4771 (setq completion-list-mode-map map)))
4772
4773 ;; Completion mode is suitable only for specially formatted data.
4774 (put 'completion-list-mode 'mode-class 'special)
4775
4776 (defvar completion-reference-buffer nil
4777 "Record the buffer that was current when the completion list was requested.
4778 This is a local variable in the completion list buffer.
4779 Initial value is nil to avoid some compiler warnings.")
4780
4781 (defvar completion-no-auto-exit nil
4782 "Non-nil means `choose-completion-string' should never exit the minibuffer.
4783 This also applies to other functions such as `choose-completion'
4784 and `mouse-choose-completion'.")
4785
4786 (defvar completion-base-size nil
4787 "Number of chars at beginning of minibuffer not involved in completion.
4788 This is a local variable in the completion list buffer
4789 but it talks about the buffer in `completion-reference-buffer'.
4790 If this is nil, it means to compare text to determine which part
4791 of the tail end of the buffer's text is involved in completion.")
4792
4793 (defun delete-completion-window ()
4794 "Delete the completion list window.
4795 Go to the window from which completion was requested."
4796 (interactive)
4797 (let ((buf completion-reference-buffer))
4798 (if (one-window-p t)
4799 (if (window-dedicated-p (selected-window))
4800 (delete-frame (selected-frame)))
4801 (delete-window (selected-window))
4802 (if (get-buffer-window buf)
4803 (select-window (get-buffer-window buf))))))
4804
4805 (defun previous-completion (n)
4806 "Move to the previous item in the completion list."
4807 (interactive "p")
4808 (next-completion (- n)))
4809
4810 (defun next-completion (n)
4811 "Move to the next item in the completion list.
4812 With prefix argument N, move N items (negative N means move backward)."
4813 (interactive "p")
4814 (let ((beg (point-min)) (end (point-max)))
4815 (while (and (> n 0) (not (eobp)))
4816 ;; If in a completion, move to the end of it.
4817 (when (get-text-property (point) 'mouse-face)
4818 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4819 ;; Move to start of next one.
4820 (unless (get-text-property (point) 'mouse-face)
4821 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4822 (setq n (1- n)))
4823 (while (and (< n 0) (not (bobp)))
4824 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
4825 ;; If in a completion, move to the start of it.
4826 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
4827 (goto-char (previous-single-property-change
4828 (point) 'mouse-face nil beg)))
4829 ;; Move to end of the previous completion.
4830 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
4831 (goto-char (previous-single-property-change
4832 (point) 'mouse-face nil beg)))
4833 ;; Move to the start of that one.
4834 (goto-char (previous-single-property-change
4835 (point) 'mouse-face nil beg))
4836 (setq n (1+ n))))))
4837
4838 (defun choose-completion ()
4839 "Choose the completion that point is in or next to."
4840 (interactive)
4841 (let (beg end completion (buffer completion-reference-buffer)
4842 (base-size completion-base-size))
4843 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
4844 (setq end (point) beg (1+ (point))))
4845 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
4846 (setq end (1- (point)) beg (point)))
4847 (if (null beg)
4848 (error "No completion here"))
4849 (setq beg (previous-single-property-change beg 'mouse-face))
4850 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
4851 (setq completion (buffer-substring-no-properties beg end))
4852 (let ((owindow (selected-window)))
4853 (if (and (one-window-p t 'selected-frame)
4854 (window-dedicated-p (selected-window)))
4855 ;; This is a special buffer's frame
4856 (iconify-frame (selected-frame))
4857 (or (window-dedicated-p (selected-window))
4858 (bury-buffer)))
4859 (select-window owindow))
4860 (choose-completion-string completion buffer base-size)))
4861
4862 ;; Delete the longest partial match for STRING
4863 ;; that can be found before POINT.
4864 (defun choose-completion-delete-max-match (string)
4865 (let ((opoint (point))
4866 len)
4867 ;; Try moving back by the length of the string.
4868 (goto-char (max (- (point) (length string))
4869 (minibuffer-prompt-end)))
4870 ;; See how far back we were actually able to move. That is the
4871 ;; upper bound on how much we can match and delete.
4872 (setq len (- opoint (point)))
4873 (if completion-ignore-case
4874 (setq string (downcase string)))
4875 (while (and (> len 0)
4876 (let ((tail (buffer-substring (point) opoint)))
4877 (if completion-ignore-case
4878 (setq tail (downcase tail)))
4879 (not (string= tail (substring string 0 len)))))
4880 (setq len (1- len))
4881 (forward-char 1))
4882 (delete-char len)))
4883
4884 (defvar choose-completion-string-functions nil
4885 "Functions that may override the normal insertion of a completion choice.
4886 These functions are called in order with four arguments:
4887 CHOICE - the string to insert in the buffer,
4888 BUFFER - the buffer in which the choice should be inserted,
4889 MINI-P - non-nil iff BUFFER is a minibuffer, and
4890 BASE-SIZE - the number of characters in BUFFER before
4891 the string being completed.
4892
4893 If a function in the list returns non-nil, that function is supposed
4894 to have inserted the CHOICE in the BUFFER, and possibly exited
4895 the minibuffer; no further functions will be called.
4896
4897 If all functions in the list return nil, that means to use
4898 the default method of inserting the completion in BUFFER.")
4899
4900 (defun choose-completion-string (choice &optional buffer base-size)
4901 "Switch to BUFFER and insert the completion choice CHOICE.
4902 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
4903 to keep. If it is nil, we call `choose-completion-delete-max-match'
4904 to decide what to delete."
4905
4906 ;; If BUFFER is the minibuffer, exit the minibuffer
4907 ;; unless it is reading a file name and CHOICE is a directory,
4908 ;; or completion-no-auto-exit is non-nil.
4909
4910 (let* ((buffer (or buffer completion-reference-buffer))
4911 (mini-p (minibufferp buffer)))
4912 ;; If BUFFER is a minibuffer, barf unless it's the currently
4913 ;; active minibuffer.
4914 (if (and mini-p
4915 (or (not (active-minibuffer-window))
4916 (not (equal buffer
4917 (window-buffer (active-minibuffer-window))))))
4918 (error "Minibuffer is not active for completion")
4919 ;; Set buffer so buffer-local choose-completion-string-functions works.
4920 (set-buffer buffer)
4921 (unless (run-hook-with-args-until-success
4922 'choose-completion-string-functions
4923 choice buffer mini-p base-size)
4924 ;; Insert the completion into the buffer where it was requested.
4925 (if base-size
4926 (delete-region (+ base-size (if mini-p
4927 (minibuffer-prompt-end)
4928 (point-min)))
4929 (point))
4930 (choose-completion-delete-max-match choice))
4931 (insert choice)
4932 (remove-text-properties (- (point) (length choice)) (point)
4933 '(mouse-face nil))
4934 ;; Update point in the window that BUFFER is showing in.
4935 (let ((window (get-buffer-window buffer t)))
4936 (set-window-point window (point)))
4937 ;; If completing for the minibuffer, exit it with this choice.
4938 (and (not completion-no-auto-exit)
4939 (equal buffer (window-buffer (minibuffer-window)))
4940 minibuffer-completion-table
4941 ;; If this is reading a file name, and the file name chosen
4942 ;; is a directory, don't exit the minibuffer.
4943 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
4944 (file-directory-p (field-string (point-max))))
4945 (let ((mini (active-minibuffer-window)))
4946 (select-window mini)
4947 (when minibuffer-auto-raise
4948 (raise-frame (window-frame mini))))
4949 (exit-minibuffer)))))))
4950
4951 (defun completion-list-mode ()
4952 "Major mode for buffers showing lists of possible completions.
4953 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
4954 to select the completion near point.
4955 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
4956 with the mouse."
4957 (interactive)
4958 (kill-all-local-variables)
4959 (use-local-map completion-list-mode-map)
4960 (setq mode-name "Completion List")
4961 (setq major-mode 'completion-list-mode)
4962 (make-local-variable 'completion-base-size)
4963 (setq completion-base-size nil)
4964 (run-mode-hooks 'completion-list-mode-hook))
4965
4966 (defun completion-list-mode-finish ()
4967 "Finish setup of the completions buffer.
4968 Called from `temp-buffer-show-hook'."
4969 (when (eq major-mode 'completion-list-mode)
4970 (toggle-read-only 1)))
4971
4972 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
4973
4974 (defvar completion-setup-hook nil
4975 "Normal hook run at the end of setting up a completion list buffer.
4976 When this hook is run, the current buffer is the one in which the
4977 command to display the completion list buffer was run.
4978 The completion list buffer is available as the value of `standard-output'.
4979 The common prefix substring for completion may be available as the
4980 value of `completion-common-substring'. See also `display-completion-list'.")
4981
4982
4983 ;; Variables and faces used in `completion-setup-function'.
4984
4985 (defface completions-first-difference
4986 '((t (:inherit bold)))
4987 "Face put on the first uncommon character in completions in *Completions* buffer."
4988 :group 'completion)
4989
4990 (defface completions-common-part
4991 '((t (:inherit default)))
4992 "Face put on the common prefix substring in completions in *Completions* buffer.
4993 The idea of `completions-common-part' is that you can use it to
4994 make the common parts less visible than normal, so that the rest
4995 of the differing parts is, by contrast, slightly highlighted."
4996 :group 'completion)
4997
4998 ;; This is for packages that need to bind it to a non-default regexp
4999 ;; in order to make the first-differing character highlight work
5000 ;; to their liking
5001 (defvar completion-root-regexp "^/"
5002 "Regexp to use in `completion-setup-function' to find the root directory.")
5003
5004 (defvar completion-common-substring nil
5005 "Common prefix substring to use in `completion-setup-function' to put faces.
5006 The value is set by `display-completion-list' during running `completion-setup-hook'.
5007
5008 To put faces `completions-first-difference' and `completions-common-part'
5009 in the `*Completions*' buffer, the common prefix substring in completions
5010 is needed as a hint. (The minibuffer is a special case. The content
5011 of the minibuffer before point is always the common substring.)")
5012
5013 ;; This function goes in completion-setup-hook, so that it is called
5014 ;; after the text of the completion list buffer is written.
5015 (defun completion-setup-function ()
5016 (let* ((mainbuf (current-buffer))
5017 (mbuf-contents (minibuffer-completion-contents))
5018 common-string-length)
5019 ;; When reading a file name in the minibuffer,
5020 ;; set default-directory in the minibuffer
5021 ;; so it will get copied into the completion list buffer.
5022 (if minibuffer-completing-file-name
5023 (with-current-buffer mainbuf
5024 (setq default-directory (file-name-directory mbuf-contents))))
5025 (with-current-buffer standard-output
5026 (completion-list-mode)
5027 (set (make-local-variable 'completion-reference-buffer) mainbuf)
5028 (setq completion-base-size
5029 (cond
5030 ((and (symbolp minibuffer-completion-table)
5031 (get minibuffer-completion-table 'completion-base-size-function))
5032 ;; To compute base size, a function can use the global value of
5033 ;; completion-common-substring or minibuffer-completion-contents.
5034 (with-current-buffer mainbuf
5035 (funcall (get minibuffer-completion-table
5036 'completion-base-size-function))))
5037 (minibuffer-completing-file-name
5038 ;; For file name completion, use the number of chars before
5039 ;; the start of the file name component at point.
5040 (with-current-buffer mainbuf
5041 (save-excursion
5042 (skip-chars-backward completion-root-regexp)
5043 (- (point) (minibuffer-prompt-end)))))
5044 ;; Otherwise, in minibuffer, the base size is 0.
5045 ((minibufferp mainbuf) 0)))
5046 (setq common-string-length
5047 (cond
5048 (completion-common-substring
5049 (length completion-common-substring))
5050 (completion-base-size
5051 (- (length mbuf-contents) completion-base-size))))
5052 ;; Put faces on first uncommon characters and common parts.
5053 (when (and (integerp common-string-length) (>= common-string-length 0))
5054 (let ((element-start (point-min))
5055 (maxp (point-max))
5056 element-common-end)
5057 (while (and (setq element-start
5058 (next-single-property-change
5059 element-start 'mouse-face))
5060 (< (setq element-common-end
5061 (+ element-start common-string-length))
5062 maxp))
5063 (when (get-char-property element-start 'mouse-face)
5064 (if (and (> common-string-length 0)
5065 (get-char-property (1- element-common-end) 'mouse-face))
5066 (put-text-property element-start element-common-end
5067 'font-lock-face 'completions-common-part))
5068 (if (get-char-property element-common-end 'mouse-face)
5069 (put-text-property element-common-end (1+ element-common-end)
5070 'font-lock-face 'completions-first-difference))))))
5071 ;; Insert help string.
5072 (goto-char (point-min))
5073 (if (display-mouse-p)
5074 (insert (substitute-command-keys
5075 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
5076 (insert (substitute-command-keys
5077 "In this buffer, type \\[choose-completion] to \
5078 select the completion near point.\n\n")))))
5079
5080 (add-hook 'completion-setup-hook 'completion-setup-function)
5081
5082 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
5083 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
5084
5085 (defun switch-to-completions ()
5086 "Select the completion list window."
5087 (interactive)
5088 ;; Make sure we have a completions window.
5089 (or (get-buffer-window "*Completions*")
5090 (minibuffer-completion-help))
5091 (let ((window (get-buffer-window "*Completions*")))
5092 (when window
5093 (select-window window)
5094 (goto-char (point-min))
5095 (search-forward "\n\n")
5096 (forward-line 1))))
5097 \f
5098 ;;; Support keyboard commands to turn on various modifiers.
5099
5100 ;; These functions -- which are not commands -- each add one modifier
5101 ;; to the following event.
5102
5103 (defun event-apply-alt-modifier (ignore-prompt)
5104 "\\<function-key-map>Add the Alt modifier to the following event.
5105 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
5106 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
5107 (defun event-apply-super-modifier (ignore-prompt)
5108 "\\<function-key-map>Add the Super modifier to the following event.
5109 For example, type \\[event-apply-super-modifier] & to enter Super-&."
5110 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
5111 (defun event-apply-hyper-modifier (ignore-prompt)
5112 "\\<function-key-map>Add the Hyper modifier to the following event.
5113 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
5114 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
5115 (defun event-apply-shift-modifier (ignore-prompt)
5116 "\\<function-key-map>Add the Shift modifier to the following event.
5117 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
5118 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
5119 (defun event-apply-control-modifier (ignore-prompt)
5120 "\\<function-key-map>Add the Ctrl modifier to the following event.
5121 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
5122 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
5123 (defun event-apply-meta-modifier (ignore-prompt)
5124 "\\<function-key-map>Add the Meta modifier to the following event.
5125 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
5126 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
5127
5128 (defun event-apply-modifier (event symbol lshiftby prefix)
5129 "Apply a modifier flag to event EVENT.
5130 SYMBOL is the name of this modifier, as a symbol.
5131 LSHIFTBY is the numeric value of this modifier, in keyboard events.
5132 PREFIX is the string that represents this modifier in an event type symbol."
5133 (if (numberp event)
5134 (cond ((eq symbol 'control)
5135 (if (and (<= (downcase event) ?z)
5136 (>= (downcase event) ?a))
5137 (- (downcase event) ?a -1)
5138 (if (and (<= (downcase event) ?Z)
5139 (>= (downcase event) ?A))
5140 (- (downcase event) ?A -1)
5141 (logior (lsh 1 lshiftby) event))))
5142 ((eq symbol 'shift)
5143 (if (and (<= (downcase event) ?z)
5144 (>= (downcase event) ?a))
5145 (upcase event)
5146 (logior (lsh 1 lshiftby) event)))
5147 (t
5148 (logior (lsh 1 lshiftby) event)))
5149 (if (memq symbol (event-modifiers event))
5150 event
5151 (let ((event-type (if (symbolp event) event (car event))))
5152 (setq event-type (intern (concat prefix (symbol-name event-type))))
5153 (if (symbolp event)
5154 event-type
5155 (cons event-type (cdr event)))))))
5156
5157 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
5158 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
5159 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
5160 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
5161 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
5162 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
5163 \f
5164 ;;;; Keypad support.
5165
5166 ;;; Make the keypad keys act like ordinary typing keys. If people add
5167 ;;; bindings for the function key symbols, then those bindings will
5168 ;;; override these, so this shouldn't interfere with any existing
5169 ;;; bindings.
5170
5171 ;; Also tell read-char how to handle these keys.
5172 (mapc
5173 (lambda (keypad-normal)
5174 (let ((keypad (nth 0 keypad-normal))
5175 (normal (nth 1 keypad-normal)))
5176 (put keypad 'ascii-character normal)
5177 (define-key function-key-map (vector keypad) (vector normal))))
5178 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
5179 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
5180 (kp-space ?\s)
5181 (kp-tab ?\t)
5182 (kp-enter ?\r)
5183 (kp-multiply ?*)
5184 (kp-add ?+)
5185 (kp-separator ?,)
5186 (kp-subtract ?-)
5187 (kp-decimal ?.)
5188 (kp-divide ?/)
5189 (kp-equal ?=)))
5190 \f
5191 ;;;;
5192 ;;;; forking a twin copy of a buffer.
5193 ;;;;
5194
5195 (defvar clone-buffer-hook nil
5196 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
5197
5198 (defun clone-process (process &optional newname)
5199 "Create a twin copy of PROCESS.
5200 If NEWNAME is nil, it defaults to PROCESS' name;
5201 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
5202 If PROCESS is associated with a buffer, the new process will be associated
5203 with the current buffer instead.
5204 Returns nil if PROCESS has already terminated."
5205 (setq newname (or newname (process-name process)))
5206 (if (string-match "<[0-9]+>\\'" newname)
5207 (setq newname (substring newname 0 (match-beginning 0))))
5208 (when (memq (process-status process) '(run stop open))
5209 (let* ((process-connection-type (process-tty-name process))
5210 (new-process
5211 (if (memq (process-status process) '(open))
5212 (let ((args (process-contact process t)))
5213 (setq args (plist-put args :name newname))
5214 (setq args (plist-put args :buffer
5215 (if (process-buffer process)
5216 (current-buffer))))
5217 (apply 'make-network-process args))
5218 (apply 'start-process newname
5219 (if (process-buffer process) (current-buffer))
5220 (process-command process)))))
5221 (set-process-query-on-exit-flag
5222 new-process (process-query-on-exit-flag process))
5223 (set-process-inherit-coding-system-flag
5224 new-process (process-inherit-coding-system-flag process))
5225 (set-process-filter new-process (process-filter process))
5226 (set-process-sentinel new-process (process-sentinel process))
5227 (set-process-plist new-process (copy-sequence (process-plist process)))
5228 new-process)))
5229
5230 ;; things to maybe add (currently partly covered by `funcall mode'):
5231 ;; - syntax-table
5232 ;; - overlays
5233 (defun clone-buffer (&optional newname display-flag)
5234 "Create and return a twin copy of the current buffer.
5235 Unlike an indirect buffer, the new buffer can be edited
5236 independently of the old one (if it is not read-only).
5237 NEWNAME is the name of the new buffer. It may be modified by
5238 adding or incrementing <N> at the end as necessary to create a
5239 unique buffer name. If nil, it defaults to the name of the
5240 current buffer, with the proper suffix. If DISPLAY-FLAG is
5241 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
5242 clone a file-visiting buffer, or a buffer whose major mode symbol
5243 has a non-nil `no-clone' property, results in an error.
5244
5245 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
5246 current buffer with appropriate suffix. However, if a prefix
5247 argument is given, then the command prompts for NEWNAME in the
5248 minibuffer.
5249
5250 This runs the normal hook `clone-buffer-hook' in the new buffer
5251 after it has been set up properly in other respects."
5252 (interactive
5253 (progn
5254 (if buffer-file-name
5255 (error "Cannot clone a file-visiting buffer"))
5256 (if (get major-mode 'no-clone)
5257 (error "Cannot clone a buffer in %s mode" mode-name))
5258 (list (if current-prefix-arg
5259 (read-buffer "Name of new cloned buffer: " (current-buffer)))
5260 t)))
5261 (if buffer-file-name
5262 (error "Cannot clone a file-visiting buffer"))
5263 (if (get major-mode 'no-clone)
5264 (error "Cannot clone a buffer in %s mode" mode-name))
5265 (setq newname (or newname (buffer-name)))
5266 (if (string-match "<[0-9]+>\\'" newname)
5267 (setq newname (substring newname 0 (match-beginning 0))))
5268 (let ((buf (current-buffer))
5269 (ptmin (point-min))
5270 (ptmax (point-max))
5271 (pt (point))
5272 (mk (if mark-active (mark t)))
5273 (modified (buffer-modified-p))
5274 (mode major-mode)
5275 (lvars (buffer-local-variables))
5276 (process (get-buffer-process (current-buffer)))
5277 (new (generate-new-buffer (or newname (buffer-name)))))
5278 (save-restriction
5279 (widen)
5280 (with-current-buffer new
5281 (insert-buffer-substring buf)))
5282 (with-current-buffer new
5283 (narrow-to-region ptmin ptmax)
5284 (goto-char pt)
5285 (if mk (set-mark mk))
5286 (set-buffer-modified-p modified)
5287
5288 ;; Clone the old buffer's process, if any.
5289 (when process (clone-process process))
5290
5291 ;; Now set up the major mode.
5292 (funcall mode)
5293
5294 ;; Set up other local variables.
5295 (mapcar (lambda (v)
5296 (condition-case () ;in case var is read-only
5297 (if (symbolp v)
5298 (makunbound v)
5299 (set (make-local-variable (car v)) (cdr v)))
5300 (error nil)))
5301 lvars)
5302
5303 ;; Run any hooks (typically set up by the major mode
5304 ;; for cloning to work properly).
5305 (run-hooks 'clone-buffer-hook))
5306 (if display-flag
5307 ;; Presumably the current buffer is shown in the selected frame, so
5308 ;; we want to display the clone elsewhere.
5309 (let ((same-window-regexps nil)
5310 (same-window-buffer-names))
5311 (pop-to-buffer new)))
5312 new))
5313
5314
5315 (defun clone-indirect-buffer (newname display-flag &optional norecord)
5316 "Create an indirect buffer that is a twin copy of the current buffer.
5317
5318 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
5319 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
5320 or if not called with a prefix arg, NEWNAME defaults to the current
5321 buffer's name. The name is modified by adding a `<N>' suffix to it
5322 or by incrementing the N in an existing suffix.
5323
5324 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
5325 This is always done when called interactively.
5326
5327 Optional third arg NORECORD non-nil means do not put this buffer at the
5328 front of the list of recently selected ones."
5329 (interactive
5330 (progn
5331 (if (get major-mode 'no-clone-indirect)
5332 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5333 (list (if current-prefix-arg
5334 (read-buffer "Name of indirect buffer: " (current-buffer)))
5335 t)))
5336 (if (get major-mode 'no-clone-indirect)
5337 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5338 (setq newname (or newname (buffer-name)))
5339 (if (string-match "<[0-9]+>\\'" newname)
5340 (setq newname (substring newname 0 (match-beginning 0))))
5341 (let* ((name (generate-new-buffer-name newname))
5342 (buffer (make-indirect-buffer (current-buffer) name t)))
5343 (when display-flag
5344 (pop-to-buffer buffer norecord))
5345 buffer))
5346
5347
5348 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
5349 "Like `clone-indirect-buffer' but display in another window."
5350 (interactive
5351 (progn
5352 (if (get major-mode 'no-clone-indirect)
5353 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5354 (list (if current-prefix-arg
5355 (read-buffer "Name of indirect buffer: " (current-buffer)))
5356 t)))
5357 (let ((pop-up-windows t))
5358 (clone-indirect-buffer newname display-flag norecord)))
5359
5360 \f
5361 ;;; Handling of Backspace and Delete keys.
5362
5363 (defcustom normal-erase-is-backspace
5364 (and (not noninteractive)
5365 (or (memq system-type '(ms-dos windows-nt))
5366 (eq window-system 'mac)
5367 (and (memq window-system '(x))
5368 (fboundp 'x-backspace-delete-keys-p)
5369 (x-backspace-delete-keys-p))
5370 ;; If the terminal Emacs is running on has erase char
5371 ;; set to ^H, use the Backspace key for deleting
5372 ;; backward and, and the Delete key for deleting forward.
5373 (and (null window-system)
5374 (eq tty-erase-char ?\^H))))
5375 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
5376
5377 On window systems, the default value of this option is chosen
5378 according to the keyboard used. If the keyboard has both a Backspace
5379 key and a Delete key, and both are mapped to their usual meanings, the
5380 option's default value is set to t, so that Backspace can be used to
5381 delete backward, and Delete can be used to delete forward.
5382
5383 If not running under a window system, customizing this option accomplishes
5384 a similar effect by mapping C-h, which is usually generated by the
5385 Backspace key, to DEL, and by mapping DEL to C-d via
5386 `keyboard-translate'. The former functionality of C-h is available on
5387 the F1 key. You should probably not use this setting if you don't
5388 have both Backspace, Delete and F1 keys.
5389
5390 Setting this variable with setq doesn't take effect. Programmatically,
5391 call `normal-erase-is-backspace-mode' (which see) instead."
5392 :type 'boolean
5393 :group 'editing-basics
5394 :version "21.1"
5395 :set (lambda (symbol value)
5396 ;; The fboundp is because of a problem with :set when
5397 ;; dumping Emacs. It doesn't really matter.
5398 (if (fboundp 'normal-erase-is-backspace-mode)
5399 (normal-erase-is-backspace-mode (or value 0))
5400 (set-default symbol value))))
5401
5402
5403 (defun normal-erase-is-backspace-mode (&optional arg)
5404 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
5405
5406 With numeric arg, turn the mode on if and only if ARG is positive.
5407
5408 On window systems, when this mode is on, Delete is mapped to C-d and
5409 Backspace is mapped to DEL; when this mode is off, both Delete and
5410 Backspace are mapped to DEL. (The remapping goes via
5411 `function-key-map', so binding Delete or Backspace in the global or
5412 local keymap will override that.)
5413
5414 In addition, on window systems, the bindings of C-Delete, M-Delete,
5415 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
5416 the global keymap in accordance with the functionality of Delete and
5417 Backspace. For example, if Delete is remapped to C-d, which deletes
5418 forward, C-Delete is bound to `kill-word', but if Delete is remapped
5419 to DEL, which deletes backward, C-Delete is bound to
5420 `backward-kill-word'.
5421
5422 If not running on a window system, a similar effect is accomplished by
5423 remapping C-h (normally produced by the Backspace key) and DEL via
5424 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
5425 to C-d; if it's off, the keys are not remapped.
5426
5427 When not running on a window system, and this mode is turned on, the
5428 former functionality of C-h is available on the F1 key. You should
5429 probably not turn on this mode on a text-only terminal if you don't
5430 have both Backspace, Delete and F1 keys.
5431
5432 See also `normal-erase-is-backspace'."
5433 (interactive "P")
5434 (setq normal-erase-is-backspace
5435 (if arg
5436 (> (prefix-numeric-value arg) 0)
5437 (not normal-erase-is-backspace)))
5438
5439 (cond ((or (memq window-system '(x w32 mac pc))
5440 (memq system-type '(ms-dos windows-nt)))
5441 (let ((bindings
5442 `(([C-delete] [C-backspace])
5443 ([M-delete] [M-backspace])
5444 ([C-M-delete] [C-M-backspace])
5445 (,esc-map
5446 [C-delete] [C-backspace])))
5447 (old-state (lookup-key function-key-map [delete])))
5448
5449 (if normal-erase-is-backspace
5450 (progn
5451 (define-key function-key-map [delete] [?\C-d])
5452 (define-key function-key-map [kp-delete] [?\C-d])
5453 (define-key function-key-map [backspace] [?\C-?]))
5454 (define-key function-key-map [delete] [?\C-?])
5455 (define-key function-key-map [kp-delete] [?\C-?])
5456 (define-key function-key-map [backspace] [?\C-?]))
5457
5458 ;; Maybe swap bindings of C-delete and C-backspace, etc.
5459 (unless (equal old-state (lookup-key function-key-map [delete]))
5460 (dolist (binding bindings)
5461 (let ((map global-map))
5462 (when (keymapp (car binding))
5463 (setq map (car binding) binding (cdr binding)))
5464 (let* ((key1 (nth 0 binding))
5465 (key2 (nth 1 binding))
5466 (binding1 (lookup-key map key1))
5467 (binding2 (lookup-key map key2)))
5468 (define-key map key1 binding2)
5469 (define-key map key2 binding1)))))))
5470 (t
5471 (if normal-erase-is-backspace
5472 (progn
5473 (keyboard-translate ?\C-h ?\C-?)
5474 (keyboard-translate ?\C-? ?\C-d))
5475 (keyboard-translate ?\C-h ?\C-h)
5476 (keyboard-translate ?\C-? ?\C-?))))
5477
5478 (run-hooks 'normal-erase-is-backspace-hook)
5479 (if (interactive-p)
5480 (message "Delete key deletes %s"
5481 (if normal-erase-is-backspace "forward" "backward"))))
5482 \f
5483 (defvar vis-mode-saved-buffer-invisibility-spec nil
5484 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
5485
5486 (define-minor-mode visible-mode
5487 "Toggle Visible mode.
5488 With argument ARG turn Visible mode on iff ARG is positive.
5489
5490 Enabling Visible mode makes all invisible text temporarily visible.
5491 Disabling Visible mode turns off that effect. Visible mode
5492 works by saving the value of `buffer-invisibility-spec' and setting it to nil."
5493 :lighter " Vis"
5494 :group 'editing-basics
5495 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
5496 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
5497 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
5498 (when visible-mode
5499 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
5500 buffer-invisibility-spec)
5501 (setq buffer-invisibility-spec nil)))
5502 \f
5503 ;; Minibuffer prompt stuff.
5504
5505 ;(defun minibuffer-prompt-modification (start end)
5506 ; (error "You cannot modify the prompt"))
5507 ;
5508 ;
5509 ;(defun minibuffer-prompt-insertion (start end)
5510 ; (let ((inhibit-modification-hooks t))
5511 ; (delete-region start end)
5512 ; ;; Discard undo information for the text insertion itself
5513 ; ;; and for the text deletion.above.
5514 ; (when (consp buffer-undo-list)
5515 ; (setq buffer-undo-list (cddr buffer-undo-list)))
5516 ; (message "You cannot modify the prompt")))
5517 ;
5518 ;
5519 ;(setq minibuffer-prompt-properties
5520 ; (list 'modification-hooks '(minibuffer-prompt-modification)
5521 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
5522 ;
5523
5524 (provide 'simple)
5525
5526 ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
5527 ;;; simple.el ends here