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