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