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