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