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