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