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