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