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