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