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