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