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