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