(x_draw_relief_rect): Remove unused variable `dpy'.
[emacs.git] / lisp / simple.el
blobc6acebbb83d2a65298c5187e167339522e156121
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, or (at your option)
15 ;; 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; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
27 ;;; Commentary:
29 ;; A grab-bag of basic Emacs commands not specifically related to some
30 ;; major mode or to file-handling.
32 ;;; Code:
34 (eval-when-compile
35 (autoload 'widget-convert "wid-edit")
36 (autoload '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 (frame-parameter frame 'buried-buffer-list)
90 buffer visible-ok frame)
91 (get-next-valid-buffer (nreverse (buffer-list frame))
92 buffer visible-ok frame)
93 (progn
94 (set-buffer-major-mode (get-buffer-create "*scratch*"))
95 (get-buffer "*scratch*"))))
97 (defun next-buffer ()
98 "Switch to the next buffer in cyclic order."
99 (interactive)
100 (let ((buffer (current-buffer))
101 (bbl (frame-parameter nil 'buried-buffer-list)))
102 (switch-to-buffer (other-buffer buffer t))
103 (bury-buffer buffer)
104 (set-frame-parameter nil 'buried-buffer-list
105 (cons buffer (delq buffer bbl)))))
107 (defun previous-buffer ()
108 "Switch to the previous buffer in cyclic order."
109 (interactive)
110 (let ((buffer (last-buffer (current-buffer) t))
111 (bbl (frame-parameter nil 'buried-buffer-list)))
112 (switch-to-buffer buffer)
113 ;; Clean up buried-buffer-list up to and including the chosen buffer.
114 (while (and bbl (not (eq (car bbl) buffer)))
115 (setq bbl (cdr bbl)))
116 (set-frame-parameter nil 'buried-buffer-list bbl)))
119 ;;; next-error support framework
121 (defgroup next-error nil
122 "`next-error' support framework."
123 :group 'compilation
124 :version "22.1")
126 (defface next-error
127 '((t (:inherit region)))
128 "Face used to highlight next error locus."
129 :group 'next-error
130 :version "22.1")
132 (defcustom next-error-highlight 0.5
133 "*Highlighting of locations in selected source buffers.
134 If a number, highlight the locus in `next-error' face for the given time
135 in seconds, or until the next command is executed.
136 If t, highlight the locus until the next command is executed, or until
137 some other locus replaces it.
138 If nil, don't highlight the locus in the source buffer.
139 If `fringe-arrow', indicate the locus by the fringe arrow."
140 :type '(choice (number :tag "Highlight for specified time")
141 (const :tag "Semipermanent highlighting" t)
142 (const :tag "No highlighting" nil)
143 (const :tag "Fringe arrow" fringe-arrow))
144 :group 'next-error
145 :version "22.1")
147 (defcustom next-error-highlight-no-select 0.5
148 "*Highlighting of locations in `next-error-no-select'.
149 If number, highlight the locus in `next-error' face for given time in seconds.
150 If t, highlight the locus indefinitely until some other locus replaces it.
151 If nil, don't highlight the locus in the source buffer.
152 If `fringe-arrow', indicate the locus by the fringe arrow."
153 :type '(choice (number :tag "Highlight for specified time")
154 (const :tag "Semipermanent highlighting" t)
155 (const :tag "No highlighting" nil)
156 (const :tag "Fringe arrow" fringe-arrow))
157 :group 'next-error
158 :version "22.1")
160 (defcustom next-error-hook nil
161 "*List of hook functions run by `next-error' after visiting source file."
162 :type 'hook
163 :group 'next-error)
165 (defvar next-error-highlight-timer nil)
167 (defvar next-error-overlay-arrow-position nil)
168 (put 'next-error-overlay-arrow-position 'overlay-arrow-string "=>")
169 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
171 (defvar next-error-last-buffer nil
172 "The most recent `next-error' buffer.
173 A buffer becomes most recent when its compilation, grep, or
174 similar mode is started, or when it is used with \\[next-error]
175 or \\[compile-goto-error].")
177 (defvar next-error-function nil
178 "Function to use to find the next error in the current buffer.
179 The function is called with 2 parameters:
180 ARG is an integer specifying by how many errors to move.
181 RESET is a boolean which, if non-nil, says to go back to the beginning
182 of the errors before moving.
183 Major modes providing compile-like functionality should set this variable
184 to indicate to `next-error' that this is a candidate buffer and how
185 to navigate in it.")
187 (make-variable-buffer-local 'next-error-function)
189 (defsubst next-error-buffer-p (buffer
190 &optional avoid-current
191 extra-test-inclusive
192 extra-test-exclusive)
193 "Test if BUFFER is a `next-error' capable buffer.
195 If AVOID-CURRENT is non-nil, treat the current buffer
196 as an absolute last resort only.
198 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
199 that normally would not qualify. If it returns t, the buffer
200 in question is treated as usable.
202 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
203 that would normally be considered usable. If it returns nil,
204 that buffer is rejected."
205 (and (buffer-name buffer) ;First make sure it's live.
206 (not (and avoid-current (eq buffer (current-buffer))))
207 (with-current-buffer buffer
208 (if next-error-function ; This is the normal test.
209 ;; Optionally reject some buffers.
210 (if extra-test-exclusive
211 (funcall extra-test-exclusive)
213 ;; Optionally accept some other buffers.
214 (and extra-test-inclusive
215 (funcall extra-test-inclusive))))))
217 (defun next-error-find-buffer (&optional avoid-current
218 extra-test-inclusive
219 extra-test-exclusive)
220 "Return a `next-error' capable buffer.
222 If AVOID-CURRENT is non-nil, treat the current buffer
223 as an absolute last resort only.
225 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
226 that normally would not qualify. If it returns t, the buffer
227 in question is treated as usable.
229 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
230 that would normally be considered usable. If it returns nil,
231 that buffer is rejected."
233 ;; 1. If one window on the selected frame displays such buffer, return it.
234 (let ((window-buffers
235 (delete-dups
236 (delq nil (mapcar (lambda (w)
237 (if (next-error-buffer-p
238 (window-buffer w)
239 avoid-current
240 extra-test-inclusive extra-test-exclusive)
241 (window-buffer w)))
242 (window-list))))))
243 (if (eq (length window-buffers) 1)
244 (car window-buffers)))
245 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
246 (if (and next-error-last-buffer
247 (next-error-buffer-p next-error-last-buffer avoid-current
248 extra-test-inclusive extra-test-exclusive))
249 next-error-last-buffer)
250 ;; 3. If the current buffer is acceptable, choose it.
251 (if (next-error-buffer-p (current-buffer) avoid-current
252 extra-test-inclusive extra-test-exclusive)
253 (current-buffer))
254 ;; 4. Look for any acceptable buffer.
255 (let ((buffers (buffer-list)))
256 (while (and buffers
257 (not (next-error-buffer-p
258 (car buffers) avoid-current
259 extra-test-inclusive extra-test-exclusive)))
260 (setq buffers (cdr buffers)))
261 (car buffers))
262 ;; 5. Use the current buffer as a last resort if it qualifies,
263 ;; even despite AVOID-CURRENT.
264 (and avoid-current
265 (next-error-buffer-p (current-buffer) nil
266 extra-test-inclusive extra-test-exclusive)
267 (progn
268 (message "This is the only buffer with error message locations")
269 (current-buffer)))
270 ;; 6. Give up.
271 (error "No buffers contain error message locations")))
273 (defun next-error (&optional arg reset)
274 "Visit next `next-error' message and corresponding source code.
276 If all the error messages parsed so far have been processed already,
277 the message buffer is checked for new ones.
279 A prefix ARG specifies how many error messages to move;
280 negative means move back to previous error messages.
281 Just \\[universal-argument] as a prefix means reparse the error message buffer
282 and start at the first error.
284 The RESET argument specifies that we should restart from the beginning.
286 \\[next-error] normally uses the most recently started
287 compilation, grep, or occur buffer. It can also operate on any
288 buffer with output from the \\[compile], \\[grep] commands, or,
289 more generally, on any buffer in Compilation mode or with
290 Compilation Minor mode enabled, or any buffer in which
291 `next-error-function' is bound to an appropriate function.
292 To specify use of a particular buffer for error messages, type
293 \\[next-error] in that buffer when it is the only one displayed
294 in the current frame.
296 Once \\[next-error] has chosen the buffer for error messages, it
297 runs `next-error-hook' with `run-hooks', and stays with that buffer
298 until you use it in some other buffer which uses Compilation mode
299 or Compilation Minor mode.
301 See variables `compilation-parse-errors-function' and
302 \`compilation-error-regexp-alist' for customization ideas."
303 (interactive "P")
304 (if (consp arg) (setq reset t arg nil))
305 (when (setq next-error-last-buffer (next-error-find-buffer))
306 ;; we know here that next-error-function is a valid symbol we can funcall
307 (with-current-buffer next-error-last-buffer
308 (funcall next-error-function (prefix-numeric-value arg) reset)
309 (run-hooks 'next-error-hook))))
311 (defun next-error-internal ()
312 "Visit the source code corresponding to the `next-error' message at point."
313 (setq next-error-last-buffer (current-buffer))
314 ;; we know here that next-error-function is a valid symbol we can funcall
315 (with-current-buffer next-error-last-buffer
316 (funcall next-error-function 0 nil)
317 (run-hooks 'next-error-hook)))
319 (defalias 'goto-next-locus 'next-error)
320 (defalias 'next-match 'next-error)
322 (defun previous-error (&optional n)
323 "Visit previous `next-error' message and corresponding source code.
325 Prefix arg N says how many error messages to move backwards (or
326 forwards, if negative).
328 This operates on the output from the \\[compile] and \\[grep] commands."
329 (interactive "p")
330 (next-error (- (or n 1))))
332 (defun first-error (&optional n)
333 "Restart at the first error.
334 Visit corresponding source code.
335 With prefix arg N, visit the source code of the Nth error.
336 This operates on the output from the \\[compile] command, for instance."
337 (interactive "p")
338 (next-error n t))
340 (defun next-error-no-select (&optional n)
341 "Move point to the next error in the `next-error' buffer and highlight match.
342 Prefix arg N says how many error messages to move forwards (or
343 backwards, if negative).
344 Finds and highlights the source line like \\[next-error], but does not
345 select the source buffer."
346 (interactive "p")
347 (let ((next-error-highlight next-error-highlight-no-select))
348 (next-error n))
349 (pop-to-buffer next-error-last-buffer))
351 (defun previous-error-no-select (&optional n)
352 "Move point to the previous error in the `next-error' buffer and highlight match.
353 Prefix arg N says how many error messages to move backwards (or
354 forwards, if negative).
355 Finds and highlights the source line like \\[previous-error], but does not
356 select the source buffer."
357 (interactive "p")
358 (next-error-no-select (- (or n 1))))
360 ;;; Internal variable for `next-error-follow-mode-post-command-hook'.
361 (defvar next-error-follow-last-line nil)
363 (define-minor-mode next-error-follow-minor-mode
364 "Minor mode for compilation, occur and diff modes.
365 When turned on, cursor motion in the compilation, grep, occur or diff
366 buffer causes automatic display of the corresponding source code
367 location."
368 :group 'next-error :init-value nil :lighter " Fol"
369 (if (not next-error-follow-minor-mode)
370 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
371 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
372 (make-local-variable 'next-error-follow-last-line)))
374 ;;; Used as a `post-command-hook' by `next-error-follow-mode'
375 ;;; for the *Compilation* *grep* and *Occur* buffers.
376 (defun next-error-follow-mode-post-command-hook ()
377 (unless (equal next-error-follow-last-line (line-number-at-pos))
378 (setq next-error-follow-last-line (line-number-at-pos))
379 (condition-case nil
380 (let ((compilation-context-lines nil))
381 (setq compilation-current-error (point))
382 (next-error-no-select 0))
383 (error t))))
388 (defun fundamental-mode ()
389 "Major mode not specialized for anything in particular.
390 Other major modes are defined by comparison with this one."
391 (interactive)
392 (kill-all-local-variables)
393 (unless delay-mode-hooks
394 (run-hooks 'after-change-major-mode-hook)))
396 ;; Making and deleting lines.
398 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard)))
400 (defun newline (&optional arg)
401 "Insert a newline, and move to left margin of the new line if it's blank.
402 If `use-hard-newlines' is non-nil, the newline is marked with the
403 text-property `hard'.
404 With ARG, insert that many newlines.
405 Call `auto-fill-function' if the current column number is greater
406 than the value of `fill-column' and ARG is nil."
407 (interactive "*P")
408 (barf-if-buffer-read-only)
409 ;; Inserting a newline at the end of a line produces better redisplay in
410 ;; try_window_id than inserting at the beginning of a line, and the textual
411 ;; result is the same. So, if we're at beginning of line, pretend to be at
412 ;; the end of the previous line.
413 (let ((flag (and (not (bobp))
414 (bolp)
415 ;; Make sure no functions want to be told about
416 ;; the range of the changes.
417 (not after-change-functions)
418 (not before-change-functions)
419 ;; Make sure there are no markers here.
420 (not (buffer-has-markers-at (1- (point))))
421 (not (buffer-has-markers-at (point)))
422 ;; Make sure no text properties want to know
423 ;; where the change was.
424 (not (get-char-property (1- (point)) 'modification-hooks))
425 (not (get-char-property (1- (point)) 'insert-behind-hooks))
426 (or (eobp)
427 (not (get-char-property (point) 'insert-in-front-hooks)))
428 ;; Make sure the newline before point isn't intangible.
429 (not (get-char-property (1- (point)) 'intangible))
430 ;; Make sure the newline before point isn't read-only.
431 (not (get-char-property (1- (point)) 'read-only))
432 ;; Make sure the newline before point isn't invisible.
433 (not (get-char-property (1- (point)) 'invisible))
434 ;; Make sure the newline before point has the same
435 ;; properties as the char before it (if any).
436 (< (or (previous-property-change (point)) -2)
437 (- (point) 2))))
438 (was-page-start (and (bolp)
439 (looking-at page-delimiter)))
440 (beforepos (point)))
441 (if flag (backward-char 1))
442 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
443 ;; Set last-command-char to tell self-insert what to insert.
444 (let ((last-command-char ?\n)
445 ;; Don't auto-fill if we have a numeric argument.
446 ;; Also not if flag is true (it would fill wrong line);
447 ;; there is no need to since we're at BOL.
448 (auto-fill-function (if (or arg flag) nil auto-fill-function)))
449 (unwind-protect
450 (self-insert-command (prefix-numeric-value arg))
451 ;; If we get an error in self-insert-command, put point at right place.
452 (if flag (forward-char 1))))
453 ;; Even if we did *not* get an error, keep that forward-char;
454 ;; all further processing should apply to the newline that the user
455 ;; thinks he inserted.
457 ;; Mark the newline(s) `hard'.
458 (if use-hard-newlines
459 (set-hard-newline-properties
460 (- (point) (if arg (prefix-numeric-value arg) 1)) (point)))
461 ;; If the newline leaves the previous line blank,
462 ;; and we have a left margin, delete that from the blank line.
463 (or flag
464 (save-excursion
465 (goto-char beforepos)
466 (beginning-of-line)
467 (and (looking-at "[ \t]$")
468 (> (current-left-margin) 0)
469 (delete-region (point) (progn (end-of-line) (point))))))
470 ;; Indent the line after the newline, except in one case:
471 ;; when we added the newline at the beginning of a line
472 ;; which starts a page.
473 (or was-page-start
474 (move-to-left-margin nil t)))
475 nil)
477 (defun set-hard-newline-properties (from to)
478 (let ((sticky (get-text-property from 'rear-nonsticky)))
479 (put-text-property from to 'hard 't)
480 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
481 (if (and (listp sticky) (not (memq 'hard sticky)))
482 (put-text-property from (point) 'rear-nonsticky
483 (cons 'hard sticky)))))
485 (defun open-line (n)
486 "Insert a newline and leave point before it.
487 If there is a fill prefix and/or a `left-margin', insert them
488 on the new line if the line would have been blank.
489 With arg N, insert N newlines."
490 (interactive "*p")
491 (let* ((do-fill-prefix (and fill-prefix (bolp)))
492 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
493 (loc (point))
494 ;; Don't expand an abbrev before point.
495 (abbrev-mode nil))
496 (newline n)
497 (goto-char loc)
498 (while (> n 0)
499 (cond ((bolp)
500 (if do-left-margin (indent-to (current-left-margin)))
501 (if do-fill-prefix (insert-and-inherit fill-prefix))))
502 (forward-line 1)
503 (setq n (1- n)))
504 (goto-char loc)
505 (end-of-line)))
507 (defun split-line (&optional arg)
508 "Split current line, moving portion beyond point vertically down.
509 If the current line starts with `fill-prefix', insert it on the new
510 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
512 When called from Lisp code, ARG may be a prefix string to copy."
513 (interactive "*P")
514 (skip-chars-forward " \t")
515 (let* ((col (current-column))
516 (pos (point))
517 ;; What prefix should we check for (nil means don't).
518 (prefix (cond ((stringp arg) arg)
519 (arg nil)
520 (t fill-prefix)))
521 ;; Does this line start with it?
522 (have-prfx (and prefix
523 (save-excursion
524 (beginning-of-line)
525 (looking-at (regexp-quote prefix))))))
526 (newline 1)
527 (if have-prfx (insert-and-inherit prefix))
528 (indent-to col 0)
529 (goto-char pos)))
531 (defun delete-indentation (&optional arg)
532 "Join this line to previous and fix up whitespace at join.
533 If there is a fill prefix, delete it from the beginning of this line.
534 With argument, join this line to following line."
535 (interactive "*P")
536 (beginning-of-line)
537 (if arg (forward-line 1))
538 (if (eq (preceding-char) ?\n)
539 (progn
540 (delete-region (point) (1- (point)))
541 ;; If the second line started with the fill prefix,
542 ;; delete the prefix.
543 (if (and fill-prefix
544 (<= (+ (point) (length fill-prefix)) (point-max))
545 (string= fill-prefix
546 (buffer-substring (point)
547 (+ (point) (length fill-prefix)))))
548 (delete-region (point) (+ (point) (length fill-prefix))))
549 (fixup-whitespace))))
551 (defalias 'join-line #'delete-indentation) ; easier to find
553 (defun delete-blank-lines ()
554 "On blank line, delete all surrounding blank lines, leaving just one.
555 On isolated blank line, delete that one.
556 On nonblank line, delete any immediately following blank lines."
557 (interactive "*")
558 (let (thisblank singleblank)
559 (save-excursion
560 (beginning-of-line)
561 (setq thisblank (looking-at "[ \t]*$"))
562 ;; Set singleblank if there is just one blank line here.
563 (setq singleblank
564 (and thisblank
565 (not (looking-at "[ \t]*\n[ \t]*$"))
566 (or (bobp)
567 (progn (forward-line -1)
568 (not (looking-at "[ \t]*$")))))))
569 ;; Delete preceding blank lines, and this one too if it's the only one.
570 (if thisblank
571 (progn
572 (beginning-of-line)
573 (if singleblank (forward-line 1))
574 (delete-region (point)
575 (if (re-search-backward "[^ \t\n]" nil t)
576 (progn (forward-line 1) (point))
577 (point-min)))))
578 ;; Delete following blank lines, unless the current line is blank
579 ;; and there are no following blank lines.
580 (if (not (and thisblank singleblank))
581 (save-excursion
582 (end-of-line)
583 (forward-line 1)
584 (delete-region (point)
585 (if (re-search-forward "[^ \t\n]" nil t)
586 (progn (beginning-of-line) (point))
587 (point-max)))))
588 ;; Handle the special case where point is followed by newline and eob.
589 ;; Delete the line, leaving point at eob.
590 (if (looking-at "^[ \t]*\n\\'")
591 (delete-region (point) (point-max)))))
593 (defun delete-trailing-whitespace ()
594 "Delete all the trailing whitespace across the current buffer.
595 All whitespace after the last non-whitespace character in a line is deleted.
596 This respects narrowing, created by \\[narrow-to-region] and friends.
597 A formfeed is not considered whitespace by this function."
598 (interactive "*")
599 (save-match-data
600 (save-excursion
601 (goto-char (point-min))
602 (while (re-search-forward "\\s-$" nil t)
603 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
604 ;; Don't delete formfeeds, even if they are considered whitespace.
605 (save-match-data
606 (if (looking-at ".*\f")
607 (goto-char (match-end 0))))
608 (delete-region (point) (match-end 0))))))
610 (defun newline-and-indent ()
611 "Insert a newline, then indent according to major mode.
612 Indentation is done using the value of `indent-line-function'.
613 In programming language modes, this is the same as TAB.
614 In some text modes, where TAB inserts a tab, this command indents to the
615 column specified by the function `current-left-margin'."
616 (interactive "*")
617 (delete-horizontal-space t)
618 (newline)
619 (indent-according-to-mode))
621 (defun reindent-then-newline-and-indent ()
622 "Reindent current line, insert newline, then indent the new line.
623 Indentation of both lines is done according to the current major mode,
624 which means calling the current value of `indent-line-function'.
625 In programming language modes, this is the same as TAB.
626 In some text modes, where TAB inserts a tab, this indents to the
627 column specified by the function `current-left-margin'."
628 (interactive "*")
629 (let ((pos (point)))
630 ;; Be careful to insert the newline before indenting the line.
631 ;; Otherwise, the indentation might be wrong.
632 (newline)
633 (save-excursion
634 (goto-char pos)
635 ;; Usually indent-according-to-mode should "preserve" point, but it is
636 ;; not guaranteed; e.g. indent-to-left-margin doesn't.
637 (save-excursion (indent-according-to-mode))
638 (delete-horizontal-space t))
639 (indent-according-to-mode)))
641 (defun quoted-insert (arg)
642 "Read next input character and insert it.
643 This is useful for inserting control characters.
645 If the first character you type after this command is an octal digit,
646 you should type a sequence of octal digits which specify a character code.
647 Any nondigit terminates the sequence. If the terminator is a RET,
648 it is discarded; any other terminator is used itself as input.
649 The variable `read-quoted-char-radix' specifies the radix for this feature;
650 set it to 10 or 16 to use decimal or hex instead of octal.
652 In overwrite mode, this function inserts the character anyway, and
653 does not handle octal digits specially. This means that if you use
654 overwrite as your normal editing mode, you can use this function to
655 insert characters when necessary.
657 In binary overwrite mode, this function does overwrite, and octal
658 digits are interpreted as a character code. This is intended to be
659 useful for editing binary files."
660 (interactive "*p")
661 (let* ((char (let (translation-table-for-input input-method-function)
662 (if (or (not overwrite-mode)
663 (eq overwrite-mode 'overwrite-mode-binary))
664 (read-quoted-char)
665 (read-char)))))
666 ;; Assume character codes 0240 - 0377 stand for characters in some
667 ;; single-byte character set, and convert them to Emacs
668 ;; characters.
669 (if (and enable-multibyte-characters
670 (>= char ?\240)
671 (<= char ?\377))
672 (setq char (unibyte-char-to-multibyte char)))
673 (if (> arg 0)
674 (if (eq overwrite-mode 'overwrite-mode-binary)
675 (delete-char arg)))
676 (while (> arg 0)
677 (insert-and-inherit char)
678 (setq arg (1- arg)))))
680 (defun forward-to-indentation (&optional arg)
681 "Move forward ARG lines and position at first nonblank character."
682 (interactive "p")
683 (forward-line (or arg 1))
684 (skip-chars-forward " \t"))
686 (defun backward-to-indentation (&optional arg)
687 "Move backward ARG lines and position at first nonblank character."
688 (interactive "p")
689 (forward-line (- (or arg 1)))
690 (skip-chars-forward " \t"))
692 (defun back-to-indentation ()
693 "Move point to the first non-whitespace character on this line."
694 (interactive)
695 (beginning-of-line 1)
696 (skip-syntax-forward " " (line-end-position))
697 ;; Move back over chars that have whitespace syntax but have the p flag.
698 (backward-prefix-chars))
700 (defun fixup-whitespace ()
701 "Fixup white space between objects around point.
702 Leave one space or none, according to the context."
703 (interactive "*")
704 (save-excursion
705 (delete-horizontal-space)
706 (if (or (looking-at "^\\|\\s)")
707 (save-excursion (forward-char -1)
708 (looking-at "$\\|\\s(\\|\\s'")))
710 (insert ?\s))))
712 (defun delete-horizontal-space (&optional backward-only)
713 "Delete all spaces and tabs around point.
714 If BACKWARD-ONLY is non-nil, only delete them before point."
715 (interactive "*P")
716 (let ((orig-pos (point)))
717 (delete-region
718 (if backward-only
719 orig-pos
720 (progn
721 (skip-chars-forward " \t")
722 (constrain-to-field nil orig-pos t)))
723 (progn
724 (skip-chars-backward " \t")
725 (constrain-to-field nil orig-pos)))))
727 (defun just-one-space (&optional n)
728 "Delete all spaces and tabs around point, leaving one space (or N spaces)."
729 (interactive "*p")
730 (let ((orig-pos (point)))
731 (skip-chars-backward " \t")
732 (constrain-to-field nil orig-pos)
733 (dotimes (i (or n 1))
734 (if (= (following-char) ?\s)
735 (forward-char 1)
736 (insert ?\s)))
737 (delete-region
738 (point)
739 (progn
740 (skip-chars-forward " \t")
741 (constrain-to-field nil orig-pos t)))))
743 (defun beginning-of-buffer (&optional arg)
744 "Move point to the beginning of the buffer; leave mark at previous position.
745 With \\[universal-argument] prefix, do not set mark at previous position.
746 With numeric arg N, put point N/10 of the way from the beginning.
748 If the buffer is narrowed, this command uses the beginning and size
749 of the accessible part of the buffer.
751 Don't use this command in Lisp programs!
752 \(goto-char (point-min)) is faster and avoids clobbering the mark."
753 (interactive "P")
754 (or (consp arg)
755 (and transient-mark-mode mark-active)
756 (push-mark))
757 (let ((size (- (point-max) (point-min))))
758 (goto-char (if (and arg (not (consp arg)))
759 (+ (point-min)
760 (if (> size 10000)
761 ;; Avoid overflow for large buffer sizes!
762 (* (prefix-numeric-value arg)
763 (/ size 10))
764 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
765 (point-min))))
766 (if (and arg (not (consp arg))) (forward-line 1)))
768 (defun end-of-buffer (&optional arg)
769 "Move point to the end of the buffer; leave mark at previous position.
770 With \\[universal-argument] prefix, do not set mark at previous position.
771 With numeric arg N, put point N/10 of the way from the end.
773 If the buffer is narrowed, this command uses the beginning and size
774 of the accessible part of the buffer.
776 Don't use this command in Lisp programs!
777 \(goto-char (point-max)) is faster and avoids clobbering the mark."
778 (interactive "P")
779 (or (consp arg)
780 (and transient-mark-mode mark-active)
781 (push-mark))
782 (let ((size (- (point-max) (point-min))))
783 (goto-char (if (and arg (not (consp arg)))
784 (- (point-max)
785 (if (> size 10000)
786 ;; Avoid overflow for large buffer sizes!
787 (* (prefix-numeric-value arg)
788 (/ size 10))
789 (/ (* size (prefix-numeric-value arg)) 10)))
790 (point-max))))
791 ;; If we went to a place in the middle of the buffer,
792 ;; adjust it to the beginning of a line.
793 (cond ((and arg (not (consp arg))) (forward-line 1))
794 ((> (point) (window-end nil t))
795 ;; If the end of the buffer is not already on the screen,
796 ;; then scroll specially to put it near, but not at, the bottom.
797 (overlay-recenter (point))
798 (recenter -3))))
800 (defun mark-whole-buffer ()
801 "Put point at beginning and mark at end of buffer.
802 You probably should not use this function in Lisp programs;
803 it is usually a mistake for a Lisp function to use any subroutine
804 that uses or sets the mark."
805 (interactive)
806 (push-mark (point))
807 (push-mark (point-max) nil t)
808 (goto-char (point-min)))
811 ;; Counting lines, one way or another.
813 (defun goto-line (arg &optional buffer)
814 "Goto line ARG, counting from line 1 at beginning of buffer.
815 Normally, move point in the current buffer.
816 With just \\[universal-argument] as argument, move point in the most recently
817 displayed other buffer, and switch to it. When called from Lisp code,
818 the optional argument BUFFER specifies a buffer to switch to.
820 If there's a number in the buffer at point, it is the default for ARG."
821 (interactive
822 (if (and current-prefix-arg (not (consp current-prefix-arg)))
823 (list (prefix-numeric-value current-prefix-arg))
824 ;; Look for a default, a number in the buffer at point.
825 (let* ((default
826 (save-excursion
827 (skip-chars-backward "0-9")
828 (if (looking-at "[0-9]")
829 (buffer-substring-no-properties
830 (point)
831 (progn (skip-chars-forward "0-9")
832 (point))))))
833 ;; Decide if we're switching buffers.
834 (buffer
835 (if (consp current-prefix-arg)
836 (other-buffer (current-buffer) t)))
837 (buffer-prompt
838 (if buffer
839 (concat " in " (buffer-name buffer))
840 "")))
841 ;; Read the argument, offering that number (if any) as default.
842 (list (read-from-minibuffer (format (if default "Goto line%s (%s): "
843 "Goto line%s: ")
844 buffer-prompt
845 default)
846 nil nil t
847 'minibuffer-history
848 default)
849 buffer))))
850 ;; Switch to the desired buffer, one way or another.
851 (if buffer
852 (let ((window (get-buffer-window buffer)))
853 (if window (select-window window)
854 (switch-to-buffer-other-window buffer))))
855 ;; Move to the specified line number in that buffer.
856 (save-restriction
857 (widen)
858 (goto-char 1)
859 (if (eq selective-display t)
860 (re-search-forward "[\n\C-m]" nil 'end (1- arg))
861 (forward-line (1- arg)))))
863 (defun count-lines-region (start end)
864 "Print number of lines and characters in the region."
865 (interactive "r")
866 (message "Region has %d lines, %d characters"
867 (count-lines start end) (- end start)))
869 (defun what-line ()
870 "Print the current buffer line number and narrowed line number of point."
871 (interactive)
872 (let ((start (point-min))
873 (n (line-number-at-pos)))
874 (if (= start 1)
875 (message "Line %d" n)
876 (save-excursion
877 (save-restriction
878 (widen)
879 (message "line %d (narrowed line %d)"
880 (+ n (line-number-at-pos start) -1) n))))))
882 (defun count-lines (start end)
883 "Return number of lines between START and END.
884 This is usually the number of newlines between them,
885 but can be one more if START is not equal to END
886 and the greater of them is not at the start of a line."
887 (save-excursion
888 (save-restriction
889 (narrow-to-region start end)
890 (goto-char (point-min))
891 (if (eq selective-display t)
892 (save-match-data
893 (let ((done 0))
894 (while (re-search-forward "[\n\C-m]" nil t 40)
895 (setq done (+ 40 done)))
896 (while (re-search-forward "[\n\C-m]" nil t 1)
897 (setq done (+ 1 done)))
898 (goto-char (point-max))
899 (if (and (/= start end)
900 (not (bolp)))
901 (1+ done)
902 done)))
903 (- (buffer-size) (forward-line (buffer-size)))))))
905 (defun line-number-at-pos (&optional pos)
906 "Return (narrowed) buffer line number at position POS.
907 If POS is nil, use current buffer location.
908 Counting starts at (point-min), so the value refers
909 to the contents of the accessible portion of the buffer."
910 (let ((opoint (or pos (point))) start)
911 (save-excursion
912 (goto-char (point-min))
913 (setq start (point))
914 (goto-char opoint)
915 (forward-line 0)
916 (1+ (count-lines start (point))))))
918 (defun what-cursor-position (&optional detail)
919 "Print info on cursor position (on screen and within buffer).
920 Also describe the character after point, and give its character code
921 in octal, decimal and hex.
923 For a non-ASCII multibyte character, also give its encoding in the
924 buffer's selected coding system if the coding system encodes the
925 character safely. If the character is encoded into one byte, that
926 code is shown in hex. If the character is encoded into more than one
927 byte, just \"...\" is shown.
929 In addition, with prefix argument, show details about that character
930 in *Help* buffer. See also the command `describe-char'."
931 (interactive "P")
932 (let* ((char (following-char))
933 (beg (point-min))
934 (end (point-max))
935 (pos (point))
936 (total (buffer-size))
937 (percent (if (> total 50000)
938 ;; Avoid overflow from multiplying by 100!
939 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
940 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
941 (hscroll (if (= (window-hscroll) 0)
943 (format " Hscroll=%d" (window-hscroll))))
944 (col (current-column)))
945 (if (= pos end)
946 (if (or (/= beg 1) (/= end (1+ total)))
947 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
948 pos total percent beg end col hscroll)
949 (message "point=%d of %d (EOB) column=%d%s"
950 pos total col hscroll))
951 (let ((coding buffer-file-coding-system)
952 encoded encoding-msg display-prop under-display)
953 (if (or (not coding)
954 (eq (coding-system-type coding) t))
955 (setq coding default-buffer-file-coding-system))
956 (if (not (char-valid-p char))
957 (setq encoding-msg
958 (format "(%d, #o%o, #x%x, invalid)" char char char))
959 ;; Check if the character is displayed with some `display'
960 ;; text property. In that case, set under-display to the
961 ;; buffer substring covered by that property.
962 (setq display-prop (get-text-property pos 'display))
963 (if display-prop
964 (let ((to (or (next-single-property-change pos 'display)
965 (point-max))))
966 (if (< to (+ pos 4))
967 (setq under-display "")
968 (setq under-display "..."
969 to (+ pos 4)))
970 (setq under-display
971 (concat (buffer-substring-no-properties pos to)
972 under-display)))
973 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
974 (setq encoding-msg
975 (if display-prop
976 (if (not (stringp display-prop))
977 (format "(%d, #o%o, #x%x, part of display \"%s\")"
978 char char char under-display)
979 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
980 char char char under-display display-prop))
981 (if encoded
982 (format "(%d, #o%o, #x%x, file %s)"
983 char char char
984 (if (> (length encoded) 1)
985 "..."
986 (encoded-string-description encoded coding)))
987 (format "(%d, #o%o, #x%x)" char char char)))))
988 (if detail
989 ;; We show the detailed information about CHAR.
990 (describe-char (point)))
991 (if (or (/= beg 1) (/= end (1+ total)))
992 (message "Char: %s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
993 (if (< char 256)
994 (single-key-description char)
995 (buffer-substring-no-properties (point) (1+ (point))))
996 encoding-msg pos total percent beg end col hscroll)
997 (message "Char: %s %s point=%d of %d (%d%%) column=%d%s"
998 (if enable-multibyte-characters
999 (if (< char 128)
1000 (single-key-description char)
1001 (buffer-substring-no-properties (point) (1+ (point))))
1002 (single-key-description char))
1003 encoding-msg pos total percent col hscroll))))))
1005 ;; Initialize read-expression-map. It is defined at C level.
1006 (let ((m (make-sparse-keymap)))
1007 (define-key m "\M-\t" 'lisp-complete-symbol)
1008 (set-keymap-parent m minibuffer-local-map)
1009 (setq read-expression-map m))
1011 (defvar read-expression-history nil)
1013 (defvar minibuffer-completing-symbol nil
1014 "Non-nil means completing a Lisp symbol in the minibuffer.")
1016 (defcustom eval-expression-print-level 4
1017 "Value for `print-level' while printing value in `eval-expression'.
1018 A value of nil means no limit."
1019 :group 'lisp
1020 :type '(choice (const :tag "No Limit" nil) integer)
1021 :version "21.1")
1023 (defcustom eval-expression-print-length 12
1024 "Value for `print-length' while printing value in `eval-expression'.
1025 A value of nil means no limit."
1026 :group 'lisp
1027 :type '(choice (const :tag "No Limit" nil) integer)
1028 :version "21.1")
1030 (defcustom eval-expression-debug-on-error t
1031 "If non-nil set `debug-on-error' to t in `eval-expression'.
1032 If nil, don't change the value of `debug-on-error'."
1033 :group 'lisp
1034 :type 'boolean
1035 :version "21.1")
1037 (defun eval-expression-print-format (value)
1038 "Format VALUE as a result of evaluated expression.
1039 Return a formatted string which is displayed in the echo area
1040 in addition to the value printed by prin1 in functions which
1041 display the result of expression evaluation."
1042 (if (and (integerp value)
1043 (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1044 (eq this-command last-command)
1045 (if (boundp 'edebug-active) edebug-active)))
1046 (let ((char-string
1047 (if (or (if (boundp 'edebug-active) edebug-active)
1048 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1049 (prin1-char value))))
1050 (if char-string
1051 (format " (#o%o, #x%x, %s)" value value char-string)
1052 (format " (#o%o, #x%x)" value value)))))
1054 ;; We define this, rather than making `eval' interactive,
1055 ;; for the sake of completion of names like eval-region, eval-buffer.
1056 (defun eval-expression (eval-expression-arg
1057 &optional eval-expression-insert-value)
1058 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
1059 Value is also consed on to front of the variable `values'.
1060 Optional argument EVAL-EXPRESSION-INSERT-VALUE, if non-nil, means
1061 insert the result into the current buffer instead of printing it in
1062 the echo area.
1064 If `eval-expression-debug-on-error' is non-nil, which is the default,
1065 this command arranges for all errors to enter the debugger."
1066 (interactive
1067 (list (let ((minibuffer-completing-symbol t))
1068 (read-from-minibuffer "Eval: "
1069 nil read-expression-map t
1070 'read-expression-history))
1071 current-prefix-arg))
1073 (if (null eval-expression-debug-on-error)
1074 (setq values (cons (eval eval-expression-arg) values))
1075 (let ((old-value (make-symbol "t")) new-value)
1076 ;; Bind debug-on-error to something unique so that we can
1077 ;; detect when evaled code changes it.
1078 (let ((debug-on-error old-value))
1079 (setq values (cons (eval eval-expression-arg) values))
1080 (setq new-value debug-on-error))
1081 ;; If evaled code has changed the value of debug-on-error,
1082 ;; propagate that change to the global binding.
1083 (unless (eq old-value new-value)
1084 (setq debug-on-error new-value))))
1086 (let ((print-length eval-expression-print-length)
1087 (print-level eval-expression-print-level))
1088 (if eval-expression-insert-value
1089 (with-no-warnings
1090 (let ((standard-output (current-buffer)))
1091 (prin1 (car values))))
1092 (prog1
1093 (prin1 (car values) t)
1094 (let ((str (eval-expression-print-format (car values))))
1095 (if str (princ str t)))))))
1097 (defun edit-and-eval-command (prompt command)
1098 "Prompting with PROMPT, let user edit COMMAND and eval result.
1099 COMMAND is a Lisp expression. Let user edit that expression in
1100 the minibuffer, then read and evaluate the result."
1101 (let ((command
1102 (let ((print-level nil)
1103 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1104 (unwind-protect
1105 (read-from-minibuffer prompt
1106 (prin1-to-string command)
1107 read-expression-map t
1108 'command-history)
1109 ;; If command was added to command-history as a string,
1110 ;; get rid of that. We want only evaluable expressions there.
1111 (if (stringp (car command-history))
1112 (setq command-history (cdr command-history)))))))
1114 ;; If command to be redone does not match front of history,
1115 ;; add it to the history.
1116 (or (equal command (car command-history))
1117 (setq command-history (cons command command-history)))
1118 (eval command)))
1120 (defun repeat-complex-command (arg)
1121 "Edit and re-evaluate last complex command, or ARGth from last.
1122 A complex command is one which used the minibuffer.
1123 The command is placed in the minibuffer as a Lisp form for editing.
1124 The result is executed, repeating the command as changed.
1125 If the command has been changed or is not the most recent previous command
1126 it is added to the front of the command history.
1127 You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1128 to get different commands to edit and resubmit."
1129 (interactive "p")
1130 (let ((elt (nth (1- arg) command-history))
1131 newcmd)
1132 (if elt
1133 (progn
1134 (setq newcmd
1135 (let ((print-level nil)
1136 (minibuffer-history-position arg)
1137 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1138 (unwind-protect
1139 (read-from-minibuffer
1140 "Redo: " (prin1-to-string elt) read-expression-map t
1141 (cons 'command-history arg))
1143 ;; If command was added to command-history as a
1144 ;; string, get rid of that. We want only
1145 ;; evaluable expressions there.
1146 (if (stringp (car command-history))
1147 (setq command-history (cdr command-history))))))
1149 ;; If command to be redone does not match front of history,
1150 ;; add it to the history.
1151 (or (equal newcmd (car command-history))
1152 (setq command-history (cons newcmd command-history)))
1153 (eval newcmd))
1154 (if command-history
1155 (error "Argument %d is beyond length of command history" arg)
1156 (error "There are no previous complex commands to repeat")))))
1158 (defvar minibuffer-history nil
1159 "Default minibuffer history list.
1160 This is used for all minibuffer input
1161 except when an alternate history list is specified.
1163 Maximum length of the history list is determined by the value
1164 of `history-length', which see.")
1165 (defvar minibuffer-history-sexp-flag nil
1166 "Control whether history list elements are expressions or strings.
1167 If the value of this variable equals current minibuffer depth,
1168 they are expressions; otherwise they are strings.
1169 \(That convention is designed to do the right thing for
1170 recursive uses of the minibuffer.)")
1171 (setq minibuffer-history-variable 'minibuffer-history)
1172 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1173 (defvar minibuffer-history-search-history nil)
1175 (defvar minibuffer-text-before-history nil
1176 "Text that was in this minibuffer before any history commands.
1177 This is nil if there have not yet been any history commands
1178 in this use of the minibuffer.")
1180 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1182 (defun minibuffer-history-initialize ()
1183 (setq minibuffer-text-before-history nil))
1185 (defun minibuffer-avoid-prompt (new old)
1186 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1187 (constrain-to-field nil (point-max)))
1189 (defcustom minibuffer-history-case-insensitive-variables nil
1190 "*Minibuffer history variables for which matching should ignore case.
1191 If a history variable is a member of this list, then the
1192 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1193 commands ignore case when searching it, regardless of `case-fold-search'."
1194 :type '(repeat variable)
1195 :group 'minibuffer)
1197 (defun previous-matching-history-element (regexp n)
1198 "Find the previous history element that matches REGEXP.
1199 \(Previous history elements refer to earlier actions.)
1200 With prefix argument N, search for Nth previous match.
1201 If N is negative, find the next or Nth next match.
1202 Normally, history elements are matched case-insensitively if
1203 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1204 makes the search case-sensitive.
1205 See also `minibuffer-history-case-insensitive-variables'."
1206 (interactive
1207 (let* ((enable-recursive-minibuffers t)
1208 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1210 minibuffer-local-map
1212 'minibuffer-history-search-history
1213 (car minibuffer-history-search-history))))
1214 ;; Use the last regexp specified, by default, if input is empty.
1215 (list (if (string= regexp "")
1216 (if minibuffer-history-search-history
1217 (car minibuffer-history-search-history)
1218 (error "No previous history search regexp"))
1219 regexp)
1220 (prefix-numeric-value current-prefix-arg))))
1221 (unless (zerop n)
1222 (if (and (zerop minibuffer-history-position)
1223 (null minibuffer-text-before-history))
1224 (setq minibuffer-text-before-history
1225 (minibuffer-contents-no-properties)))
1226 (let ((history (symbol-value minibuffer-history-variable))
1227 (case-fold-search
1228 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1229 ;; On some systems, ignore case for file names.
1230 (if (memq minibuffer-history-variable
1231 minibuffer-history-case-insensitive-variables)
1233 ;; Respect the user's setting for case-fold-search:
1234 case-fold-search)
1235 nil))
1236 prevpos
1237 match-string
1238 match-offset
1239 (pos minibuffer-history-position))
1240 (while (/= n 0)
1241 (setq prevpos pos)
1242 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1243 (when (= pos prevpos)
1244 (error (if (= pos 1)
1245 "No later matching history item"
1246 "No earlier matching history item")))
1247 (setq match-string
1248 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1249 (let ((print-level nil))
1250 (prin1-to-string (nth (1- pos) history)))
1251 (nth (1- pos) history)))
1252 (setq match-offset
1253 (if (< n 0)
1254 (and (string-match regexp match-string)
1255 (match-end 0))
1256 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1257 (match-beginning 1))))
1258 (when match-offset
1259 (setq n (+ n (if (< n 0) 1 -1)))))
1260 (setq minibuffer-history-position pos)
1261 (goto-char (point-max))
1262 (delete-minibuffer-contents)
1263 (insert match-string)
1264 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1265 (if (memq (car (car command-history)) '(previous-matching-history-element
1266 next-matching-history-element))
1267 (setq command-history (cdr command-history))))
1269 (defun next-matching-history-element (regexp n)
1270 "Find the next history element that matches REGEXP.
1271 \(The next history element refers to a more recent action.)
1272 With prefix argument N, search for Nth next match.
1273 If N is negative, find the previous or Nth previous match.
1274 Normally, history elements are matched case-insensitively if
1275 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1276 makes the search case-sensitive."
1277 (interactive
1278 (let* ((enable-recursive-minibuffers t)
1279 (regexp (read-from-minibuffer "Next element matching (regexp): "
1281 minibuffer-local-map
1283 'minibuffer-history-search-history
1284 (car minibuffer-history-search-history))))
1285 ;; Use the last regexp specified, by default, if input is empty.
1286 (list (if (string= regexp "")
1287 (if minibuffer-history-search-history
1288 (car minibuffer-history-search-history)
1289 (error "No previous history search regexp"))
1290 regexp)
1291 (prefix-numeric-value current-prefix-arg))))
1292 (previous-matching-history-element regexp (- n)))
1294 (defvar minibuffer-temporary-goal-position nil)
1296 (defun next-history-element (n)
1297 "Puts next element of the minibuffer history in the minibuffer.
1298 With argument N, it uses the Nth following element."
1299 (interactive "p")
1300 (or (zerop n)
1301 (let ((narg (- minibuffer-history-position n))
1302 (minimum (if minibuffer-default -1 0))
1303 elt minibuffer-returned-to-present)
1304 (if (and (zerop minibuffer-history-position)
1305 (null minibuffer-text-before-history))
1306 (setq minibuffer-text-before-history
1307 (minibuffer-contents-no-properties)))
1308 (if (< narg minimum)
1309 (if minibuffer-default
1310 (error "End of history; no next item")
1311 (error "End of history; no default available")))
1312 (if (> narg (length (symbol-value minibuffer-history-variable)))
1313 (error "Beginning of history; no preceding item"))
1314 (unless (memq last-command '(next-history-element
1315 previous-history-element))
1316 (let ((prompt-end (minibuffer-prompt-end)))
1317 (set (make-local-variable 'minibuffer-temporary-goal-position)
1318 (cond ((<= (point) prompt-end) prompt-end)
1319 ((eobp) nil)
1320 (t (point))))))
1321 (goto-char (point-max))
1322 (delete-minibuffer-contents)
1323 (setq minibuffer-history-position narg)
1324 (cond ((= narg -1)
1325 (setq elt minibuffer-default))
1326 ((= narg 0)
1327 (setq elt (or minibuffer-text-before-history ""))
1328 (setq minibuffer-returned-to-present t)
1329 (setq minibuffer-text-before-history nil))
1330 (t (setq elt (nth (1- minibuffer-history-position)
1331 (symbol-value minibuffer-history-variable)))))
1332 (insert
1333 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1334 (not minibuffer-returned-to-present))
1335 (let ((print-level nil))
1336 (prin1-to-string elt))
1337 elt))
1338 (goto-char (or minibuffer-temporary-goal-position (point-max))))))
1340 (defun previous-history-element (n)
1341 "Puts previous element of the minibuffer history in the minibuffer.
1342 With argument N, it uses the Nth previous element."
1343 (interactive "p")
1344 (next-history-element (- n)))
1346 (defun next-complete-history-element (n)
1347 "Get next history element which completes the minibuffer before the point.
1348 The contents of the minibuffer after the point are deleted, and replaced
1349 by the new completion."
1350 (interactive "p")
1351 (let ((point-at-start (point)))
1352 (next-matching-history-element
1353 (concat
1354 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1356 ;; next-matching-history-element always puts us at (point-min).
1357 ;; Move to the position we were at before changing the buffer contents.
1358 ;; This is still sensical, because the text before point has not changed.
1359 (goto-char point-at-start)))
1361 (defun previous-complete-history-element (n)
1363 Get previous history element which completes the minibuffer before the point.
1364 The contents of the minibuffer after the point are deleted, and replaced
1365 by the new completion."
1366 (interactive "p")
1367 (next-complete-history-element (- n)))
1369 ;; For compatibility with the old subr of the same name.
1370 (defun minibuffer-prompt-width ()
1371 "Return the display width of the minibuffer prompt.
1372 Return 0 if current buffer is not a minibuffer."
1373 ;; Return the width of everything before the field at the end of
1374 ;; the buffer; this should be 0 for normal buffers.
1375 (1- (minibuffer-prompt-end)))
1377 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1378 (defalias 'advertised-undo 'undo)
1380 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
1381 "Table mapping redo records to the corresponding undo one.
1382 A redo record for undo-in-region maps to t.
1383 A redo record for ordinary undo maps to the following (earlier) undo.")
1385 (defvar undo-in-region nil
1386 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1388 (defvar undo-no-redo nil
1389 "If t, `undo' doesn't go through redo entries.")
1391 (defvar pending-undo-list nil
1392 "Within a run of consecutive undo commands, list remaining to be undone.
1393 If t, we undid all the way to the end of it.")
1395 (defun undo (&optional arg)
1396 "Undo some previous changes.
1397 Repeat this command to undo more changes.
1398 A numeric argument serves as a repeat count.
1400 In Transient Mark mode when the mark is active, only undo changes within
1401 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1402 as an argument limits undo to changes within the current region."
1403 (interactive "*P")
1404 ;; Make last-command indicate for the next command that this was an undo.
1405 ;; That way, another undo will undo more.
1406 ;; If we get to the end of the undo history and get an error,
1407 ;; another undo command will find the undo history empty
1408 ;; and will get another error. To begin undoing the undos,
1409 ;; you must type some other command.
1410 (let ((modified (buffer-modified-p))
1411 (recent-save (recent-auto-save-p))
1412 message)
1413 ;; If we get an error in undo-start,
1414 ;; the next command should not be a "consecutive undo".
1415 ;; So set `this-command' to something other than `undo'.
1416 (setq this-command 'undo-start)
1418 (unless (and (eq last-command 'undo)
1419 (or (eq pending-undo-list t)
1420 ;; If something (a timer or filter?) changed the buffer
1421 ;; since the previous command, don't continue the undo seq.
1422 (let ((list buffer-undo-list))
1423 (while (eq (car list) nil)
1424 (setq list (cdr list)))
1425 ;; If the last undo record made was made by undo
1426 ;; it shows nothing else happened in between.
1427 (gethash list undo-equiv-table))))
1428 (setq undo-in-region
1429 (if transient-mark-mode mark-active (and arg (not (numberp arg)))))
1430 (if undo-in-region
1431 (undo-start (region-beginning) (region-end))
1432 (undo-start))
1433 ;; get rid of initial undo boundary
1434 (undo-more 1))
1435 ;; If we got this far, the next command should be a consecutive undo.
1436 (setq this-command 'undo)
1437 ;; Check to see whether we're hitting a redo record, and if
1438 ;; so, ask the user whether she wants to skip the redo/undo pair.
1439 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
1440 (or (eq (selected-window) (minibuffer-window))
1441 (setq message (if undo-in-region
1442 (if equiv "Redo in region!" "Undo in region!")
1443 (if equiv "Redo!" "Undo!"))))
1444 (when (and (consp equiv) undo-no-redo)
1445 ;; The equiv entry might point to another redo record if we have done
1446 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1447 (while (let ((next (gethash equiv undo-equiv-table)))
1448 (if next (setq equiv next))))
1449 (setq pending-undo-list equiv)))
1450 (undo-more
1451 (if (or transient-mark-mode (numberp arg))
1452 (prefix-numeric-value arg)
1454 ;; Record the fact that the just-generated undo records come from an
1455 ;; undo operation--that is, they are redo records.
1456 ;; In the ordinary case (not within a region), map the redo
1457 ;; record to the following undos.
1458 ;; I don't know how to do that in the undo-in-region case.
1459 (puthash buffer-undo-list
1460 (if undo-in-region t pending-undo-list)
1461 undo-equiv-table)
1462 ;; Don't specify a position in the undo record for the undo command.
1463 ;; Instead, undoing this should move point to where the change is.
1464 (let ((tail buffer-undo-list)
1465 (prev nil))
1466 (while (car tail)
1467 (when (integerp (car tail))
1468 (let ((pos (car tail)))
1469 (if prev
1470 (setcdr prev (cdr tail))
1471 (setq buffer-undo-list (cdr tail)))
1472 (setq tail (cdr tail))
1473 (while (car tail)
1474 (if (eq pos (car tail))
1475 (if prev
1476 (setcdr prev (cdr tail))
1477 (setq buffer-undo-list (cdr tail)))
1478 (setq prev tail))
1479 (setq tail (cdr tail)))
1480 (setq tail nil)))
1481 (setq prev tail tail (cdr tail))))
1482 ;; Record what the current undo list says,
1483 ;; so the next command can tell if the buffer was modified in between.
1484 (and modified (not (buffer-modified-p))
1485 (delete-auto-save-file-if-necessary recent-save))
1486 ;; Display a message announcing success.
1487 (if message
1488 (message message))))
1490 (defun buffer-disable-undo (&optional buffer)
1491 "Make BUFFER stop keeping undo information.
1492 No argument or nil as argument means do this for the current buffer."
1493 (interactive)
1494 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
1495 (setq buffer-undo-list t)))
1497 (defun undo-only (&optional arg)
1498 "Undo some previous changes.
1499 Repeat this command to undo more changes.
1500 A numeric argument serves as a repeat count.
1501 Contrary to `undo', this will not redo a previous undo."
1502 (interactive "*p")
1503 (let ((undo-no-redo t)) (undo arg)))
1505 (defvar undo-in-progress nil
1506 "Non-nil while performing an undo.
1507 Some change-hooks test this variable to do something different.")
1509 (defun undo-more (n)
1510 "Undo back N undo-boundaries beyond what was already undone recently.
1511 Call `undo-start' to get ready to undo recent changes,
1512 then call `undo-more' one or more times to undo them."
1513 (or (listp pending-undo-list)
1514 (error (concat "No further undo information"
1515 (and undo-in-region " for region"))))
1516 (let ((undo-in-progress t))
1517 (setq pending-undo-list (primitive-undo n pending-undo-list))
1518 (if (null pending-undo-list)
1519 (setq pending-undo-list t))))
1521 ;; Deep copy of a list
1522 (defun undo-copy-list (list)
1523 "Make a copy of undo list LIST."
1524 (mapcar 'undo-copy-list-1 list))
1526 (defun undo-copy-list-1 (elt)
1527 (if (consp elt)
1528 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1529 elt))
1531 (defun undo-start (&optional beg end)
1532 "Set `pending-undo-list' to the front of the undo list.
1533 The next call to `undo-more' will undo the most recently made change.
1534 If BEG and END are specified, then only undo elements
1535 that apply to text between BEG and END are used; other undo elements
1536 are ignored. If BEG and END are nil, all undo elements are used."
1537 (if (eq buffer-undo-list t)
1538 (error "No undo information in this buffer"))
1539 (setq pending-undo-list
1540 (if (and beg end (not (= beg end)))
1541 (undo-make-selective-list (min beg end) (max beg end))
1542 buffer-undo-list)))
1544 (defvar undo-adjusted-markers)
1546 (defun undo-make-selective-list (start end)
1547 "Return a list of undo elements for the region START to END.
1548 The elements come from `buffer-undo-list', but we keep only
1549 the elements inside this region, and discard those outside this region.
1550 If we find an element that crosses an edge of this region,
1551 we stop and ignore all further elements."
1552 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1553 (undo-list (list nil))
1554 undo-adjusted-markers
1555 some-rejected
1556 undo-elt undo-elt temp-undo-list delta)
1557 (while undo-list-copy
1558 (setq undo-elt (car undo-list-copy))
1559 (let ((keep-this
1560 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1561 ;; This is a "was unmodified" element.
1562 ;; Keep it if we have kept everything thus far.
1563 (not some-rejected))
1565 (undo-elt-in-region undo-elt start end)))))
1566 (if keep-this
1567 (progn
1568 (setq end (+ end (cdr (undo-delta undo-elt))))
1569 ;; Don't put two nils together in the list
1570 (if (not (and (eq (car undo-list) nil)
1571 (eq undo-elt nil)))
1572 (setq undo-list (cons undo-elt undo-list))))
1573 (if (undo-elt-crosses-region undo-elt start end)
1574 (setq undo-list-copy nil)
1575 (setq some-rejected t)
1576 (setq temp-undo-list (cdr undo-list-copy))
1577 (setq delta (undo-delta undo-elt))
1579 (when (/= (cdr delta) 0)
1580 (let ((position (car delta))
1581 (offset (cdr delta)))
1583 ;; Loop down the earlier events adjusting their buffer
1584 ;; positions to reflect the fact that a change to the buffer
1585 ;; isn't being undone. We only need to process those element
1586 ;; types which undo-elt-in-region will return as being in
1587 ;; the region since only those types can ever get into the
1588 ;; output
1590 (while temp-undo-list
1591 (setq undo-elt (car temp-undo-list))
1592 (cond ((integerp undo-elt)
1593 (if (>= undo-elt position)
1594 (setcar temp-undo-list (- undo-elt offset))))
1595 ((atom undo-elt) nil)
1596 ((stringp (car undo-elt))
1597 ;; (TEXT . POSITION)
1598 (let ((text-pos (abs (cdr undo-elt)))
1599 (point-at-end (< (cdr undo-elt) 0 )))
1600 (if (>= text-pos position)
1601 (setcdr undo-elt (* (if point-at-end -1 1)
1602 (- text-pos offset))))))
1603 ((integerp (car undo-elt))
1604 ;; (BEGIN . END)
1605 (when (>= (car undo-elt) position)
1606 (setcar undo-elt (- (car undo-elt) offset))
1607 (setcdr undo-elt (- (cdr undo-elt) offset))))
1608 ((null (car undo-elt))
1609 ;; (nil PROPERTY VALUE BEG . END)
1610 (let ((tail (nthcdr 3 undo-elt)))
1611 (when (>= (car tail) position)
1612 (setcar tail (- (car tail) offset))
1613 (setcdr tail (- (cdr tail) offset))))))
1614 (setq temp-undo-list (cdr temp-undo-list))))))))
1615 (setq undo-list-copy (cdr undo-list-copy)))
1616 (nreverse undo-list)))
1618 (defun undo-elt-in-region (undo-elt start end)
1619 "Determine whether UNDO-ELT falls inside the region START ... END.
1620 If it crosses the edge, we return nil."
1621 (cond ((integerp undo-elt)
1622 (and (>= undo-elt start)
1623 (<= undo-elt end)))
1624 ((eq undo-elt nil)
1626 ((atom undo-elt)
1627 nil)
1628 ((stringp (car undo-elt))
1629 ;; (TEXT . POSITION)
1630 (and (>= (abs (cdr undo-elt)) start)
1631 (< (abs (cdr undo-elt)) end)))
1632 ((and (consp undo-elt) (markerp (car undo-elt)))
1633 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1634 ;; See if MARKER is inside the region.
1635 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1636 (unless alist-elt
1637 (setq alist-elt (cons (car undo-elt)
1638 (marker-position (car undo-elt))))
1639 (setq undo-adjusted-markers
1640 (cons alist-elt undo-adjusted-markers)))
1641 (and (cdr alist-elt)
1642 (>= (cdr alist-elt) start)
1643 (<= (cdr alist-elt) end))))
1644 ((null (car undo-elt))
1645 ;; (nil PROPERTY VALUE BEG . END)
1646 (let ((tail (nthcdr 3 undo-elt)))
1647 (and (>= (car tail) start)
1648 (<= (cdr tail) end))))
1649 ((integerp (car undo-elt))
1650 ;; (BEGIN . END)
1651 (and (>= (car undo-elt) start)
1652 (<= (cdr undo-elt) end)))))
1654 (defun undo-elt-crosses-region (undo-elt start end)
1655 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1656 This assumes we have already decided that UNDO-ELT
1657 is not *inside* the region START...END."
1658 (cond ((atom undo-elt) nil)
1659 ((null (car undo-elt))
1660 ;; (nil PROPERTY VALUE BEG . END)
1661 (let ((tail (nthcdr 3 undo-elt)))
1662 (and (< (car tail) end)
1663 (> (cdr tail) start))))
1664 ((integerp (car undo-elt))
1665 ;; (BEGIN . END)
1666 (and (< (car undo-elt) end)
1667 (> (cdr undo-elt) start)))))
1669 ;; Return the first affected buffer position and the delta for an undo element
1670 ;; delta is defined as the change in subsequent buffer positions if we *did*
1671 ;; the undo.
1672 (defun undo-delta (undo-elt)
1673 (if (consp undo-elt)
1674 (cond ((stringp (car undo-elt))
1675 ;; (TEXT . POSITION)
1676 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1677 ((integerp (car undo-elt))
1678 ;; (BEGIN . END)
1679 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1681 '(0 . 0)))
1682 '(0 . 0)))
1684 (defcustom undo-ask-before-discard nil
1685 "If non-nil ask about discarding undo info for the current command.
1686 Normally, Emacs discards the undo info for the current command if
1687 it exceeds `undo-outer-limit'. But if you set this option
1688 non-nil, it asks in the echo area whether to discard the info.
1689 If you answer no, there is a slight risk that Emacs might crash, so
1690 only do it if you really want to undo the command.
1692 This option is mainly intended for debugging. You have to be
1693 careful if you use it for other purposes. Garbage collection is
1694 inhibited while the question is asked, meaning that Emacs might
1695 leak memory. So you should make sure that you do not wait
1696 excessively long before answering the question."
1697 :type 'boolean
1698 :group 'undo
1699 :version "22.1")
1701 (defvar undo-extra-outer-limit nil
1702 "If non-nil, an extra level of size that's ok in an undo item.
1703 We don't ask the user about truncating the undo list until the
1704 current item gets bigger than this amount.
1706 This variable only matters if `undo-ask-before-discard' is non-nil.")
1707 (make-variable-buffer-local 'undo-extra-outer-limit)
1709 ;; When the first undo batch in an undo list is longer than
1710 ;; undo-outer-limit, this function gets called to warn the user that
1711 ;; the undo info for the current command was discarded. Garbage
1712 ;; collection is inhibited around the call, so it had better not do a
1713 ;; lot of consing.
1714 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
1715 (defun undo-outer-limit-truncate (size)
1716 (if undo-ask-before-discard
1717 (when (or (null undo-extra-outer-limit)
1718 (> size undo-extra-outer-limit))
1719 ;; Don't ask the question again unless it gets even bigger.
1720 ;; This applies, in particular, if the user quits from the question.
1721 ;; Such a quit quits out of GC, but something else will call GC
1722 ;; again momentarily. It will call this function again,
1723 ;; but we don't want to ask the question again.
1724 (setq undo-extra-outer-limit (+ size 50000))
1725 (if (let (use-dialog-box track-mouse executing-kbd-macro )
1726 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
1727 (buffer-name) size)))
1728 (progn (setq buffer-undo-list nil)
1729 (setq undo-extra-outer-limit nil)
1731 nil))
1732 (display-warning '(undo discard-info)
1733 (concat
1734 (format "Buffer `%s' undo info was %d bytes long.\n"
1735 (buffer-name) size)
1736 "The undo info was discarded because it exceeded \
1737 `undo-outer-limit'.
1739 This is normal if you executed a command that made a huge change
1740 to the buffer. In that case, to prevent similar problems in the
1741 future, set `undo-outer-limit' to a value that is large enough to
1742 cover the maximum size of normal changes you expect a single
1743 command to make, but not so large that it might exceed the
1744 maximum memory allotted to Emacs.
1746 If you did not execute any such command, the situation is
1747 probably due to a bug and you should report it.
1749 You can disable the popping up of this buffer by adding the entry
1750 \(undo discard-info) to the user option `warning-suppress-types'.\n")
1751 :warning)
1752 (setq buffer-undo-list nil)
1755 (defvar shell-command-history nil
1756 "History list for some commands that read shell commands.
1758 Maximum length of the history list is determined by the value
1759 of `history-length', which see.")
1761 (defvar shell-command-switch "-c"
1762 "Switch used to have the shell execute its command line argument.")
1764 (defvar shell-command-default-error-buffer nil
1765 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1766 This buffer is used when `shell-command' or `shell-command-on-region'
1767 is run interactively. A value of nil means that output to stderr and
1768 stdout will be intermixed in the output stream.")
1770 (defun shell-command (command &optional output-buffer error-buffer)
1771 "Execute string COMMAND in inferior shell; display output, if any.
1772 With prefix argument, insert the COMMAND's output at point.
1774 If COMMAND ends in ampersand, execute it asynchronously.
1775 The output appears in the buffer `*Async Shell Command*'.
1776 That buffer is in shell mode.
1778 Otherwise, COMMAND is executed synchronously. The output appears in
1779 the buffer `*Shell Command Output*'. If the output is short enough to
1780 display in the echo area (which is determined by the variables
1781 `resize-mini-windows' and `max-mini-window-height'), it is shown
1782 there, but it is nonetheless available in buffer `*Shell Command
1783 Output*' even though that buffer is not automatically displayed.
1785 To specify a coding system for converting non-ASCII characters
1786 in the shell command output, use \\[universal-coding-system-argument]
1787 before this command.
1789 Noninteractive callers can specify coding systems by binding
1790 `coding-system-for-read' and `coding-system-for-write'.
1792 The optional second argument OUTPUT-BUFFER, if non-nil,
1793 says to put the output in some other buffer.
1794 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1795 If OUTPUT-BUFFER is not a buffer and not nil,
1796 insert output in current buffer. (This cannot be done asynchronously.)
1797 In either case, the output is inserted after point (leaving mark after it).
1799 If the command terminates without error, but generates output,
1800 and you did not specify \"insert it in the current buffer\",
1801 the output can be displayed in the echo area or in its buffer.
1802 If the output is short enough to display in the echo area
1803 \(determined by the variable `max-mini-window-height' if
1804 `resize-mini-windows' is non-nil), it is shown there. Otherwise,
1805 the buffer containing the output is displayed.
1807 If there is output and an error, and you did not specify \"insert it
1808 in the current buffer\", a message about the error goes at the end
1809 of the output.
1811 If there is no output, or if output is inserted in the current buffer,
1812 then `*Shell Command Output*' is deleted.
1814 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
1815 or buffer name to which to direct the command's standard error output.
1816 If it is nil, error output is mingled with regular output.
1817 In an interactive call, the variable `shell-command-default-error-buffer'
1818 specifies the value of ERROR-BUFFER."
1820 (interactive (list (read-from-minibuffer "Shell command: "
1821 nil nil nil 'shell-command-history)
1822 current-prefix-arg
1823 shell-command-default-error-buffer))
1824 ;; Look for a handler in case default-directory is a remote file name.
1825 (let ((handler
1826 (find-file-name-handler (directory-file-name default-directory)
1827 'shell-command)))
1828 (if handler
1829 (funcall handler 'shell-command command output-buffer error-buffer)
1830 (if (and output-buffer
1831 (not (or (bufferp output-buffer) (stringp output-buffer))))
1832 ;; Output goes in current buffer.
1833 (let ((error-file
1834 (if error-buffer
1835 (make-temp-file
1836 (expand-file-name "scor"
1837 (or small-temporary-file-directory
1838 temporary-file-directory)))
1839 nil)))
1840 (barf-if-buffer-read-only)
1841 (push-mark nil t)
1842 ;; We do not use -f for csh; we will not support broken use of
1843 ;; .cshrcs. Even the BSD csh manual says to use
1844 ;; "if ($?prompt) exit" before things which are not useful
1845 ;; non-interactively. Besides, if someone wants their other
1846 ;; aliases for shell commands then they can still have them.
1847 (call-process shell-file-name nil
1848 (if error-file
1849 (list t error-file)
1851 nil shell-command-switch command)
1852 (when (and error-file (file-exists-p error-file))
1853 (if (< 0 (nth 7 (file-attributes error-file)))
1854 (with-current-buffer (get-buffer-create error-buffer)
1855 (let ((pos-from-end (- (point-max) (point))))
1856 (or (bobp)
1857 (insert "\f\n"))
1858 ;; Do no formatting while reading error file,
1859 ;; because that can run a shell command, and we
1860 ;; don't want that to cause an infinite recursion.
1861 (format-insert-file error-file nil)
1862 ;; Put point after the inserted errors.
1863 (goto-char (- (point-max) pos-from-end)))
1864 (display-buffer (current-buffer))))
1865 (delete-file error-file))
1866 ;; This is like exchange-point-and-mark, but doesn't
1867 ;; activate the mark. It is cleaner to avoid activation,
1868 ;; even though the command loop would deactivate the mark
1869 ;; because we inserted text.
1870 (goto-char (prog1 (mark t)
1871 (set-marker (mark-marker) (point)
1872 (current-buffer)))))
1873 ;; Output goes in a separate buffer.
1874 ;; Preserve the match data in case called from a program.
1875 (save-match-data
1876 (if (string-match "[ \t]*&[ \t]*\\'" command)
1877 ;; Command ending with ampersand means asynchronous.
1878 (let ((buffer (get-buffer-create
1879 (or output-buffer "*Async Shell Command*")))
1880 (directory default-directory)
1881 proc)
1882 ;; Remove the ampersand.
1883 (setq command (substring command 0 (match-beginning 0)))
1884 ;; If will kill a process, query first.
1885 (setq proc (get-buffer-process buffer))
1886 (if proc
1887 (if (yes-or-no-p "A command is running. Kill it? ")
1888 (kill-process proc)
1889 (error "Shell command in progress")))
1890 (with-current-buffer buffer
1891 (setq buffer-read-only nil)
1892 (erase-buffer)
1893 (display-buffer buffer)
1894 (setq default-directory directory)
1895 (setq proc (start-process "Shell" buffer shell-file-name
1896 shell-command-switch command))
1897 (setq mode-line-process '(":%s"))
1898 (require 'shell) (shell-mode)
1899 (set-process-sentinel proc 'shell-command-sentinel)
1901 (shell-command-on-region (point) (point) command
1902 output-buffer nil error-buffer)))))))
1904 (defun display-message-or-buffer (message
1905 &optional buffer-name not-this-window frame)
1906 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
1907 MESSAGE may be either a string or a buffer.
1909 A buffer is displayed using `display-buffer' if MESSAGE is too long for
1910 the maximum height of the echo area, as defined by `max-mini-window-height'
1911 if `resize-mini-windows' is non-nil.
1913 Returns either the string shown in the echo area, or when a pop-up
1914 buffer is used, the window used to display it.
1916 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
1917 name of the buffer used to display it in the case where a pop-up buffer
1918 is used, defaulting to `*Message*'. In the case where MESSAGE is a
1919 string and it is displayed in the echo area, it is not specified whether
1920 the contents are inserted into the buffer anyway.
1922 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
1923 and only used if a buffer is displayed."
1924 (cond ((and (stringp message) (not (string-match "\n" message)))
1925 ;; Trivial case where we can use the echo area
1926 (message "%s" message))
1927 ((and (stringp message)
1928 (= (string-match "\n" message) (1- (length message))))
1929 ;; Trivial case where we can just remove single trailing newline
1930 (message "%s" (substring message 0 (1- (length message)))))
1932 ;; General case
1933 (with-current-buffer
1934 (if (bufferp message)
1935 message
1936 (get-buffer-create (or buffer-name "*Message*")))
1938 (unless (bufferp message)
1939 (erase-buffer)
1940 (insert message))
1942 (let ((lines
1943 (if (= (buffer-size) 0)
1945 (count-screen-lines nil nil nil (minibuffer-window)))))
1946 (cond ((= lines 0))
1947 ((and (or (<= lines 1)
1948 (<= lines
1949 (if resize-mini-windows
1950 (cond ((floatp max-mini-window-height)
1951 (* (frame-height)
1952 max-mini-window-height))
1953 ((integerp max-mini-window-height)
1954 max-mini-window-height)
1957 1)))
1958 ;; Don't use the echo area if the output buffer is
1959 ;; already dispayed in the selected frame.
1960 (not (get-buffer-window (current-buffer))))
1961 ;; Echo area
1962 (goto-char (point-max))
1963 (when (bolp)
1964 (backward-char 1))
1965 (message "%s" (buffer-substring (point-min) (point))))
1967 ;; Buffer
1968 (goto-char (point-min))
1969 (display-buffer (current-buffer)
1970 not-this-window frame))))))))
1973 ;; We have a sentinel to prevent insertion of a termination message
1974 ;; in the buffer itself.
1975 (defun shell-command-sentinel (process signal)
1976 (if (memq (process-status process) '(exit signal))
1977 (message "%s: %s."
1978 (car (cdr (cdr (process-command process))))
1979 (substring signal 0 -1))))
1981 (defun shell-command-on-region (start end command
1982 &optional output-buffer replace
1983 error-buffer display-error-buffer)
1984 "Execute string COMMAND in inferior shell with region as input.
1985 Normally display output (if any) in temp buffer `*Shell Command Output*';
1986 Prefix arg means replace the region with it. Return the exit code of
1987 COMMAND.
1989 To specify a coding system for converting non-ASCII characters
1990 in the input and output to the shell command, use \\[universal-coding-system-argument]
1991 before this command. By default, the input (from the current buffer)
1992 is encoded in the same coding system that will be used to save the file,
1993 `buffer-file-coding-system'. If the output is going to replace the region,
1994 then it is decoded from that same coding system.
1996 The noninteractive arguments are START, END, COMMAND,
1997 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
1998 Noninteractive callers can specify coding systems by binding
1999 `coding-system-for-read' and `coding-system-for-write'.
2001 If the command generates output, the output may be displayed
2002 in the echo area or in a buffer.
2003 If the output is short enough to display in the echo area
2004 \(determined by the variable `max-mini-window-height' if
2005 `resize-mini-windows' is non-nil), it is shown there. Otherwise
2006 it is displayed in the buffer `*Shell Command Output*'. The output
2007 is available in that buffer in both cases.
2009 If there is output and an error, a message about the error
2010 appears at the end of the output.
2012 If there is no output, or if output is inserted in the current buffer,
2013 then `*Shell Command Output*' is deleted.
2015 If the optional fourth argument OUTPUT-BUFFER is non-nil,
2016 that says to put the output in some other buffer.
2017 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2018 If OUTPUT-BUFFER is not a buffer and not nil,
2019 insert output in the current buffer.
2020 In either case, the output is inserted after point (leaving mark after it).
2022 If REPLACE, the optional fifth argument, is non-nil, that means insert
2023 the output in place of text from START to END, putting point and mark
2024 around it.
2026 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
2027 or buffer name to which to direct the command's standard error output.
2028 If it is nil, error output is mingled with regular output.
2029 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2030 were any errors. (This is always t, interactively.)
2031 In an interactive call, the variable `shell-command-default-error-buffer'
2032 specifies the value of ERROR-BUFFER."
2033 (interactive (let (string)
2034 (unless (mark)
2035 (error "The mark is not set now, so there is no region"))
2036 ;; Do this before calling region-beginning
2037 ;; and region-end, in case subprocess output
2038 ;; relocates them while we are in the minibuffer.
2039 (setq string (read-from-minibuffer "Shell command on region: "
2040 nil nil nil
2041 'shell-command-history))
2042 ;; call-interactively recognizes region-beginning and
2043 ;; region-end specially, leaving them in the history.
2044 (list (region-beginning) (region-end)
2045 string
2046 current-prefix-arg
2047 current-prefix-arg
2048 shell-command-default-error-buffer
2049 t)))
2050 (let ((error-file
2051 (if error-buffer
2052 (make-temp-file
2053 (expand-file-name "scor"
2054 (or small-temporary-file-directory
2055 temporary-file-directory)))
2056 nil))
2057 exit-status)
2058 (if (or replace
2059 (and output-buffer
2060 (not (or (bufferp output-buffer) (stringp output-buffer)))))
2061 ;; Replace specified region with output from command.
2062 (let ((swap (and replace (< start end))))
2063 ;; Don't muck with mark unless REPLACE says we should.
2064 (goto-char start)
2065 (and replace (push-mark (point) 'nomsg))
2066 (setq exit-status
2067 (call-process-region start end shell-file-name t
2068 (if error-file
2069 (list t error-file)
2071 nil shell-command-switch command))
2072 ;; It is rude to delete a buffer which the command is not using.
2073 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2074 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2075 ;; (kill-buffer shell-buffer)))
2076 ;; Don't muck with mark unless REPLACE says we should.
2077 (and replace swap (exchange-point-and-mark)))
2078 ;; No prefix argument: put the output in a temp buffer,
2079 ;; replacing its entire contents.
2080 (let ((buffer (get-buffer-create
2081 (or output-buffer "*Shell Command Output*"))))
2082 (unwind-protect
2083 (if (eq buffer (current-buffer))
2084 ;; If the input is the same buffer as the output,
2085 ;; delete everything but the specified region,
2086 ;; then replace that region with the output.
2087 (progn (setq buffer-read-only nil)
2088 (delete-region (max start end) (point-max))
2089 (delete-region (point-min) (min start end))
2090 (setq exit-status
2091 (call-process-region (point-min) (point-max)
2092 shell-file-name t
2093 (if error-file
2094 (list t error-file)
2096 nil shell-command-switch
2097 command)))
2098 ;; Clear the output buffer, then run the command with
2099 ;; output there.
2100 (let ((directory default-directory))
2101 (save-excursion
2102 (set-buffer buffer)
2103 (setq buffer-read-only nil)
2104 (if (not output-buffer)
2105 (setq default-directory directory))
2106 (erase-buffer)))
2107 (setq exit-status
2108 (call-process-region start end shell-file-name nil
2109 (if error-file
2110 (list buffer error-file)
2111 buffer)
2112 nil shell-command-switch command)))
2113 ;; Report the output.
2114 (with-current-buffer buffer
2115 (setq mode-line-process
2116 (cond ((null exit-status)
2117 " - Error")
2118 ((stringp exit-status)
2119 (format " - Signal [%s]" exit-status))
2120 ((not (equal 0 exit-status))
2121 (format " - Exit [%d]" exit-status)))))
2122 (if (with-current-buffer buffer (> (point-max) (point-min)))
2123 ;; There's some output, display it
2124 (display-message-or-buffer buffer)
2125 ;; No output; error?
2126 (let ((output
2127 (if (and error-file
2128 (< 0 (nth 7 (file-attributes error-file))))
2129 "some error output"
2130 "no output")))
2131 (cond ((null exit-status)
2132 (message "(Shell command failed with error)"))
2133 ((equal 0 exit-status)
2134 (message "(Shell command succeeded with %s)"
2135 output))
2136 ((stringp exit-status)
2137 (message "(Shell command killed by signal %s)"
2138 exit-status))
2140 (message "(Shell command failed with code %d and %s)"
2141 exit-status output))))
2142 ;; Don't kill: there might be useful info in the undo-log.
2143 ;; (kill-buffer buffer)
2144 ))))
2146 (when (and error-file (file-exists-p error-file))
2147 (if (< 0 (nth 7 (file-attributes error-file)))
2148 (with-current-buffer (get-buffer-create error-buffer)
2149 (let ((pos-from-end (- (point-max) (point))))
2150 (or (bobp)
2151 (insert "\f\n"))
2152 ;; Do no formatting while reading error file,
2153 ;; because that can run a shell command, and we
2154 ;; don't want that to cause an infinite recursion.
2155 (format-insert-file error-file nil)
2156 ;; Put point after the inserted errors.
2157 (goto-char (- (point-max) pos-from-end)))
2158 (and display-error-buffer
2159 (display-buffer (current-buffer)))))
2160 (delete-file error-file))
2161 exit-status))
2163 (defun shell-command-to-string (command)
2164 "Execute shell command COMMAND and return its output as a string."
2165 (with-output-to-string
2166 (with-current-buffer
2167 standard-output
2168 (call-process shell-file-name nil t nil shell-command-switch command))))
2170 (defun process-file (program &optional infile buffer display &rest args)
2171 "Process files synchronously in a separate process.
2172 Similar to `call-process', but may invoke a file handler based on
2173 `default-directory'. The current working directory of the
2174 subprocess is `default-directory'.
2176 File names in INFILE and BUFFER are handled normally, but file
2177 names in ARGS should be relative to `default-directory', as they
2178 are passed to the process verbatim. \(This is a difference to
2179 `call-process' which does not support file handlers for INFILE
2180 and BUFFER.\)
2182 Some file handlers might not support all variants, for example
2183 they might behave as if DISPLAY was nil, regardless of the actual
2184 value passed."
2185 (let ((fh (find-file-name-handler default-directory 'process-file))
2186 lc stderr-file)
2187 (unwind-protect
2188 (if fh (apply fh 'process-file program infile buffer display args)
2189 (when infile (setq lc (file-local-copy infile)))
2190 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
2191 (make-temp-file "emacs")))
2192 (prog1
2193 (apply 'call-process program
2194 (or lc infile)
2195 (if stderr-file (list (car buffer) stderr-file) buffer)
2196 display args)
2197 (when stderr-file (copy-file stderr-file (cadr buffer)))))
2198 (when stderr-file (delete-file stderr-file))
2199 (when lc (delete-file lc)))))
2203 (defvar universal-argument-map
2204 (let ((map (make-sparse-keymap)))
2205 (define-key map [t] 'universal-argument-other-key)
2206 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2207 (define-key map [switch-frame] nil)
2208 (define-key map [?\C-u] 'universal-argument-more)
2209 (define-key map [?-] 'universal-argument-minus)
2210 (define-key map [?0] 'digit-argument)
2211 (define-key map [?1] 'digit-argument)
2212 (define-key map [?2] 'digit-argument)
2213 (define-key map [?3] 'digit-argument)
2214 (define-key map [?4] 'digit-argument)
2215 (define-key map [?5] 'digit-argument)
2216 (define-key map [?6] 'digit-argument)
2217 (define-key map [?7] 'digit-argument)
2218 (define-key map [?8] 'digit-argument)
2219 (define-key map [?9] 'digit-argument)
2220 (define-key map [kp-0] 'digit-argument)
2221 (define-key map [kp-1] 'digit-argument)
2222 (define-key map [kp-2] 'digit-argument)
2223 (define-key map [kp-3] 'digit-argument)
2224 (define-key map [kp-4] 'digit-argument)
2225 (define-key map [kp-5] 'digit-argument)
2226 (define-key map [kp-6] 'digit-argument)
2227 (define-key map [kp-7] 'digit-argument)
2228 (define-key map [kp-8] 'digit-argument)
2229 (define-key map [kp-9] 'digit-argument)
2230 (define-key map [kp-subtract] 'universal-argument-minus)
2231 map)
2232 "Keymap used while processing \\[universal-argument].")
2234 (defvar universal-argument-num-events nil
2235 "Number of argument-specifying events read by `universal-argument'.
2236 `universal-argument-other-key' uses this to discard those events
2237 from (this-command-keys), and reread only the final command.")
2239 (defvar overriding-map-is-bound nil
2240 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2242 (defvar saved-overriding-map nil
2243 "The saved value of `overriding-terminal-local-map'.
2244 That variable gets restored to this value on exiting \"universal
2245 argument mode\".")
2247 (defun ensure-overriding-map-is-bound ()
2248 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2249 (unless overriding-map-is-bound
2250 (setq saved-overriding-map overriding-terminal-local-map)
2251 (setq overriding-terminal-local-map universal-argument-map)
2252 (setq overriding-map-is-bound t)))
2254 (defun restore-overriding-map ()
2255 "Restore `overriding-terminal-local-map' to its saved value."
2256 (setq overriding-terminal-local-map saved-overriding-map)
2257 (setq overriding-map-is-bound nil))
2259 (defun universal-argument ()
2260 "Begin a numeric argument for the following command.
2261 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2262 \\[universal-argument] following the digits or minus sign ends the argument.
2263 \\[universal-argument] without digits or minus sign provides 4 as argument.
2264 Repeating \\[universal-argument] without digits or minus sign
2265 multiplies the argument by 4 each time.
2266 For some commands, just \\[universal-argument] by itself serves as a flag
2267 which is different in effect from any particular numeric argument.
2268 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2269 (interactive)
2270 (setq prefix-arg (list 4))
2271 (setq universal-argument-num-events (length (this-command-keys)))
2272 (ensure-overriding-map-is-bound))
2274 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2275 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2276 (defun universal-argument-more (arg)
2277 (interactive "P")
2278 (if (consp arg)
2279 (setq prefix-arg (list (* 4 (car arg))))
2280 (if (eq arg '-)
2281 (setq prefix-arg (list -4))
2282 (setq prefix-arg arg)
2283 (restore-overriding-map)))
2284 (setq universal-argument-num-events (length (this-command-keys))))
2286 (defun negative-argument (arg)
2287 "Begin a negative numeric argument for the next command.
2288 \\[universal-argument] following digits or minus sign ends the argument."
2289 (interactive "P")
2290 (cond ((integerp arg)
2291 (setq prefix-arg (- arg)))
2292 ((eq arg '-)
2293 (setq prefix-arg nil))
2295 (setq prefix-arg '-)))
2296 (setq universal-argument-num-events (length (this-command-keys)))
2297 (ensure-overriding-map-is-bound))
2299 (defun digit-argument (arg)
2300 "Part of the numeric argument for the next command.
2301 \\[universal-argument] following digits or minus sign ends the argument."
2302 (interactive "P")
2303 (let* ((char (if (integerp last-command-char)
2304 last-command-char
2305 (get last-command-char 'ascii-character)))
2306 (digit (- (logand char ?\177) ?0)))
2307 (cond ((integerp arg)
2308 (setq prefix-arg (+ (* arg 10)
2309 (if (< arg 0) (- digit) digit))))
2310 ((eq arg '-)
2311 ;; Treat -0 as just -, so that -01 will work.
2312 (setq prefix-arg (if (zerop digit) '- (- digit))))
2314 (setq prefix-arg digit))))
2315 (setq universal-argument-num-events (length (this-command-keys)))
2316 (ensure-overriding-map-is-bound))
2318 ;; For backward compatibility, minus with no modifiers is an ordinary
2319 ;; command if digits have already been entered.
2320 (defun universal-argument-minus (arg)
2321 (interactive "P")
2322 (if (integerp arg)
2323 (universal-argument-other-key arg)
2324 (negative-argument arg)))
2326 ;; Anything else terminates the argument and is left in the queue to be
2327 ;; executed as a command.
2328 (defun universal-argument-other-key (arg)
2329 (interactive "P")
2330 (setq prefix-arg arg)
2331 (let* ((key (this-command-keys))
2332 (keylist (listify-key-sequence key)))
2333 (setq unread-command-events
2334 (append (nthcdr universal-argument-num-events keylist)
2335 unread-command-events)))
2336 (reset-this-command-lengths)
2337 (restore-overriding-map))
2339 (defvar buffer-substring-filters nil
2340 "List of filter functions for `filter-buffer-substring'.
2341 Each function must accept a single argument, a string, and return
2342 a string. The buffer substring is passed to the first function
2343 in the list, and the return value of each function is passed to
2344 the next. The return value of the last function is used as the
2345 return value of `filter-buffer-substring'.
2347 If this variable is nil, no filtering is performed.")
2349 (defun filter-buffer-substring (beg end &optional delete noprops)
2350 "Return the buffer substring between BEG and END, after filtering.
2351 The buffer substring is passed through each of the filter
2352 functions in `buffer-substring-filters', and the value from the
2353 last filter function is returned. If `buffer-substring-filters'
2354 is nil, the buffer substring is returned unaltered.
2356 If DELETE is non-nil, the text between BEG and END is deleted
2357 from the buffer.
2359 If NOPROPS is non-nil, final string returned does not include
2360 text properties, while the string passed to the filters still
2361 includes text properties from the buffer text.
2363 Point is temporarily set to BEG before calling
2364 `buffer-substring-filters', in case the functions need to know
2365 where the text came from.
2367 This function should be used instead of `buffer-substring',
2368 `buffer-substring-no-properties', or `delete-and-extract-region'
2369 when you want to allow filtering to take place. For example,
2370 major or minor modes can use `buffer-substring-filters' to
2371 extract characters that are special to a buffer, and should not
2372 be copied into other buffers."
2373 (cond
2374 ((or delete buffer-substring-filters)
2375 (save-excursion
2376 (goto-char beg)
2377 (let ((string (if delete (delete-and-extract-region beg end)
2378 (buffer-substring beg end))))
2379 (dolist (filter buffer-substring-filters)
2380 (setq string (funcall filter string)))
2381 (if noprops
2382 (set-text-properties 0 (length string) nil string))
2383 string)))
2384 (noprops
2385 (buffer-substring-no-properties beg end))
2387 (buffer-substring beg end))))
2390 ;;;; Window system cut and paste hooks.
2392 (defvar interprogram-cut-function nil
2393 "Function to call to make a killed region available to other programs.
2395 Most window systems provide some sort of facility for cutting and
2396 pasting text between the windows of different programs.
2397 This variable holds a function that Emacs calls whenever text
2398 is put in the kill ring, to make the new kill available to other
2399 programs.
2401 The function takes one or two arguments.
2402 The first argument, TEXT, is a string containing
2403 the text which should be made available.
2404 The second, optional, argument PUSH, has the same meaning as the
2405 similar argument to `x-set-cut-buffer', which see.")
2407 (defvar interprogram-paste-function nil
2408 "Function to call to get text cut from other programs.
2410 Most window systems provide some sort of facility for cutting and
2411 pasting text between the windows of different programs.
2412 This variable holds a function that Emacs calls to obtain
2413 text that other programs have provided for pasting.
2415 The function should be called with no arguments. If the function
2416 returns nil, then no other program has provided such text, and the top
2417 of the Emacs kill ring should be used. If the function returns a
2418 string, then the caller of the function \(usually `current-kill')
2419 should put this string in the kill ring as the latest kill.
2421 Note that the function should return a string only if a program other
2422 than Emacs has provided a string for pasting; if Emacs provided the
2423 most recent string, the function should return nil. If it is
2424 difficult to tell whether Emacs or some other program provided the
2425 current string, it is probably good enough to return nil if the string
2426 is equal (according to `string=') to the last text Emacs provided.")
2430 ;;;; The kill ring data structure.
2432 (defvar kill-ring nil
2433 "List of killed text sequences.
2434 Since the kill ring is supposed to interact nicely with cut-and-paste
2435 facilities offered by window systems, use of this variable should
2436 interact nicely with `interprogram-cut-function' and
2437 `interprogram-paste-function'. The functions `kill-new',
2438 `kill-append', and `current-kill' are supposed to implement this
2439 interaction; you may want to use them instead of manipulating the kill
2440 ring directly.")
2442 (defcustom kill-ring-max 60
2443 "*Maximum length of kill ring before oldest elements are thrown away."
2444 :type 'integer
2445 :group 'killing)
2447 (defvar kill-ring-yank-pointer nil
2448 "The tail of the kill ring whose car is the last thing yanked.")
2450 (defun kill-new (string &optional replace yank-handler)
2451 "Make STRING the latest kill in the kill ring.
2452 Set `kill-ring-yank-pointer' to point to it.
2453 If `interprogram-cut-function' is non-nil, apply it to STRING.
2454 Optional second argument REPLACE non-nil means that STRING will replace
2455 the front of the kill ring, rather than being added to the list.
2457 Optional third arguments YANK-HANDLER controls how the STRING is later
2458 inserted into a buffer; see `insert-for-yank' for details.
2459 When a yank handler is specified, STRING must be non-empty (the yank
2460 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2462 When the yank handler has a non-nil PARAM element, the original STRING
2463 argument is not used by `insert-for-yank'. However, since Lisp code
2464 may access and use elements from the kill ring directly, the STRING
2465 argument should still be a \"useful\" string for such uses."
2466 (if (> (length string) 0)
2467 (if yank-handler
2468 (put-text-property 0 (length string)
2469 'yank-handler yank-handler string))
2470 (if yank-handler
2471 (signal 'args-out-of-range
2472 (list string "yank-handler specified for empty string"))))
2473 (if (fboundp 'menu-bar-update-yank-menu)
2474 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
2475 (if (and replace kill-ring)
2476 (setcar kill-ring string)
2477 (push string kill-ring)
2478 (if (> (length kill-ring) kill-ring-max)
2479 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
2480 (setq kill-ring-yank-pointer kill-ring)
2481 (if interprogram-cut-function
2482 (funcall interprogram-cut-function string (not replace))))
2484 (defun kill-append (string before-p &optional yank-handler)
2485 "Append STRING to the end of the latest kill in the kill ring.
2486 If BEFORE-P is non-nil, prepend STRING to the kill.
2487 Optional third argument YANK-HANDLER, if non-nil, specifies the
2488 yank-handler text property to be set on the combined kill ring
2489 string. If the specified yank-handler arg differs from the
2490 yank-handler property of the latest kill string, this function
2491 adds the combined string to the kill ring as a new element,
2492 instead of replacing the last kill with it.
2493 If `interprogram-cut-function' is set, pass the resulting kill to it."
2494 (let* ((cur (car kill-ring)))
2495 (kill-new (if before-p (concat string cur) (concat cur string))
2496 (or (= (length cur) 0)
2497 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2498 yank-handler)))
2500 (defun current-kill (n &optional do-not-move)
2501 "Rotate the yanking point by N places, and then return that kill.
2502 If N is zero, `interprogram-paste-function' is set, and calling it
2503 returns a string, then that string is added to the front of the
2504 kill ring and returned as the latest kill.
2505 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
2506 yanking point; just return the Nth kill forward."
2507 (let ((interprogram-paste (and (= n 0)
2508 interprogram-paste-function
2509 (funcall interprogram-paste-function))))
2510 (if interprogram-paste
2511 (progn
2512 ;; Disable the interprogram cut function when we add the new
2513 ;; text to the kill ring, so Emacs doesn't try to own the
2514 ;; selection, with identical text.
2515 (let ((interprogram-cut-function nil))
2516 (kill-new interprogram-paste))
2517 interprogram-paste)
2518 (or kill-ring (error "Kill ring is empty"))
2519 (let ((ARGth-kill-element
2520 (nthcdr (mod (- n (length kill-ring-yank-pointer))
2521 (length kill-ring))
2522 kill-ring)))
2523 (or do-not-move
2524 (setq kill-ring-yank-pointer ARGth-kill-element))
2525 (car ARGth-kill-element)))))
2529 ;;;; Commands for manipulating the kill ring.
2531 (defcustom kill-read-only-ok nil
2532 "*Non-nil means don't signal an error for killing read-only text."
2533 :type 'boolean
2534 :group 'killing)
2536 (put 'text-read-only 'error-conditions
2537 '(text-read-only buffer-read-only error))
2538 (put 'text-read-only 'error-message "Text is read-only")
2540 (defun kill-region (beg end &optional yank-handler)
2541 "Kill (\"cut\") text between point and mark.
2542 This deletes the text from the buffer and saves it in the kill ring.
2543 The command \\[yank] can retrieve it from there.
2544 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
2546 If you want to append the killed region to the last killed text,
2547 use \\[append-next-kill] before \\[kill-region].
2549 If the buffer is read-only, Emacs will beep and refrain from deleting
2550 the text, but put the text in the kill ring anyway. This means that
2551 you can use the killing commands to copy text from a read-only buffer.
2553 This is the primitive for programs to kill text (as opposed to deleting it).
2554 Supply two arguments, character positions indicating the stretch of text
2555 to be killed.
2556 Any command that calls this function is a \"kill command\".
2557 If the previous command was also a kill command,
2558 the text killed this time appends to the text killed last time
2559 to make one entry in the kill ring.
2561 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
2562 specifies the yank-handler text property to be set on the killed
2563 text. See `insert-for-yank'."
2564 ;; Pass point first, then mark, because the order matters
2565 ;; when calling kill-append.
2566 (interactive (list (point) (mark)))
2567 (unless (and beg end)
2568 (error "The mark is not set now, so there is no region"))
2569 (condition-case nil
2570 (let ((string (filter-buffer-substring beg end t)))
2571 (when string ;STRING is nil if BEG = END
2572 ;; Add that string to the kill ring, one way or another.
2573 (if (eq last-command 'kill-region)
2574 (kill-append string (< end beg) yank-handler)
2575 (kill-new string nil yank-handler)))
2576 (when (or string (eq last-command 'kill-region))
2577 (setq this-command 'kill-region))
2578 nil)
2579 ((buffer-read-only text-read-only)
2580 ;; The code above failed because the buffer, or some of the characters
2581 ;; in the region, are read-only.
2582 ;; We should beep, in case the user just isn't aware of this.
2583 ;; However, there's no harm in putting
2584 ;; the region's text in the kill ring, anyway.
2585 (copy-region-as-kill beg end)
2586 ;; Set this-command now, so it will be set even if we get an error.
2587 (setq this-command 'kill-region)
2588 ;; This should barf, if appropriate, and give us the correct error.
2589 (if kill-read-only-ok
2590 (progn (message "Read only text copied to kill ring") nil)
2591 ;; Signal an error if the buffer is read-only.
2592 (barf-if-buffer-read-only)
2593 ;; If the buffer isn't read-only, the text is.
2594 (signal 'text-read-only (list (current-buffer)))))))
2596 ;; copy-region-as-kill no longer sets this-command, because it's confusing
2597 ;; to get two copies of the text when the user accidentally types M-w and
2598 ;; then corrects it with the intended C-w.
2599 (defun copy-region-as-kill (beg end)
2600 "Save the region as if killed, but don't kill it.
2601 In Transient Mark mode, deactivate the mark.
2602 If `interprogram-cut-function' is non-nil, also save the text for a window
2603 system cut and paste."
2604 (interactive "r")
2605 (if (eq last-command 'kill-region)
2606 (kill-append (filter-buffer-substring beg end) (< end beg))
2607 (kill-new (filter-buffer-substring beg end)))
2608 (if transient-mark-mode
2609 (setq deactivate-mark t))
2610 nil)
2612 (defun kill-ring-save (beg end)
2613 "Save the region as if killed, but don't kill it.
2614 In Transient Mark mode, deactivate the mark.
2615 If `interprogram-cut-function' is non-nil, also save the text for a window
2616 system cut and paste.
2618 If you want to append the killed line to the last killed text,
2619 use \\[append-next-kill] before \\[kill-ring-save].
2621 This command is similar to `copy-region-as-kill', except that it gives
2622 visual feedback indicating the extent of the region being copied."
2623 (interactive "r")
2624 (copy-region-as-kill beg end)
2625 ;; This use of interactive-p is correct
2626 ;; because the code it controls just gives the user visual feedback.
2627 (if (interactive-p)
2628 (let ((other-end (if (= (point) beg) end beg))
2629 (opoint (point))
2630 ;; Inhibit quitting so we can make a quit here
2631 ;; look like a C-g typed as a command.
2632 (inhibit-quit t))
2633 (if (pos-visible-in-window-p other-end (selected-window))
2634 (unless (and transient-mark-mode
2635 (face-background 'region))
2636 ;; Swap point and mark.
2637 (set-marker (mark-marker) (point) (current-buffer))
2638 (goto-char other-end)
2639 (sit-for blink-matching-delay)
2640 ;; Swap back.
2641 (set-marker (mark-marker) other-end (current-buffer))
2642 (goto-char opoint)
2643 ;; If user quit, deactivate the mark
2644 ;; as C-g would as a command.
2645 (and quit-flag mark-active
2646 (deactivate-mark)))
2647 (let* ((killed-text (current-kill 0))
2648 (message-len (min (length killed-text) 40)))
2649 (if (= (point) beg)
2650 ;; Don't say "killed"; that is misleading.
2651 (message "Saved text until \"%s\""
2652 (substring killed-text (- message-len)))
2653 (message "Saved text from \"%s\""
2654 (substring killed-text 0 message-len))))))))
2656 (defun append-next-kill (&optional interactive)
2657 "Cause following command, if it kills, to append to previous kill.
2658 The argument is used for internal purposes; do not supply one."
2659 (interactive "p")
2660 ;; We don't use (interactive-p), since that breaks kbd macros.
2661 (if interactive
2662 (progn
2663 (setq this-command 'kill-region)
2664 (message "If the next command is a kill, it will append"))
2665 (setq last-command 'kill-region)))
2667 ;; Yanking.
2669 ;; This is actually used in subr.el but defcustom does not work there.
2670 (defcustom yank-excluded-properties
2671 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2672 yank-handler follow-link fontified)
2673 "*Text properties to discard when yanking.
2674 The value should be a list of text properties to discard or t,
2675 which means to discard all text properties."
2676 :type '(choice (const :tag "All" t) (repeat symbol))
2677 :group 'killing
2678 :version "22.1")
2680 (defvar yank-window-start nil)
2681 (defvar yank-undo-function nil
2682 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2683 Function is called with two parameters, START and END corresponding to
2684 the value of the mark and point; it is guaranteed that START <= END.
2685 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
2687 (defun yank-pop (&optional arg)
2688 "Replace just-yanked stretch of killed text with a different stretch.
2689 This command is allowed only immediately after a `yank' or a `yank-pop'.
2690 At such a time, the region contains a stretch of reinserted
2691 previously-killed text. `yank-pop' deletes that text and inserts in its
2692 place a different stretch of killed text.
2694 With no argument, the previous kill is inserted.
2695 With argument N, insert the Nth previous kill.
2696 If N is negative, this is a more recent kill.
2698 The sequence of kills wraps around, so that after the oldest one
2699 comes the newest one.
2701 When this command inserts killed text into the buffer, it honors
2702 `yank-excluded-properties' and `yank-handler' as described in the
2703 doc string for `insert-for-yank-1', which see."
2704 (interactive "*p")
2705 (if (not (eq last-command 'yank))
2706 (error "Previous command was not a yank"))
2707 (setq this-command 'yank)
2708 (unless arg (setq arg 1))
2709 (let ((inhibit-read-only t)
2710 (before (< (point) (mark t))))
2711 (if before
2712 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2713 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
2714 (setq yank-undo-function nil)
2715 (set-marker (mark-marker) (point) (current-buffer))
2716 (insert-for-yank (current-kill arg))
2717 ;; Set the window start back where it was in the yank command,
2718 ;; if possible.
2719 (set-window-start (selected-window) yank-window-start t)
2720 (if before
2721 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2722 ;; It is cleaner to avoid activation, even though the command
2723 ;; loop would deactivate the mark because we inserted text.
2724 (goto-char (prog1 (mark t)
2725 (set-marker (mark-marker) (point) (current-buffer))))))
2726 nil)
2728 (defun yank (&optional arg)
2729 "Reinsert (\"paste\") the last stretch of killed text.
2730 More precisely, reinsert the stretch of killed text most recently
2731 killed OR yanked. Put point at end, and set mark at beginning.
2732 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
2733 With argument N, reinsert the Nth most recently killed stretch of killed
2734 text.
2736 When this command inserts killed text into the buffer, it honors
2737 `yank-excluded-properties' and `yank-handler' as described in the
2738 doc string for `insert-for-yank-1', which see.
2740 See also the command `yank-pop' (\\[yank-pop])."
2741 (interactive "*P")
2742 (setq yank-window-start (window-start))
2743 ;; If we don't get all the way thru, make last-command indicate that
2744 ;; for the following command.
2745 (setq this-command t)
2746 (push-mark (point))
2747 (insert-for-yank (current-kill (cond
2748 ((listp arg) 0)
2749 ((eq arg '-) -2)
2750 (t (1- arg)))))
2751 (if (consp arg)
2752 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2753 ;; It is cleaner to avoid activation, even though the command
2754 ;; loop would deactivate the mark because we inserted text.
2755 (goto-char (prog1 (mark t)
2756 (set-marker (mark-marker) (point) (current-buffer)))))
2757 ;; If we do get all the way thru, make this-command indicate that.
2758 (if (eq this-command t)
2759 (setq this-command 'yank))
2760 nil)
2762 (defun rotate-yank-pointer (arg)
2763 "Rotate the yanking point in the kill ring.
2764 With argument, rotate that many kills forward (or backward, if negative)."
2765 (interactive "p")
2766 (current-kill arg))
2768 ;; Some kill commands.
2770 ;; Internal subroutine of delete-char
2771 (defun kill-forward-chars (arg)
2772 (if (listp arg) (setq arg (car arg)))
2773 (if (eq arg '-) (setq arg -1))
2774 (kill-region (point) (forward-point arg)))
2776 ;; Internal subroutine of backward-delete-char
2777 (defun kill-backward-chars (arg)
2778 (if (listp arg) (setq arg (car arg)))
2779 (if (eq arg '-) (setq arg -1))
2780 (kill-region (point) (forward-point (- arg))))
2782 (defcustom backward-delete-char-untabify-method 'untabify
2783 "*The method for untabifying when deleting backward.
2784 Can be `untabify' -- turn a tab to many spaces, then delete one space;
2785 `hungry' -- delete all whitespace, both tabs and spaces;
2786 `all' -- delete all whitespace, including tabs, spaces and newlines;
2787 nil -- just delete one character."
2788 :type '(choice (const untabify) (const hungry) (const all) (const nil))
2789 :version "20.3"
2790 :group 'killing)
2792 (defun backward-delete-char-untabify (arg &optional killp)
2793 "Delete characters backward, changing tabs into spaces.
2794 The exact behavior depends on `backward-delete-char-untabify-method'.
2795 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
2796 Interactively, ARG is the prefix arg (default 1)
2797 and KILLP is t if a prefix arg was specified."
2798 (interactive "*p\nP")
2799 (when (eq backward-delete-char-untabify-method 'untabify)
2800 (let ((count arg))
2801 (save-excursion
2802 (while (and (> count 0) (not (bobp)))
2803 (if (= (preceding-char) ?\t)
2804 (let ((col (current-column)))
2805 (forward-char -1)
2806 (setq col (- col (current-column)))
2807 (insert-char ?\s col)
2808 (delete-char 1)))
2809 (forward-char -1)
2810 (setq count (1- count))))))
2811 (delete-backward-char
2812 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
2813 ((eq backward-delete-char-untabify-method 'all)
2814 " \t\n\r"))))
2815 (if skip
2816 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
2817 (point)))))
2818 (+ arg (if (zerop wh) 0 (1- wh))))
2819 arg))
2820 killp))
2822 (defun zap-to-char (arg char)
2823 "Kill up to and including ARG'th occurrence of CHAR.
2824 Case is ignored if `case-fold-search' is non-nil in the current buffer.
2825 Goes backward if ARG is negative; error if CHAR not found."
2826 (interactive "p\ncZap to char: ")
2827 (if (char-table-p translation-table-for-input)
2828 (setq char (or (aref translation-table-for-input char) char)))
2829 (kill-region (point) (progn
2830 (search-forward (char-to-string char) nil nil arg)
2831 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
2832 (point))))
2834 ;; kill-line and its subroutines.
2836 (defcustom kill-whole-line nil
2837 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
2838 :type 'boolean
2839 :group 'killing)
2841 (defun kill-line (&optional arg)
2842 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
2843 With prefix argument, kill that many lines from point.
2844 Negative arguments kill lines backward.
2845 With zero argument, kills the text before point on the current line.
2847 When calling from a program, nil means \"no arg\",
2848 a number counts as a prefix arg.
2850 To kill a whole line, when point is not at the beginning, type \
2851 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
2853 If `kill-whole-line' is non-nil, then this command kills the whole line
2854 including its terminating newline, when used at the beginning of a line
2855 with no argument. As a consequence, you can always kill a whole line
2856 by typing \\[move-beginning-of-line] \\[kill-line].
2858 If you want to append the killed line to the last killed text,
2859 use \\[append-next-kill] before \\[kill-line].
2861 If the buffer is read-only, Emacs will beep and refrain from deleting
2862 the line, but put the line in the kill ring anyway. This means that
2863 you can use this command to copy text from a read-only buffer.
2864 \(If the variable `kill-read-only-ok' is non-nil, then this won't
2865 even beep.)"
2866 (interactive "P")
2867 (kill-region (point)
2868 ;; It is better to move point to the other end of the kill
2869 ;; before killing. That way, in a read-only buffer, point
2870 ;; moves across the text that is copied to the kill ring.
2871 ;; The choice has no effect on undo now that undo records
2872 ;; the value of point from before the command was run.
2873 (progn
2874 (if arg
2875 (forward-visible-line (prefix-numeric-value arg))
2876 (if (eobp)
2877 (signal 'end-of-buffer nil))
2878 (let ((end
2879 (save-excursion
2880 (end-of-visible-line) (point))))
2881 (if (or (save-excursion
2882 ;; If trailing whitespace is visible,
2883 ;; don't treat it as nothing.
2884 (unless show-trailing-whitespace
2885 (skip-chars-forward " \t" end))
2886 (= (point) end))
2887 (and kill-whole-line (bolp)))
2888 (forward-visible-line 1)
2889 (goto-char end))))
2890 (point))))
2892 (defun kill-whole-line (&optional arg)
2893 "Kill current line.
2894 With prefix arg, kill that many lines starting from the current line.
2895 If arg is negative, kill backward. Also kill the preceding newline.
2896 \(This is meant to make \\[repeat] work well with negative arguments.\)
2897 If arg is zero, kill current line but exclude the trailing newline."
2898 (interactive "p")
2899 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
2900 (signal 'end-of-buffer nil))
2901 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
2902 (signal 'beginning-of-buffer nil))
2903 (unless (eq last-command 'kill-region)
2904 (kill-new "")
2905 (setq last-command 'kill-region))
2906 (cond ((zerop arg)
2907 ;; We need to kill in two steps, because the previous command
2908 ;; could have been a kill command, in which case the text
2909 ;; before point needs to be prepended to the current kill
2910 ;; ring entry and the text after point appended. Also, we
2911 ;; need to use save-excursion to avoid copying the same text
2912 ;; twice to the kill ring in read-only buffers.
2913 (save-excursion
2914 (kill-region (point) (progn (forward-visible-line 0) (point))))
2915 (kill-region (point) (progn (end-of-visible-line) (point))))
2916 ((< arg 0)
2917 (save-excursion
2918 (kill-region (point) (progn (end-of-visible-line) (point))))
2919 (kill-region (point)
2920 (progn (forward-visible-line (1+ arg))
2921 (unless (bobp) (backward-char))
2922 (point))))
2924 (save-excursion
2925 (kill-region (point) (progn (forward-visible-line 0) (point))))
2926 (kill-region (point)
2927 (progn (forward-visible-line arg) (point))))))
2929 (defun forward-visible-line (arg)
2930 "Move forward by ARG lines, ignoring currently invisible newlines only.
2931 If ARG is negative, move backward -ARG lines.
2932 If ARG is zero, move to the beginning of the current line."
2933 (condition-case nil
2934 (if (> arg 0)
2935 (progn
2936 (while (> arg 0)
2937 (or (zerop (forward-line 1))
2938 (signal 'end-of-buffer nil))
2939 ;; If the newline we just skipped is invisible,
2940 ;; don't count it.
2941 (let ((prop
2942 (get-char-property (1- (point)) 'invisible)))
2943 (if (if (eq buffer-invisibility-spec t)
2944 prop
2945 (or (memq prop buffer-invisibility-spec)
2946 (assq prop buffer-invisibility-spec)))
2947 (setq arg (1+ arg))))
2948 (setq arg (1- arg)))
2949 ;; If invisible text follows, and it is a number of complete lines,
2950 ;; skip it.
2951 (let ((opoint (point)))
2952 (while (and (not (eobp))
2953 (let ((prop
2954 (get-char-property (point) 'invisible)))
2955 (if (eq buffer-invisibility-spec t)
2956 prop
2957 (or (memq prop buffer-invisibility-spec)
2958 (assq prop buffer-invisibility-spec)))))
2959 (goto-char
2960 (if (get-text-property (point) 'invisible)
2961 (or (next-single-property-change (point) 'invisible)
2962 (point-max))
2963 (next-overlay-change (point)))))
2964 (unless (bolp)
2965 (goto-char opoint))))
2966 (let ((first t))
2967 (while (or first (<= arg 0))
2968 (if first
2969 (beginning-of-line)
2970 (or (zerop (forward-line -1))
2971 (signal 'beginning-of-buffer nil)))
2972 ;; If the newline we just moved to is invisible,
2973 ;; don't count it.
2974 (unless (bobp)
2975 (let ((prop
2976 (get-char-property (1- (point)) 'invisible)))
2977 (unless (if (eq buffer-invisibility-spec t)
2978 prop
2979 (or (memq prop buffer-invisibility-spec)
2980 (assq prop buffer-invisibility-spec)))
2981 (setq arg (1+ arg)))))
2982 (setq first nil))
2983 ;; If invisible text follows, and it is a number of complete lines,
2984 ;; skip it.
2985 (let ((opoint (point)))
2986 (while (and (not (bobp))
2987 (let ((prop
2988 (get-char-property (1- (point)) 'invisible)))
2989 (if (eq buffer-invisibility-spec t)
2990 prop
2991 (or (memq prop buffer-invisibility-spec)
2992 (assq prop buffer-invisibility-spec)))))
2993 (goto-char
2994 (if (get-text-property (1- (point)) 'invisible)
2995 (or (previous-single-property-change (point) 'invisible)
2996 (point-min))
2997 (previous-overlay-change (point)))))
2998 (unless (bolp)
2999 (goto-char opoint)))))
3000 ((beginning-of-buffer end-of-buffer)
3001 nil)))
3003 (defun end-of-visible-line ()
3004 "Move to end of current visible line."
3005 (end-of-line)
3006 ;; If the following character is currently invisible,
3007 ;; skip all characters with that same `invisible' property value,
3008 ;; then find the next newline.
3009 (while (and (not (eobp))
3010 (save-excursion
3011 (skip-chars-forward "^\n")
3012 (let ((prop
3013 (get-char-property (point) 'invisible)))
3014 (if (eq buffer-invisibility-spec t)
3015 prop
3016 (or (memq prop buffer-invisibility-spec)
3017 (assq prop buffer-invisibility-spec))))))
3018 (skip-chars-forward "^\n")
3019 (if (get-text-property (point) 'invisible)
3020 (goto-char (next-single-property-change (point) 'invisible))
3021 (goto-char (next-overlay-change (point))))
3022 (end-of-line)))
3024 (defun insert-buffer (buffer)
3025 "Insert after point the contents of BUFFER.
3026 Puts mark after the inserted text.
3027 BUFFER may be a buffer or a buffer name.
3029 This function is meant for the user to run interactively.
3030 Don't call it from programs: use `insert-buffer-substring' instead!"
3031 (interactive
3032 (list
3033 (progn
3034 (barf-if-buffer-read-only)
3035 (read-buffer "Insert buffer: "
3036 (if (eq (selected-window) (next-window (selected-window)))
3037 (other-buffer (current-buffer))
3038 (window-buffer (next-window (selected-window))))
3039 t))))
3040 (push-mark
3041 (save-excursion
3042 (insert-buffer-substring (get-buffer buffer))
3043 (point)))
3044 nil)
3046 (defun append-to-buffer (buffer start end)
3047 "Append to specified buffer the text of the region.
3048 It is inserted into that buffer before its point.
3050 When calling from a program, give three arguments:
3051 BUFFER (or buffer name), START and END.
3052 START and END specify the portion of the current buffer to be copied."
3053 (interactive
3054 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
3055 (region-beginning) (region-end)))
3056 (let ((oldbuf (current-buffer)))
3057 (save-excursion
3058 (let* ((append-to (get-buffer-create buffer))
3059 (windows (get-buffer-window-list append-to t t))
3060 point)
3061 (set-buffer append-to)
3062 (setq point (point))
3063 (barf-if-buffer-read-only)
3064 (insert-buffer-substring oldbuf start end)
3065 (dolist (window windows)
3066 (when (= (window-point window) point)
3067 (set-window-point window (point))))))))
3069 (defun prepend-to-buffer (buffer start end)
3070 "Prepend to specified buffer the text of the region.
3071 It is inserted into that buffer after its point.
3073 When calling from a program, give three arguments:
3074 BUFFER (or buffer name), START and END.
3075 START and END specify the portion of the current buffer to be copied."
3076 (interactive "BPrepend to buffer: \nr")
3077 (let ((oldbuf (current-buffer)))
3078 (save-excursion
3079 (set-buffer (get-buffer-create buffer))
3080 (barf-if-buffer-read-only)
3081 (save-excursion
3082 (insert-buffer-substring oldbuf start end)))))
3084 (defun copy-to-buffer (buffer start end)
3085 "Copy to specified buffer the text of the region.
3086 It is inserted into that buffer, replacing existing text there.
3088 When calling from a program, give three arguments:
3089 BUFFER (or buffer name), START and END.
3090 START and END specify the portion of the current buffer to be copied."
3091 (interactive "BCopy to buffer: \nr")
3092 (let ((oldbuf (current-buffer)))
3093 (with-current-buffer (get-buffer-create buffer)
3094 (barf-if-buffer-read-only)
3095 (erase-buffer)
3096 (save-excursion
3097 (insert-buffer-substring oldbuf start end)))))
3099 (put 'mark-inactive 'error-conditions '(mark-inactive error))
3100 (put 'mark-inactive 'error-message "The mark is not active now")
3102 (defvar activate-mark-hook nil
3103 "Hook run when the mark becomes active.
3104 It is also run at the end of a command, if the mark is active and
3105 it is possible that the region may have changed.")
3107 (defvar deactivate-mark-hook nil
3108 "Hook run when the mark becomes inactive.")
3110 (defun mark (&optional force)
3111 "Return this buffer's mark value as integer, or nil if never set.
3113 In Transient Mark mode, this function signals an error if
3114 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3115 or the argument FORCE is non-nil, it disregards whether the mark
3116 is active, and returns an integer or nil in the usual way.
3118 If you are using this in an editing command, you are most likely making
3119 a mistake; see the documentation of `set-mark'."
3120 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
3121 (marker-position (mark-marker))
3122 (signal 'mark-inactive nil)))
3124 ;; Many places set mark-active directly, and several of them failed to also
3125 ;; run deactivate-mark-hook. This shorthand should simplify.
3126 (defsubst deactivate-mark ()
3127 "Deactivate the mark by setting `mark-active' to nil.
3128 \(That makes a difference only in Transient Mark mode.)
3129 Also runs the hook `deactivate-mark-hook'."
3130 (cond
3131 ((eq transient-mark-mode 'lambda)
3132 (setq transient-mark-mode nil))
3133 (transient-mark-mode
3134 (setq mark-active nil)
3135 (run-hooks 'deactivate-mark-hook))))
3137 (defun set-mark (pos)
3138 "Set this buffer's mark to POS. Don't use this function!
3139 That is to say, don't use this function unless you want
3140 the user to see that the mark has moved, and you want the previous
3141 mark position to be lost.
3143 Normally, when a new mark is set, the old one should go on the stack.
3144 This is why most applications should use `push-mark', not `set-mark'.
3146 Novice Emacs Lisp programmers often try to use the mark for the wrong
3147 purposes. The mark saves a location for the user's convenience.
3148 Most editing commands should not alter the mark.
3149 To remember a location for internal use in the Lisp program,
3150 store it in a Lisp variable. Example:
3152 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3154 (if pos
3155 (progn
3156 (setq mark-active t)
3157 (run-hooks 'activate-mark-hook)
3158 (set-marker (mark-marker) pos (current-buffer)))
3159 ;; Normally we never clear mark-active except in Transient Mark mode.
3160 ;; But when we actually clear out the mark value too,
3161 ;; we must clear mark-active in any mode.
3162 (setq mark-active nil)
3163 (run-hooks 'deactivate-mark-hook)
3164 (set-marker (mark-marker) nil)))
3166 (defvar mark-ring nil
3167 "The list of former marks of the current buffer, most recent first.")
3168 (make-variable-buffer-local 'mark-ring)
3169 (put 'mark-ring 'permanent-local t)
3171 (defcustom mark-ring-max 16
3172 "*Maximum size of mark ring. Start discarding off end if gets this big."
3173 :type 'integer
3174 :group 'editing-basics)
3176 (defvar global-mark-ring nil
3177 "The list of saved global marks, most recent first.")
3179 (defcustom global-mark-ring-max 16
3180 "*Maximum size of global mark ring. \
3181 Start discarding off end if gets this big."
3182 :type 'integer
3183 :group 'editing-basics)
3185 (defun pop-to-mark-command ()
3186 "Jump to mark, and pop a new position for mark off the ring
3187 \(does not affect global mark ring\)."
3188 (interactive)
3189 (if (null (mark t))
3190 (error "No mark set in this buffer")
3191 (if (= (point) (mark t))
3192 (message "Mark popped"))
3193 (goto-char (mark t))
3194 (pop-mark)))
3196 (defun push-mark-command (arg &optional nomsg)
3197 "Set mark at where point is.
3198 If no prefix arg and mark is already set there, just activate it.
3199 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3200 (interactive "P")
3201 (let ((mark (marker-position (mark-marker))))
3202 (if (or arg (null mark) (/= mark (point)))
3203 (push-mark nil nomsg t)
3204 (setq mark-active t)
3205 (run-hooks 'activate-mark-hook)
3206 (unless nomsg
3207 (message "Mark activated")))))
3209 (defcustom set-mark-command-repeat-pop nil
3210 "*Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
3211 That means that C-u \\[set-mark-command] \\[set-mark-command]
3212 will pop the mark twice, and
3213 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
3214 will pop the mark three times.
3216 A value of nil means \\[set-mark-command]'s behavior does not change
3217 after C-u \\[set-mark-command]."
3218 :type 'boolean
3219 :group 'editing-basics)
3221 (defun set-mark-command (arg)
3222 "Set the mark where point is, or jump to the mark.
3223 Setting the mark also alters the region, which is the text
3224 between point and mark; this is the closest equivalent in
3225 Emacs to what some editors call the \"selection\".
3227 With no prefix argument, set the mark at point, and push the
3228 old mark position on local mark ring. Also push the old mark on
3229 global mark ring, if the previous mark was set in another buffer.
3231 When Transient Mark Mode is off, immediately repeating this
3232 command activates `transient-mark-mode' temporarily.
3234 With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
3235 jump to the mark, and set the mark from
3236 position popped off the local mark ring \(this does not affect the global
3237 mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
3238 mark ring \(see `pop-global-mark'\).
3240 If `set-mark-command-repeat-pop' is non-nil, repeating
3241 the \\[set-mark-command] command with no prefix argument pops the next position
3242 off the local (or global) mark ring and jumps there.
3244 With \\[universal-argument] \\[universal-argument] as prefix
3245 argument, unconditionally set mark where point is, even if
3246 `set-mark-command-repeat-pop' is non-nil.
3248 Novice Emacs Lisp programmers often try to use the mark for the wrong
3249 purposes. See the documentation of `set-mark' for more information."
3250 (interactive "P")
3251 (if (eq transient-mark-mode 'lambda)
3252 (setq transient-mark-mode nil))
3253 (cond
3254 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3255 (push-mark-command nil))
3256 ((not (eq this-command 'set-mark-command))
3257 (if arg
3258 (pop-to-mark-command)
3259 (push-mark-command t)))
3260 ((and set-mark-command-repeat-pop
3261 (eq last-command 'pop-to-mark-command))
3262 (setq this-command 'pop-to-mark-command)
3263 (pop-to-mark-command))
3264 ((and set-mark-command-repeat-pop
3265 (eq last-command 'pop-global-mark)
3266 (not arg))
3267 (setq this-command 'pop-global-mark)
3268 (pop-global-mark))
3269 (arg
3270 (setq this-command 'pop-to-mark-command)
3271 (pop-to-mark-command))
3272 ((and (eq last-command 'set-mark-command)
3273 mark-active (null transient-mark-mode))
3274 (setq transient-mark-mode 'lambda)
3275 (message "Transient-mark-mode temporarily enabled"))
3277 (push-mark-command nil))))
3279 (defun push-mark (&optional location nomsg activate)
3280 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3281 If the last global mark pushed was not in the current buffer,
3282 also push LOCATION on the global mark ring.
3283 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3285 Novice Emacs Lisp programmers often try to use the mark for the wrong
3286 purposes. See the documentation of `set-mark' for more information.
3288 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
3289 (unless (null (mark t))
3290 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3291 (when (> (length mark-ring) mark-ring-max)
3292 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3293 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3294 (set-marker (mark-marker) (or location (point)) (current-buffer))
3295 ;; Now push the mark on the global mark ring.
3296 (if (and global-mark-ring
3297 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3298 ;; The last global mark pushed was in this same buffer.
3299 ;; Don't push another one.
3301 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3302 (when (> (length global-mark-ring) global-mark-ring-max)
3303 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3304 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3305 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3306 (message "Mark set"))
3307 (if (or activate (not transient-mark-mode))
3308 (set-mark (mark t)))
3309 nil)
3311 (defun pop-mark ()
3312 "Pop off mark ring into the buffer's actual mark.
3313 Does not set point. Does nothing if mark ring is empty."
3314 (when mark-ring
3315 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3316 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3317 (move-marker (car mark-ring) nil)
3318 (if (null (mark t)) (ding))
3319 (setq mark-ring (cdr mark-ring)))
3320 (deactivate-mark))
3322 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
3323 (defun exchange-point-and-mark (&optional arg)
3324 "Put the mark where point is now, and point where the mark is now.
3325 This command works even when the mark is not active,
3326 and it reactivates the mark.
3327 With prefix arg, `transient-mark-mode' is enabled temporarily."
3328 (interactive "P")
3329 (if arg
3330 (if mark-active
3331 (if (null transient-mark-mode)
3332 (setq transient-mark-mode 'lambda))
3333 (setq arg nil)))
3334 (unless arg
3335 (let ((omark (mark t)))
3336 (if (null omark)
3337 (error "No mark set in this buffer"))
3338 (set-mark (point))
3339 (goto-char omark)
3340 nil)))
3342 (define-minor-mode transient-mark-mode
3343 "Toggle Transient Mark mode.
3344 With arg, turn Transient Mark mode on if arg is positive, off otherwise.
3346 In Transient Mark mode, when the mark is active, the region is highlighted.
3347 Changing the buffer \"deactivates\" the mark.
3348 So do certain other operations that set the mark
3349 but whose main purpose is something else--for example,
3350 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3352 You can also deactivate the mark by typing \\[keyboard-quit] or
3353 \\[keyboard-escape-quit].
3355 Many commands change their behavior when Transient Mark mode is in effect
3356 and the mark is active, by acting on the region instead of their usual
3357 default part of the buffer's text. Examples of such commands include
3358 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3359 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3360 Invoke \\[apropos-documentation] and type \"transient\" or
3361 \"mark.*active\" at the prompt, to see the documentation of
3362 commands which are sensitive to the Transient Mark mode."
3363 :global t :group 'editing-basics)
3365 (defvar widen-automatically t
3366 "Non-nil means it is ok for commands to call `widen' when they want to.
3367 Some commands will do this in order to go to positions outside
3368 the current accessible part of the buffer.
3370 If `widen-automatically' is nil, these commands will do something else
3371 as a fallback, and won't change the buffer bounds.")
3373 (defun pop-global-mark ()
3374 "Pop off global mark ring and jump to the top location."
3375 (interactive)
3376 ;; Pop entries which refer to non-existent buffers.
3377 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
3378 (setq global-mark-ring (cdr global-mark-ring)))
3379 (or global-mark-ring
3380 (error "No global mark set"))
3381 (let* ((marker (car global-mark-ring))
3382 (buffer (marker-buffer marker))
3383 (position (marker-position marker)))
3384 (setq global-mark-ring (nconc (cdr global-mark-ring)
3385 (list (car global-mark-ring))))
3386 (set-buffer buffer)
3387 (or (and (>= position (point-min))
3388 (<= position (point-max)))
3389 (if widen-automatically
3390 (widen)
3391 (error "Global mark position is outside accessible part of buffer")))
3392 (goto-char position)
3393 (switch-to-buffer buffer)))
3395 (defcustom next-line-add-newlines nil
3396 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
3397 :type 'boolean
3398 :version "21.1"
3399 :group 'editing-basics)
3401 (defun next-line (&optional arg try-vscroll)
3402 "Move cursor vertically down ARG lines.
3403 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3404 If there is no character in the target line exactly under the current column,
3405 the cursor is positioned after the character in that line which spans this
3406 column, or at the end of the line if it is not long enough.
3407 If there is no line in the buffer after this one, behavior depends on the
3408 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
3409 to create a line, and moves the cursor to that line. Otherwise it moves the
3410 cursor to the end of the buffer.
3412 The command \\[set-goal-column] can be used to create
3413 a semipermanent goal column for this command.
3414 Then instead of trying to move exactly vertically (or as close as possible),
3415 this command moves to the specified goal column (or as close as possible).
3416 The goal column is stored in the variable `goal-column', which is nil
3417 when there is no goal column.
3419 If you are thinking of using this in a Lisp program, consider
3420 using `forward-line' instead. It is usually easier to use
3421 and more reliable (no dependence on goal column, etc.)."
3422 (interactive "p\np")
3423 (or arg (setq arg 1))
3424 (if (and next-line-add-newlines (= arg 1))
3425 (if (save-excursion (end-of-line) (eobp))
3426 ;; When adding a newline, don't expand an abbrev.
3427 (let ((abbrev-mode nil))
3428 (end-of-line)
3429 (insert (if use-hard-newlines hard-newline "\n")))
3430 (line-move arg nil nil try-vscroll))
3431 (if (interactive-p)
3432 (condition-case nil
3433 (line-move arg nil nil try-vscroll)
3434 ((beginning-of-buffer end-of-buffer) (ding)))
3435 (line-move arg nil nil try-vscroll)))
3436 nil)
3438 (defun previous-line (&optional arg try-vscroll)
3439 "Move cursor vertically up ARG lines.
3440 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3441 If there is no character in the target line exactly over the current column,
3442 the cursor is positioned after the character in that line which spans this
3443 column, or at the end of the line if it is not long enough.
3445 The command \\[set-goal-column] can be used to create
3446 a semipermanent goal column for this command.
3447 Then instead of trying to move exactly vertically (or as close as possible),
3448 this command moves to the specified goal column (or as close as possible).
3449 The goal column is stored in the variable `goal-column', which is nil
3450 when there is no goal column.
3452 If you are thinking of using this in a Lisp program, consider using
3453 `forward-line' with a negative argument instead. It is usually easier
3454 to use and more reliable (no dependence on goal column, etc.)."
3455 (interactive "p\np")
3456 (or arg (setq arg 1))
3457 (if (interactive-p)
3458 (condition-case nil
3459 (line-move (- arg) nil nil try-vscroll)
3460 ((beginning-of-buffer end-of-buffer) (ding)))
3461 (line-move (- arg) nil nil try-vscroll))
3462 nil)
3464 (defcustom track-eol nil
3465 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
3466 This means moving to the end of each line moved onto.
3467 The beginning of a blank line does not count as the end of a line."
3468 :type 'boolean
3469 :group 'editing-basics)
3471 (defcustom goal-column nil
3472 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
3473 :type '(choice integer
3474 (const :tag "None" nil))
3475 :group 'editing-basics)
3476 (make-variable-buffer-local 'goal-column)
3478 (defvar temporary-goal-column 0
3479 "Current goal column for vertical motion.
3480 It is the column where point was
3481 at the start of current run of vertical motion commands.
3482 When the `track-eol' feature is doing its job, the value is 9999.")
3484 (defcustom line-move-ignore-invisible t
3485 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
3486 Outline mode sets this."
3487 :type 'boolean
3488 :group 'editing-basics)
3490 (defun invisible-p (pos)
3491 "Return non-nil if the character after POS is currently invisible."
3492 (let ((prop
3493 (get-char-property pos 'invisible)))
3494 (if (eq buffer-invisibility-spec t)
3495 prop
3496 (or (memq prop buffer-invisibility-spec)
3497 (assq prop buffer-invisibility-spec)))))
3498 (define-obsolete-function-alias 'line-move-invisible-p 'invisible-p)
3500 ;; Returns non-nil if partial move was done.
3501 (defun line-move-partial (arg noerror to-end)
3502 (if (< arg 0)
3503 ;; Move backward (up).
3504 ;; If already vscrolled, reduce vscroll
3505 (let ((vs (window-vscroll nil t)))
3506 (when (> vs (frame-char-height))
3507 (set-window-vscroll nil (- vs (frame-char-height)) t)))
3509 ;; Move forward (down).
3510 (let* ((lh (window-line-height -1))
3511 (vpos (nth 1 lh))
3512 (ypos (nth 2 lh))
3513 (rbot (nth 3 lh))
3514 ppos py vs)
3515 (when (or (null lh)
3516 (>= rbot (frame-char-height))
3517 (<= ypos (- (frame-char-height))))
3518 (unless lh
3519 (let ((wend (pos-visible-in-window-p t nil t)))
3520 (setq rbot (nth 3 wend)
3521 vpos (nth 5 wend))))
3522 (cond
3523 ;; If last line of window is fully visible, move forward.
3524 ((or (null rbot) (= rbot 0))
3525 nil)
3526 ;; If cursor is not in the bottom scroll margin, move forward.
3527 ((and (> vpos 0)
3528 (< (setq py
3529 (or (nth 1 (window-line-height))
3530 (let ((ppos (posn-at-point)))
3531 (cdr (or (posn-actual-col-row ppos)
3532 (posn-col-row ppos))))))
3533 (min (- (window-text-height) scroll-margin 1) (1- vpos))))
3534 nil)
3535 ;; When already vscrolled, we vscroll some more if we can,
3536 ;; or clear vscroll and move forward at end of tall image.
3537 ((> (setq vs (window-vscroll nil t)) 0)
3538 (when (> rbot 0)
3539 (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
3540 ;; If cursor just entered the bottom scroll margin, move forward,
3541 ;; but also vscroll one line so redisplay wont recenter.
3542 ((and (> vpos 0)
3543 (= py (min (- (window-text-height) scroll-margin 1)
3544 (1- vpos))))
3545 (set-window-vscroll nil (frame-char-height) t)
3546 (line-move-1 arg noerror to-end)
3548 ;; If there are lines above the last line, scroll-up one line.
3549 ((> vpos 0)
3550 (scroll-up 1)
3552 ;; Finally, start vscroll.
3554 (set-window-vscroll nil (frame-char-height) t)))))))
3557 ;; This is like line-move-1 except that it also performs
3558 ;; vertical scrolling of tall images if appropriate.
3559 ;; That is not really a clean thing to do, since it mixes
3560 ;; scrolling with cursor motion. But so far we don't have
3561 ;; a cleaner solution to the problem of making C-n do something
3562 ;; useful given a tall image.
3563 (defun line-move (arg &optional noerror to-end try-vscroll)
3564 (unless (and auto-window-vscroll try-vscroll
3565 ;; Only vscroll for single line moves
3566 (= (abs arg) 1)
3567 ;; But don't vscroll in a keyboard macro.
3568 (not defining-kbd-macro)
3569 (not executing-kbd-macro)
3570 (line-move-partial arg noerror to-end))
3571 (set-window-vscroll nil 0 t)
3572 (line-move-1 arg noerror to-end)))
3574 ;; This is the guts of next-line and previous-line.
3575 ;; Arg says how many lines to move.
3576 ;; The value is t if we can move the specified number of lines.
3577 (defun line-move-1 (arg &optional noerror to-end)
3578 ;; Don't run any point-motion hooks, and disregard intangibility,
3579 ;; for intermediate positions.
3580 (let ((inhibit-point-motion-hooks t)
3581 (opoint (point))
3582 (orig-arg arg))
3583 (unwind-protect
3584 (progn
3585 (if (not (memq last-command '(next-line previous-line)))
3586 (setq temporary-goal-column
3587 (if (and track-eol (eolp)
3588 ;; Don't count beg of empty line as end of line
3589 ;; unless we just did explicit end-of-line.
3590 (or (not (bolp)) (eq last-command 'move-end-of-line)))
3591 9999
3592 (current-column))))
3594 (if (and (not (integerp selective-display))
3595 (not line-move-ignore-invisible))
3596 ;; Use just newline characters.
3597 ;; Set ARG to 0 if we move as many lines as requested.
3598 (or (if (> arg 0)
3599 (progn (if (> arg 1) (forward-line (1- arg)))
3600 ;; This way of moving forward ARG lines
3601 ;; verifies that we have a newline after the last one.
3602 ;; It doesn't get confused by intangible text.
3603 (end-of-line)
3604 (if (zerop (forward-line 1))
3605 (setq arg 0)))
3606 (and (zerop (forward-line arg))
3607 (bolp)
3608 (setq arg 0)))
3609 (unless noerror
3610 (signal (if (< arg 0)
3611 'beginning-of-buffer
3612 'end-of-buffer)
3613 nil)))
3614 ;; Move by arg lines, but ignore invisible ones.
3615 (let (done)
3616 (while (and (> arg 0) (not done))
3617 ;; If the following character is currently invisible,
3618 ;; skip all characters with that same `invisible' property value.
3619 (while (and (not (eobp)) (invisible-p (point)))
3620 (goto-char (next-char-property-change (point))))
3621 ;; Move a line.
3622 ;; We don't use `end-of-line', since we want to escape
3623 ;; from field boundaries ocurring exactly at point.
3624 (goto-char (constrain-to-field
3625 (let ((inhibit-field-text-motion t))
3626 (line-end-position))
3627 (point) t t
3628 'inhibit-line-move-field-capture))
3629 ;; If there's no invisibility here, move over the newline.
3630 (cond
3631 ((eobp)
3632 (if (not noerror)
3633 (signal 'end-of-buffer nil)
3634 (setq done t)))
3635 ((and (> arg 1) ;; Use vertical-motion for last move
3636 (not (integerp selective-display))
3637 (not (invisible-p (point))))
3638 ;; We avoid vertical-motion when possible
3639 ;; because that has to fontify.
3640 (forward-line 1))
3641 ;; Otherwise move a more sophisticated way.
3642 ((zerop (vertical-motion 1))
3643 (if (not noerror)
3644 (signal 'end-of-buffer nil)
3645 (setq done t))))
3646 (unless done
3647 (setq arg (1- arg))))
3648 ;; The logic of this is the same as the loop above,
3649 ;; it just goes in the other direction.
3650 (while (and (< arg 0) (not done))
3651 ;; For completely consistency with the forward-motion
3652 ;; case, we should call beginning-of-line here.
3653 ;; However, if point is inside a field and on a
3654 ;; continued line, the call to (vertical-motion -1)
3655 ;; below won't move us back far enough; then we return
3656 ;; to the same column in line-move-finish, and point
3657 ;; gets stuck -- cyd
3658 (forward-line 0)
3659 (cond
3660 ((bobp)
3661 (if (not noerror)
3662 (signal 'beginning-of-buffer nil)
3663 (setq done t)))
3664 ((and (< arg -1) ;; Use vertical-motion for last move
3665 (not (integerp selective-display))
3666 (not (invisible-p (1- (point)))))
3667 (forward-line -1))
3668 ((zerop (vertical-motion -1))
3669 (if (not noerror)
3670 (signal 'beginning-of-buffer nil)
3671 (setq done t))))
3672 (unless done
3673 (setq arg (1+ arg))
3674 (while (and ;; Don't move over previous invis lines
3675 ;; if our target is the middle of this line.
3676 (or (zerop (or goal-column temporary-goal-column))
3677 (< arg 0))
3678 (not (bobp)) (invisible-p (1- (point))))
3679 (goto-char (previous-char-property-change (point))))))))
3680 ;; This is the value the function returns.
3681 (= arg 0))
3683 (cond ((> arg 0)
3684 ;; If we did not move down as far as desired,
3685 ;; at least go to end of line.
3686 (end-of-line))
3687 ((< arg 0)
3688 ;; If we did not move up as far as desired,
3689 ;; at least go to beginning of line.
3690 (beginning-of-line))
3692 (line-move-finish (or goal-column temporary-goal-column)
3693 opoint (> orig-arg 0)))))))
3695 (defun line-move-finish (column opoint forward)
3696 (let ((repeat t))
3697 (while repeat
3698 ;; Set REPEAT to t to repeat the whole thing.
3699 (setq repeat nil)
3701 (let (new
3702 (old (point))
3703 (line-beg (save-excursion (beginning-of-line) (point)))
3704 (line-end
3705 ;; Compute the end of the line
3706 ;; ignoring effectively invisible newlines.
3707 (save-excursion
3708 ;; Like end-of-line but ignores fields.
3709 (skip-chars-forward "^\n")
3710 (while (and (not (eobp)) (invisible-p (point)))
3711 (goto-char (next-char-property-change (point)))
3712 (skip-chars-forward "^\n"))
3713 (point))))
3715 ;; Move to the desired column.
3716 (line-move-to-column column)
3718 ;; Corner case: suppose we start out in a field boundary in
3719 ;; the middle of a continued line. When we get to
3720 ;; line-move-finish, point is at the start of a new *screen*
3721 ;; line but the same text line; then line-move-to-column would
3722 ;; move us backwards. Test using C-n with point on the "x" in
3723 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
3724 (and forward
3725 (< (point) old)
3726 (goto-char old))
3728 (setq new (point))
3730 ;; Process intangibility within a line.
3731 ;; With inhibit-point-motion-hooks bound to nil, a call to
3732 ;; goto-char moves point past intangible text.
3734 ;; However, inhibit-point-motion-hooks controls both the
3735 ;; intangibility and the point-entered/point-left hooks. The
3736 ;; following hack avoids calling the point-* hooks
3737 ;; unnecessarily. Note that we move *forward* past intangible
3738 ;; text when the initial and final points are the same.
3739 (goto-char new)
3740 (let ((inhibit-point-motion-hooks nil))
3741 (goto-char new)
3743 ;; If intangibility moves us to a different (later) place
3744 ;; in the same line, use that as the destination.
3745 (if (<= (point) line-end)
3746 (setq new (point))
3747 ;; If that position is "too late",
3748 ;; try the previous allowable position.
3749 ;; See if it is ok.
3750 (backward-char)
3751 (if (if forward
3752 ;; If going forward, don't accept the previous
3753 ;; allowable position if it is before the target line.
3754 (< line-beg (point))
3755 ;; If going backward, don't accept the previous
3756 ;; allowable position if it is still after the target line.
3757 (<= (point) line-end))
3758 (setq new (point))
3759 ;; As a last resort, use the end of the line.
3760 (setq new line-end))))
3762 ;; Now move to the updated destination, processing fields
3763 ;; as well as intangibility.
3764 (goto-char opoint)
3765 (let ((inhibit-point-motion-hooks nil))
3766 (goto-char
3767 ;; Ignore field boundaries if the initial and final
3768 ;; positions have the same `field' property, even if the
3769 ;; fields are non-contiguous. This seems to be "nicer"
3770 ;; behavior in many situations.
3771 (if (eq (get-char-property new 'field)
3772 (get-char-property opoint 'field))
3774 (constrain-to-field new opoint t t
3775 'inhibit-line-move-field-capture))))
3777 ;; If all this moved us to a different line,
3778 ;; retry everything within that new line.
3779 (when (or (< (point) line-beg) (> (point) line-end))
3780 ;; Repeat the intangibility and field processing.
3781 (setq repeat t))))))
3783 (defun line-move-to-column (col)
3784 "Try to find column COL, considering invisibility.
3785 This function works only in certain cases,
3786 because what we really need is for `move-to-column'
3787 and `current-column' to be able to ignore invisible text."
3788 (if (zerop col)
3789 (beginning-of-line)
3790 (move-to-column col))
3792 (when (and line-move-ignore-invisible
3793 (not (bolp)) (invisible-p (1- (point))))
3794 (let ((normal-location (point))
3795 (normal-column (current-column)))
3796 ;; If the following character is currently invisible,
3797 ;; skip all characters with that same `invisible' property value.
3798 (while (and (not (eobp))
3799 (invisible-p (point)))
3800 (goto-char (next-char-property-change (point))))
3801 ;; Have we advanced to a larger column position?
3802 (if (> (current-column) normal-column)
3803 ;; We have made some progress towards the desired column.
3804 ;; See if we can make any further progress.
3805 (line-move-to-column (+ (current-column) (- col normal-column)))
3806 ;; Otherwise, go to the place we originally found
3807 ;; and move back over invisible text.
3808 ;; that will get us to the same place on the screen
3809 ;; but with a more reasonable buffer position.
3810 (goto-char normal-location)
3811 (let ((line-beg (save-excursion (beginning-of-line) (point))))
3812 (while (and (not (bolp)) (invisible-p (1- (point))))
3813 (goto-char (previous-char-property-change (point) line-beg))))))))
3815 (defun move-end-of-line (arg)
3816 "Move point to end of current line as displayed.
3817 \(If there's an image in the line, this disregards newlines
3818 which are part of the text that the image rests on.)
3820 With argument ARG not nil or 1, move forward ARG - 1 lines first.
3821 If point reaches the beginning or end of buffer, it stops there.
3822 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
3823 (interactive "p")
3824 (or arg (setq arg 1))
3825 (let (done)
3826 (while (not done)
3827 (let ((newpos
3828 (save-excursion
3829 (let ((goal-column 0))
3830 (and (line-move arg t)
3831 (not (bobp))
3832 (progn
3833 (while (and (not (bobp)) (invisible-p (1- (point))))
3834 (goto-char (previous-char-property-change (point))))
3835 (backward-char 1)))
3836 (point)))))
3837 (goto-char newpos)
3838 (if (and (> (point) newpos)
3839 (eq (preceding-char) ?\n))
3840 (backward-char 1)
3841 (if (and (> (point) newpos) (not (eobp))
3842 (not (eq (following-char) ?\n)))
3843 ;; If we skipped something intangible
3844 ;; and now we're not really at eol,
3845 ;; keep going.
3846 (setq arg 1)
3847 (setq done t)))))))
3849 (defun move-beginning-of-line (arg)
3850 "Move point to beginning of current line as displayed.
3851 \(If there's an image in the line, this disregards newlines
3852 which are part of the text that the image rests on.)
3854 With argument ARG not nil or 1, move forward ARG - 1 lines first.
3855 If point reaches the beginning or end of buffer, it stops there.
3856 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
3857 (interactive "p")
3858 (or arg (setq arg 1))
3860 (let ((orig (point))
3861 start first-vis first-vis-field-value)
3863 ;; Move by lines, if ARG is not 1 (the default).
3864 (if (/= arg 1)
3865 (line-move (1- arg) t))
3867 ;; Move to beginning-of-line, ignoring fields and invisibles.
3868 (skip-chars-backward "^\n")
3869 (while (and (not (bobp)) (invisible-p (1- (point))))
3870 (goto-char (previous-char-property-change (point)))
3871 (skip-chars-backward "^\n"))
3872 (setq start (point))
3874 ;; Now find first visible char in the line
3875 (while (and (not (eobp)) (invisible-p (point)))
3876 (goto-char (next-char-property-change (point))))
3877 (setq first-vis (point))
3879 ;; See if fields would stop us from reaching FIRST-VIS.
3880 (setq first-vis-field-value
3881 (constrain-to-field first-vis orig (/= arg 1) t nil))
3883 (goto-char (if (/= first-vis-field-value first-vis)
3884 ;; If yes, obey them.
3885 first-vis-field-value
3886 ;; Otherwise, move to START with attention to fields.
3887 ;; (It is possible that fields never matter in this case.)
3888 (constrain-to-field (point) orig
3889 (/= arg 1) t nil)))))
3892 ;;; Many people have said they rarely use this feature, and often type
3893 ;;; it by accident. Maybe it shouldn't even be on a key.
3894 (put 'set-goal-column 'disabled t)
3896 (defun set-goal-column (arg)
3897 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
3898 Those commands will move to this position in the line moved to
3899 rather than trying to keep the same horizontal position.
3900 With a non-nil argument, clears out the goal column
3901 so that \\[next-line] and \\[previous-line] resume vertical motion.
3902 The goal column is stored in the variable `goal-column'."
3903 (interactive "P")
3904 (if arg
3905 (progn
3906 (setq goal-column nil)
3907 (message "No goal column"))
3908 (setq goal-column (current-column))
3909 ;; The older method below can be erroneous if `set-goal-column' is bound
3910 ;; to a sequence containing %
3911 ;;(message (substitute-command-keys
3912 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
3913 ;;goal-column)
3914 (message "%s"
3915 (concat
3916 (format "Goal column %d " goal-column)
3917 (substitute-command-keys
3918 "(use \\[set-goal-column] with an arg to unset it)")))
3921 nil)
3924 (defun scroll-other-window-down (lines)
3925 "Scroll the \"other window\" down.
3926 For more details, see the documentation for `scroll-other-window'."
3927 (interactive "P")
3928 (scroll-other-window
3929 ;; Just invert the argument's meaning.
3930 ;; We can do that without knowing which window it will be.
3931 (if (eq lines '-) nil
3932 (if (null lines) '-
3933 (- (prefix-numeric-value lines))))))
3935 (defun beginning-of-buffer-other-window (arg)
3936 "Move point to the beginning of the buffer in the other window.
3937 Leave mark at previous position.
3938 With arg N, put point N/10 of the way from the true beginning."
3939 (interactive "P")
3940 (let ((orig-window (selected-window))
3941 (window (other-window-for-scrolling)))
3942 ;; We use unwind-protect rather than save-window-excursion
3943 ;; because the latter would preserve the things we want to change.
3944 (unwind-protect
3945 (progn
3946 (select-window window)
3947 ;; Set point and mark in that window's buffer.
3948 (with-no-warnings
3949 (beginning-of-buffer arg))
3950 ;; Set point accordingly.
3951 (recenter '(t)))
3952 (select-window orig-window))))
3954 (defun end-of-buffer-other-window (arg)
3955 "Move point to the end of the buffer in the other window.
3956 Leave mark at previous position.
3957 With arg N, put point N/10 of the way from the true end."
3958 (interactive "P")
3959 ;; See beginning-of-buffer-other-window for comments.
3960 (let ((orig-window (selected-window))
3961 (window (other-window-for-scrolling)))
3962 (unwind-protect
3963 (progn
3964 (select-window window)
3965 (with-no-warnings
3966 (end-of-buffer arg))
3967 (recenter '(t)))
3968 (select-window orig-window))))
3970 (defun transpose-chars (arg)
3971 "Interchange characters around point, moving forward one character.
3972 With prefix arg ARG, effect is to take character before point
3973 and drag it forward past ARG other characters (backward if ARG negative).
3974 If no argument and at end of line, the previous two chars are exchanged."
3975 (interactive "*P")
3976 (and (null arg) (eolp) (forward-char -1))
3977 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3979 (defun transpose-words (arg)
3980 "Interchange words around point, leaving point at end of them.
3981 With prefix arg ARG, effect is to take word before or around point
3982 and drag it forward past ARG other words (backward if ARG negative).
3983 If ARG is zero, the words around or after point and around or after mark
3984 are interchanged."
3985 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
3986 (interactive "*p")
3987 (transpose-subr 'forward-word arg))
3989 (defun transpose-sexps (arg)
3990 "Like \\[transpose-words] but applies to sexps.
3991 Does not work on a sexp that point is in the middle of
3992 if it is a list or string."
3993 (interactive "*p")
3994 (transpose-subr
3995 (lambda (arg)
3996 ;; Here we should try to simulate the behavior of
3997 ;; (cons (progn (forward-sexp x) (point))
3998 ;; (progn (forward-sexp (- x)) (point)))
3999 ;; Except that we don't want to rely on the second forward-sexp
4000 ;; putting us back to where we want to be, since forward-sexp-function
4001 ;; might do funny things like infix-precedence.
4002 (if (if (> arg 0)
4003 (looking-at "\\sw\\|\\s_")
4004 (and (not (bobp))
4005 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
4006 ;; Jumping over a symbol. We might be inside it, mind you.
4007 (progn (funcall (if (> arg 0)
4008 'skip-syntax-backward 'skip-syntax-forward)
4009 "w_")
4010 (cons (save-excursion (forward-sexp arg) (point)) (point)))
4011 ;; Otherwise, we're between sexps. Take a step back before jumping
4012 ;; to make sure we'll obey the same precedence no matter which direction
4013 ;; we're going.
4014 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
4015 (cons (save-excursion (forward-sexp arg) (point))
4016 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
4017 (not (zerop (funcall (if (> arg 0)
4018 'skip-syntax-forward
4019 'skip-syntax-backward)
4020 ".")))))
4021 (point)))))
4022 arg 'special))
4024 (defun transpose-lines (arg)
4025 "Exchange current line and previous line, leaving point after both.
4026 With argument ARG, takes previous line and moves it past ARG lines.
4027 With argument 0, interchanges line point is in with line mark is in."
4028 (interactive "*p")
4029 (transpose-subr (function
4030 (lambda (arg)
4031 (if (> arg 0)
4032 (progn
4033 ;; Move forward over ARG lines,
4034 ;; but create newlines if necessary.
4035 (setq arg (forward-line arg))
4036 (if (/= (preceding-char) ?\n)
4037 (setq arg (1+ arg)))
4038 (if (> arg 0)
4039 (newline arg)))
4040 (forward-line arg))))
4041 arg))
4043 (defun transpose-subr (mover arg &optional special)
4044 (let ((aux (if special mover
4045 (lambda (x)
4046 (cons (progn (funcall mover x) (point))
4047 (progn (funcall mover (- x)) (point))))))
4048 pos1 pos2)
4049 (cond
4050 ((= arg 0)
4051 (save-excursion
4052 (setq pos1 (funcall aux 1))
4053 (goto-char (mark))
4054 (setq pos2 (funcall aux 1))
4055 (transpose-subr-1 pos1 pos2))
4056 (exchange-point-and-mark))
4057 ((> arg 0)
4058 (setq pos1 (funcall aux -1))
4059 (setq pos2 (funcall aux arg))
4060 (transpose-subr-1 pos1 pos2)
4061 (goto-char (car pos2)))
4063 (setq pos1 (funcall aux -1))
4064 (goto-char (car pos1))
4065 (setq pos2 (funcall aux arg))
4066 (transpose-subr-1 pos1 pos2)))))
4068 (defun transpose-subr-1 (pos1 pos2)
4069 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
4070 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
4071 (when (> (car pos1) (car pos2))
4072 (let ((swap pos1))
4073 (setq pos1 pos2 pos2 swap)))
4074 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
4075 (atomic-change-group
4076 (let (word2)
4077 ;; FIXME: We first delete the two pieces of text, so markers that
4078 ;; used to point to after the text end up pointing to before it :-(
4079 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
4080 (goto-char (car pos2))
4081 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
4082 (goto-char (car pos1))
4083 (insert word2))))
4085 (defun backward-word (&optional arg)
4086 "Move backward until encountering the beginning of a word.
4087 With argument, do this that many times."
4088 (interactive "p")
4089 (forward-word (- (or arg 1))))
4091 (defun mark-word (&optional arg allow-extend)
4092 "Set mark ARG words away from point.
4093 The place mark goes is the same place \\[forward-word] would
4094 move to with the same argument.
4095 Interactively, if this command is repeated
4096 or (in Transient Mark mode) if the mark is active,
4097 it marks the next ARG words after the ones already marked."
4098 (interactive "P\np")
4099 (cond ((and allow-extend
4100 (or (and (eq last-command this-command) (mark t))
4101 (and transient-mark-mode mark-active)))
4102 (setq arg (if arg (prefix-numeric-value arg)
4103 (if (< (mark) (point)) -1 1)))
4104 (set-mark
4105 (save-excursion
4106 (goto-char (mark))
4107 (forward-word arg)
4108 (point))))
4110 (push-mark
4111 (save-excursion
4112 (forward-word (prefix-numeric-value arg))
4113 (point))
4114 nil t))))
4116 (defun kill-word (arg)
4117 "Kill characters forward until encountering the end of a word.
4118 With argument, do this that many times."
4119 (interactive "p")
4120 (kill-region (point) (progn (forward-word arg) (point))))
4122 (defun backward-kill-word (arg)
4123 "Kill characters backward until encountering the beginning of a word.
4124 With argument, do this that many times."
4125 (interactive "p")
4126 (kill-word (- arg)))
4128 (defun current-word (&optional strict really-word)
4129 "Return the symbol or word that point is on (or a nearby one) as a string.
4130 The return value includes no text properties.
4131 If optional arg STRICT is non-nil, return nil unless point is within
4132 or adjacent to a symbol or word. In all cases the value can be nil
4133 if there is no word nearby.
4134 The function, belying its name, normally finds a symbol.
4135 If optional arg REALLY-WORD is non-nil, it finds just a word."
4136 (save-excursion
4137 (let* ((oldpoint (point)) (start (point)) (end (point))
4138 (syntaxes (if really-word "w" "w_"))
4139 (not-syntaxes (concat "^" syntaxes)))
4140 (skip-syntax-backward syntaxes) (setq start (point))
4141 (goto-char oldpoint)
4142 (skip-syntax-forward syntaxes) (setq end (point))
4143 (when (and (eq start oldpoint) (eq end oldpoint)
4144 ;; Point is neither within nor adjacent to a word.
4145 (not strict))
4146 ;; Look for preceding word in same line.
4147 (skip-syntax-backward not-syntaxes
4148 (save-excursion (beginning-of-line)
4149 (point)))
4150 (if (bolp)
4151 ;; No preceding word in same line.
4152 ;; Look for following word in same line.
4153 (progn
4154 (skip-syntax-forward not-syntaxes
4155 (save-excursion (end-of-line)
4156 (point)))
4157 (setq start (point))
4158 (skip-syntax-forward syntaxes)
4159 (setq end (point)))
4160 (setq end (point))
4161 (skip-syntax-backward syntaxes)
4162 (setq start (point))))
4163 ;; If we found something nonempty, return it as a string.
4164 (unless (= start end)
4165 (buffer-substring-no-properties start end)))))
4167 (defcustom fill-prefix nil
4168 "*String for filling to insert at front of new line, or nil for none."
4169 :type '(choice (const :tag "None" nil)
4170 string)
4171 :group 'fill)
4172 (make-variable-buffer-local 'fill-prefix)
4173 ;;;###autoload(put 'fill-prefix 'safe-local-variable 'string-or-null-p)
4175 (defcustom auto-fill-inhibit-regexp nil
4176 "*Regexp to match lines which should not be auto-filled."
4177 :type '(choice (const :tag "None" nil)
4178 regexp)
4179 :group 'fill)
4181 (defvar comment-line-break-function 'comment-indent-new-line
4182 "*Mode-specific function which line breaks and continues a comment.
4184 This function is only called during auto-filling of a comment section.
4185 The function should take a single optional argument, which is a flag
4186 indicating whether it should use soft newlines.")
4188 ;; This function is used as the auto-fill-function of a buffer
4189 ;; when Auto-Fill mode is enabled.
4190 ;; It returns t if it really did any work.
4191 ;; (Actually some major modes use a different auto-fill function,
4192 ;; but this one is the default one.)
4193 (defun do-auto-fill ()
4194 (let (fc justify give-up
4195 (fill-prefix fill-prefix))
4196 (if (or (not (setq justify (current-justification)))
4197 (null (setq fc (current-fill-column)))
4198 (and (eq justify 'left)
4199 (<= (current-column) fc))
4200 (and auto-fill-inhibit-regexp
4201 (save-excursion (beginning-of-line)
4202 (looking-at auto-fill-inhibit-regexp))))
4203 nil ;; Auto-filling not required
4204 (if (memq justify '(full center right))
4205 (save-excursion (unjustify-current-line)))
4207 ;; Choose a fill-prefix automatically.
4208 (when (and adaptive-fill-mode
4209 (or (null fill-prefix) (string= fill-prefix "")))
4210 (let ((prefix
4211 (fill-context-prefix
4212 (save-excursion (backward-paragraph 1) (point))
4213 (save-excursion (forward-paragraph 1) (point)))))
4214 (and prefix (not (equal prefix ""))
4215 ;; Use auto-indentation rather than a guessed empty prefix.
4216 (not (and fill-indent-according-to-mode
4217 (string-match "\\`[ \t]*\\'" prefix)))
4218 (setq fill-prefix prefix))))
4220 (while (and (not give-up) (> (current-column) fc))
4221 ;; Determine where to split the line.
4222 (let* (after-prefix
4223 (fill-point
4224 (save-excursion
4225 (beginning-of-line)
4226 (setq after-prefix (point))
4227 (and fill-prefix
4228 (looking-at (regexp-quote fill-prefix))
4229 (setq after-prefix (match-end 0)))
4230 (move-to-column (1+ fc))
4231 (fill-move-to-break-point after-prefix)
4232 (point))))
4234 ;; See whether the place we found is any good.
4235 (if (save-excursion
4236 (goto-char fill-point)
4237 (or (bolp)
4238 ;; There is no use breaking at end of line.
4239 (save-excursion (skip-chars-forward " ") (eolp))
4240 ;; It is futile to split at the end of the prefix
4241 ;; since we would just insert the prefix again.
4242 (and after-prefix (<= (point) after-prefix))
4243 ;; Don't split right after a comment starter
4244 ;; since we would just make another comment starter.
4245 (and comment-start-skip
4246 (let ((limit (point)))
4247 (beginning-of-line)
4248 (and (re-search-forward comment-start-skip
4249 limit t)
4250 (eq (point) limit))))))
4251 ;; No good place to break => stop trying.
4252 (setq give-up t)
4253 ;; Ok, we have a useful place to break the line. Do it.
4254 (let ((prev-column (current-column)))
4255 ;; If point is at the fill-point, do not `save-excursion'.
4256 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
4257 ;; point will end up before it rather than after it.
4258 (if (save-excursion
4259 (skip-chars-backward " \t")
4260 (= (point) fill-point))
4261 (funcall comment-line-break-function t)
4262 (save-excursion
4263 (goto-char fill-point)
4264 (funcall comment-line-break-function t)))
4265 ;; Now do justification, if required
4266 (if (not (eq justify 'left))
4267 (save-excursion
4268 (end-of-line 0)
4269 (justify-current-line justify nil t)))
4270 ;; If making the new line didn't reduce the hpos of
4271 ;; the end of the line, then give up now;
4272 ;; trying again will not help.
4273 (if (>= (current-column) prev-column)
4274 (setq give-up t))))))
4275 ;; Justify last line.
4276 (justify-current-line justify t t)
4277 t)))
4279 (defvar normal-auto-fill-function 'do-auto-fill
4280 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
4281 Some major modes set this.")
4283 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
4284 ;; FIXME: turn into a proper minor mode.
4285 ;; Add a global minor mode version of it.
4286 (defun auto-fill-mode (&optional arg)
4287 "Toggle Auto Fill mode.
4288 With arg, turn Auto Fill mode on if and only if arg is positive.
4289 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
4290 automatically breaks the line at a previous space.
4292 The value of `normal-auto-fill-function' specifies the function to use
4293 for `auto-fill-function' when turning Auto Fill mode on."
4294 (interactive "P")
4295 (prog1 (setq auto-fill-function
4296 (if (if (null arg)
4297 (not auto-fill-function)
4298 (> (prefix-numeric-value arg) 0))
4299 normal-auto-fill-function
4300 nil))
4301 (force-mode-line-update)))
4303 ;; This holds a document string used to document auto-fill-mode.
4304 (defun auto-fill-function ()
4305 "Automatically break line at a previous space, in insertion of text."
4306 nil)
4308 (defun turn-on-auto-fill ()
4309 "Unconditionally turn on Auto Fill mode."
4310 (auto-fill-mode 1))
4312 (defun turn-off-auto-fill ()
4313 "Unconditionally turn off Auto Fill mode."
4314 (auto-fill-mode -1))
4316 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
4318 (defun set-fill-column (arg)
4319 "Set `fill-column' to specified argument.
4320 Use \\[universal-argument] followed by a number to specify a column.
4321 Just \\[universal-argument] as argument means to use the current column."
4322 (interactive "P")
4323 (if (consp arg)
4324 (setq arg (current-column)))
4325 (if (not (integerp arg))
4326 ;; Disallow missing argument; it's probably a typo for C-x C-f.
4327 (error "set-fill-column requires an explicit argument")
4328 (message "Fill column set to %d (was %d)" arg fill-column)
4329 (setq fill-column arg)))
4331 (defun set-selective-display (arg)
4332 "Set `selective-display' to ARG; clear it if no arg.
4333 When the value of `selective-display' is a number > 0,
4334 lines whose indentation is >= that value are not displayed.
4335 The variable `selective-display' has a separate value for each buffer."
4336 (interactive "P")
4337 (if (eq selective-display t)
4338 (error "selective-display already in use for marked lines"))
4339 (let ((current-vpos
4340 (save-restriction
4341 (narrow-to-region (point-min) (point))
4342 (goto-char (window-start))
4343 (vertical-motion (window-height)))))
4344 (setq selective-display
4345 (and arg (prefix-numeric-value arg)))
4346 (recenter current-vpos))
4347 (set-window-start (selected-window) (window-start (selected-window)))
4348 (princ "selective-display set to " t)
4349 (prin1 selective-display t)
4350 (princ "." t))
4352 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
4353 (defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
4355 (defun toggle-truncate-lines (&optional arg)
4356 "Toggle whether to fold or truncate long lines for the current buffer.
4357 With prefix argument ARG, truncate long lines if ARG is positive,
4358 otherwise don't truncate them. Note that in side-by-side
4359 windows, truncation is always enabled."
4360 (interactive "P")
4361 (setq truncate-lines
4362 (if (null arg)
4363 (not truncate-lines)
4364 (> (prefix-numeric-value arg) 0)))
4365 (force-mode-line-update)
4366 (unless truncate-lines
4367 (let ((buffer (current-buffer)))
4368 (walk-windows (lambda (window)
4369 (if (eq buffer (window-buffer window))
4370 (set-window-hscroll window 0)))
4371 nil t)))
4372 (message "Truncate long lines %s"
4373 (if truncate-lines "enabled" "disabled")))
4375 (defvar overwrite-mode-textual " Ovwrt"
4376 "The string displayed in the mode line when in overwrite mode.")
4377 (defvar overwrite-mode-binary " Bin Ovwrt"
4378 "The string displayed in the mode line when in binary overwrite mode.")
4380 (defun overwrite-mode (arg)
4381 "Toggle overwrite mode.
4382 With prefix argument ARG, turn overwrite mode on if ARG is positive,
4383 otherwise turn it off. In overwrite mode, printing characters typed
4384 in replace existing text on a one-for-one basis, rather than pushing
4385 it to the right. At the end of a line, such characters extend the line.
4386 Before a tab, such characters insert until the tab is filled in.
4387 \\[quoted-insert] still inserts characters in overwrite mode; this
4388 is supposed to make it easier to insert characters when necessary."
4389 (interactive "P")
4390 (setq overwrite-mode
4391 (if (if (null arg) (not overwrite-mode)
4392 (> (prefix-numeric-value arg) 0))
4393 'overwrite-mode-textual))
4394 (force-mode-line-update))
4396 (defun binary-overwrite-mode (arg)
4397 "Toggle binary overwrite mode.
4398 With prefix argument ARG, turn binary overwrite mode on if ARG is
4399 positive, otherwise turn it off. In binary overwrite mode, printing
4400 characters typed in replace existing text. Newlines are not treated
4401 specially, so typing at the end of a line joins the line to the next,
4402 with the typed character between them. Typing before a tab character
4403 simply replaces the tab with the character typed. \\[quoted-insert]
4404 replaces the text at the cursor, just as ordinary typing characters do.
4406 Note that binary overwrite mode is not its own minor mode; it is a
4407 specialization of overwrite mode, entered by setting the
4408 `overwrite-mode' variable to `overwrite-mode-binary'."
4409 (interactive "P")
4410 (setq overwrite-mode
4411 (if (if (null arg)
4412 (not (eq overwrite-mode 'overwrite-mode-binary))
4413 (> (prefix-numeric-value arg) 0))
4414 'overwrite-mode-binary))
4415 (force-mode-line-update))
4417 (define-minor-mode line-number-mode
4418 "Toggle Line Number mode.
4419 With arg, turn Line Number mode on if arg is positive, otherwise
4420 turn it off. When Line Number mode is enabled, the line number
4421 appears in the mode line.
4423 Line numbers do not appear for very large buffers and buffers
4424 with very long lines; see variables `line-number-display-limit'
4425 and `line-number-display-limit-width'."
4426 :init-value t :global t :group 'mode-line)
4428 (define-minor-mode column-number-mode
4429 "Toggle Column Number mode.
4430 With arg, turn Column Number mode on if arg is positive,
4431 otherwise turn it off. When Column Number mode is enabled, the
4432 column number appears in the mode line."
4433 :global t :group 'mode-line)
4435 (define-minor-mode size-indication-mode
4436 "Toggle Size Indication mode.
4437 With arg, turn Size Indication mode on if arg is positive,
4438 otherwise turn it off. When Size Indication mode is enabled, the
4439 size of the accessible part of the buffer appears in the mode line."
4440 :global t :group 'mode-line)
4442 (defgroup paren-blinking nil
4443 "Blinking matching of parens and expressions."
4444 :prefix "blink-matching-"
4445 :group 'paren-matching)
4447 (defcustom blink-matching-paren t
4448 "*Non-nil means show matching open-paren when close-paren is inserted."
4449 :type 'boolean
4450 :group 'paren-blinking)
4452 (defcustom blink-matching-paren-on-screen t
4453 "*Non-nil means show matching open-paren when it is on screen.
4454 If nil, don't show it (but the open-paren can still be shown
4455 when it is off screen).
4457 This variable has no effect if `blink-matching-paren' is nil.
4458 \(In that case, the open-paren is never shown.)
4459 It is also ignored if `show-paren-mode' is enabled."
4460 :type 'boolean
4461 :group 'paren-blinking)
4463 (defcustom blink-matching-paren-distance (* 25 1024)
4464 "*If non-nil, maximum distance to search backwards for matching open-paren.
4465 If nil, search stops at the beginning of the accessible portion of the buffer."
4466 :type '(choice (const nil) integer)
4467 :group 'paren-blinking)
4469 (defcustom blink-matching-delay 1
4470 "*Time in seconds to delay after showing a matching paren."
4471 :type 'number
4472 :group 'paren-blinking)
4474 (defcustom blink-matching-paren-dont-ignore-comments nil
4475 "*If nil, `blink-matching-paren' ignores comments.
4476 More precisely, when looking for the matching parenthesis,
4477 it skips the contents of comments that end before point."
4478 :type 'boolean
4479 :group 'paren-blinking)
4481 (defun blink-matching-open ()
4482 "Move cursor momentarily to the beginning of the sexp before point."
4483 (interactive)
4484 (when (and (> (point) (point-min))
4485 blink-matching-paren
4486 ;; Verify an even number of quoting characters precede the close.
4487 (= 1 (logand 1 (- (point)
4488 (save-excursion
4489 (forward-char -1)
4490 (skip-syntax-backward "/\\")
4491 (point))))))
4492 (let* ((oldpos (point))
4493 blinkpos
4494 message-log-max ; Don't log messages about paren matching.
4495 matching-paren
4496 open-paren-line-string
4497 old-start
4498 new-start
4499 isdollar)
4500 (save-excursion
4501 (save-restriction
4502 ;; Don't search for matching paren within minibuffer prompt.
4503 (setq old-start (minibuffer-prompt-end))
4504 (setq new-start
4505 (if blink-matching-paren-distance
4506 (max old-start (- (point) blink-matching-paren-distance))
4507 old-start))
4508 (narrow-to-region new-start oldpos)
4509 (condition-case ()
4510 (let ((parse-sexp-ignore-comments
4511 (and parse-sexp-ignore-comments
4512 (not blink-matching-paren-dont-ignore-comments))))
4513 (setq blinkpos (scan-sexps oldpos -1)))
4514 (error nil)))
4515 (and blinkpos
4516 ;; Not syntax '$'.
4517 (not (setq isdollar (eq (syntax-class (syntax-after blinkpos)) 8)))
4518 (setq matching-paren
4519 (let ((syntax (syntax-after blinkpos)))
4520 (and (consp syntax)
4521 (eq (syntax-class syntax) 4)
4522 (cdr syntax)))))
4523 (cond
4524 ((not blinkpos)
4525 ;; Don't complain when `$' with no blinkpos, because it
4526 ;; could just be the first one in the buffer.
4527 (unless (or (eq (syntax-class (syntax-after (1- oldpos))) 8)
4528 (and blink-matching-paren-distance
4529 (> new-start old-start))
4530 ;; When `blink-matching-paren-distance' is non-nil and we
4531 ;; didn't find a matching paren within that many characters
4532 ;; don't display a message.
4533 (message "Unmatched parenthesis"))))
4534 ;; isdollar is for:
4535 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-10/msg00871.html
4536 ((not (or isdollar
4537 (eq matching-paren (char-before oldpos))
4538 ;; The cdr might hold a new paren-class info rather than
4539 ;; a matching-char info, in which case the two CDRs
4540 ;; should match.
4541 (eq matching-paren (cdr (syntax-after (1- oldpos))))))
4542 (message "Mismatched parentheses"))
4543 ((pos-visible-in-window-p blinkpos)
4544 ;; Matching open within window, temporarily move to blinkpos but only
4545 ;; if `blink-matching-paren-on-screen' is non-nil.
4546 (and blink-matching-paren-on-screen
4547 (not show-paren-mode)
4548 (save-excursion
4549 (goto-char blinkpos)
4550 (sit-for blink-matching-delay))))
4552 (save-excursion
4553 (goto-char blinkpos)
4554 (setq open-paren-line-string
4555 ;; Show what precedes the open in its line, if anything.
4556 (if (save-excursion
4557 (skip-chars-backward " \t")
4558 (not (bolp)))
4559 (buffer-substring (line-beginning-position)
4560 (1+ blinkpos))
4561 ;; Show what follows the open in its line, if anything.
4562 (if (save-excursion
4563 (forward-char 1)
4564 (skip-chars-forward " \t")
4565 (not (eolp)))
4566 (buffer-substring blinkpos
4567 (line-end-position))
4568 ;; Otherwise show the previous nonblank line,
4569 ;; if there is one.
4570 (if (save-excursion
4571 (skip-chars-backward "\n \t")
4572 (not (bobp)))
4573 (concat
4574 (buffer-substring (progn
4575 (skip-chars-backward "\n \t")
4576 (line-beginning-position))
4577 (progn (end-of-line)
4578 (skip-chars-backward " \t")
4579 (point)))
4580 ;; Replace the newline and other whitespace with `...'.
4581 "..."
4582 (buffer-substring blinkpos (1+ blinkpos)))
4583 ;; There is nothing to show except the char itself.
4584 (buffer-substring blinkpos (1+ blinkpos)))))))
4585 (message "Matches %s"
4586 (substring-no-properties open-paren-line-string))))))))
4588 ;Turned off because it makes dbx bomb out.
4589 (setq blink-paren-function 'blink-matching-open)
4591 ;; This executes C-g typed while Emacs is waiting for a command.
4592 ;; Quitting out of a program does not go through here;
4593 ;; that happens in the QUIT macro at the C code level.
4594 (defun keyboard-quit ()
4595 "Signal a `quit' condition.
4596 During execution of Lisp code, this character causes a quit directly.
4597 At top-level, as an editor command, this simply beeps."
4598 (interactive)
4599 (deactivate-mark)
4600 (if (fboundp 'kmacro-keyboard-quit)
4601 (kmacro-keyboard-quit))
4602 (setq defining-kbd-macro nil)
4603 (signal 'quit nil))
4605 (defvar buffer-quit-function nil
4606 "Function to call to \"quit\" the current buffer, or nil if none.
4607 \\[keyboard-escape-quit] calls this function when its more local actions
4608 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
4610 (defun keyboard-escape-quit ()
4611 "Exit the current \"mode\" (in a generalized sense of the word).
4612 This command can exit an interactive command such as `query-replace',
4613 can clear out a prefix argument or a region,
4614 can get out of the minibuffer or other recursive edit,
4615 cancel the use of the current buffer (for special-purpose buffers),
4616 or go back to just one window (by deleting all but the selected window)."
4617 (interactive)
4618 (cond ((eq last-command 'mode-exited) nil)
4619 ((> (minibuffer-depth) 0)
4620 (abort-recursive-edit))
4621 (current-prefix-arg
4622 nil)
4623 ((and transient-mark-mode mark-active)
4624 (deactivate-mark))
4625 ((> (recursion-depth) 0)
4626 (exit-recursive-edit))
4627 (buffer-quit-function
4628 (funcall buffer-quit-function))
4629 ((not (one-window-p t))
4630 (delete-other-windows))
4631 ((string-match "^ \\*" (buffer-name (current-buffer)))
4632 (bury-buffer))))
4634 (defun play-sound-file (file &optional volume device)
4635 "Play sound stored in FILE.
4636 VOLUME and DEVICE correspond to the keywords of the sound
4637 specification for `play-sound'."
4638 (interactive "fPlay sound file: ")
4639 (let ((sound (list :file file)))
4640 (if volume
4641 (plist-put sound :volume volume))
4642 (if device
4643 (plist-put sound :device device))
4644 (push 'sound sound)
4645 (play-sound sound)))
4648 (defcustom read-mail-command 'rmail
4649 "*Your preference for a mail reading package.
4650 This is used by some keybindings which support reading mail.
4651 See also `mail-user-agent' concerning sending mail."
4652 :type '(choice (function-item rmail)
4653 (function-item gnus)
4654 (function-item mh-rmail)
4655 (function :tag "Other"))
4656 :version "21.1"
4657 :group 'mail)
4659 (defcustom mail-user-agent 'sendmail-user-agent
4660 "*Your preference for a mail composition package.
4661 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
4662 outgoing email message. This variable lets you specify which
4663 mail-sending package you prefer.
4665 Valid values include:
4667 `sendmail-user-agent' -- use the default Emacs Mail package.
4668 See Info node `(emacs)Sending Mail'.
4669 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
4670 See Info node `(mh-e)'.
4671 `message-user-agent' -- use the Gnus Message package.
4672 See Info node `(message)'.
4673 `gnus-user-agent' -- like `message-user-agent', but with Gnus
4674 paraphernalia, particularly the Gcc: header for
4675 archiving.
4677 Additional valid symbols may be available; check with the author of
4678 your package for details. The function should return non-nil if it
4679 succeeds.
4681 See also `read-mail-command' concerning reading mail."
4682 :type '(radio (function-item :tag "Default Emacs mail"
4683 :format "%t\n"
4684 sendmail-user-agent)
4685 (function-item :tag "Emacs interface to MH"
4686 :format "%t\n"
4687 mh-e-user-agent)
4688 (function-item :tag "Gnus Message package"
4689 :format "%t\n"
4690 message-user-agent)
4691 (function-item :tag "Gnus Message with full Gnus features"
4692 :format "%t\n"
4693 gnus-user-agent)
4694 (function :tag "Other"))
4695 :group 'mail)
4697 (define-mail-user-agent 'sendmail-user-agent
4698 'sendmail-user-agent-compose
4699 'mail-send-and-exit)
4701 (defun rfc822-goto-eoh ()
4702 ;; Go to header delimiter line in a mail message, following RFC822 rules
4703 (goto-char (point-min))
4704 (when (re-search-forward
4705 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
4706 (goto-char (match-beginning 0))))
4708 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
4709 switch-function yank-action
4710 send-actions)
4711 (if switch-function
4712 (let ((special-display-buffer-names nil)
4713 (special-display-regexps nil)
4714 (same-window-buffer-names nil)
4715 (same-window-regexps nil))
4716 (funcall switch-function "*mail*")))
4717 (let ((cc (cdr (assoc-string "cc" other-headers t)))
4718 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
4719 (body (cdr (assoc-string "body" other-headers t))))
4720 (or (mail continue to subject in-reply-to cc yank-action send-actions)
4721 continue
4722 (error "Message aborted"))
4723 (save-excursion
4724 (rfc822-goto-eoh)
4725 (while other-headers
4726 (unless (member-ignore-case (car (car other-headers))
4727 '("in-reply-to" "cc" "body"))
4728 (insert (car (car other-headers)) ": "
4729 (cdr (car other-headers))
4730 (if use-hard-newlines hard-newline "\n")))
4731 (setq other-headers (cdr other-headers)))
4732 (when body
4733 (forward-line 1)
4734 (insert body))
4735 t)))
4737 (defun compose-mail (&optional to subject other-headers continue
4738 switch-function yank-action send-actions)
4739 "Start composing a mail message to send.
4740 This uses the user's chosen mail composition package
4741 as selected with the variable `mail-user-agent'.
4742 The optional arguments TO and SUBJECT specify recipients
4743 and the initial Subject field, respectively.
4745 OTHER-HEADERS is an alist specifying additional
4746 header fields. Elements look like (HEADER . VALUE) where both
4747 HEADER and VALUE are strings.
4749 CONTINUE, if non-nil, says to continue editing a message already
4750 being composed.
4752 SWITCH-FUNCTION, if non-nil, is a function to use to
4753 switch to and display the buffer used for mail composition.
4755 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
4756 to insert the raw text of the message being replied to.
4757 It has the form (FUNCTION . ARGS). The user agent will apply
4758 FUNCTION to ARGS, to insert the raw text of the original message.
4759 \(The user agent will also run `mail-citation-hook', *after* the
4760 original text has been inserted in this way.)
4762 SEND-ACTIONS is a list of actions to call when the message is sent.
4763 Each action has the form (FUNCTION . ARGS)."
4764 (interactive
4765 (list nil nil nil current-prefix-arg))
4766 (let ((function (get mail-user-agent 'composefunc)))
4767 (funcall function to subject other-headers continue
4768 switch-function yank-action send-actions)))
4770 (defun compose-mail-other-window (&optional to subject other-headers continue
4771 yank-action send-actions)
4772 "Like \\[compose-mail], but edit the outgoing message in another window."
4773 (interactive
4774 (list nil nil nil current-prefix-arg))
4775 (compose-mail to subject other-headers continue
4776 'switch-to-buffer-other-window yank-action send-actions))
4779 (defun compose-mail-other-frame (&optional to subject other-headers continue
4780 yank-action send-actions)
4781 "Like \\[compose-mail], but edit the outgoing message in another frame."
4782 (interactive
4783 (list nil nil nil current-prefix-arg))
4784 (compose-mail to subject other-headers continue
4785 'switch-to-buffer-other-frame yank-action send-actions))
4787 (defvar set-variable-value-history nil
4788 "History of values entered with `set-variable'.
4790 Maximum length of the history list is determined by the value
4791 of `history-length', which see.")
4793 (defun set-variable (variable value &optional make-local)
4794 "Set VARIABLE to VALUE. VALUE is a Lisp object.
4795 VARIABLE should be a user option variable name, a Lisp variable
4796 meant to be customized by users. You should enter VALUE in Lisp syntax,
4797 so if you want VALUE to be a string, you must surround it with doublequotes.
4798 VALUE is used literally, not evaluated.
4800 If VARIABLE has a `variable-interactive' property, that is used as if
4801 it were the arg to `interactive' (which see) to interactively read VALUE.
4803 If VARIABLE has been defined with `defcustom', then the type information
4804 in the definition is used to check that VALUE is valid.
4806 With a prefix argument, set VARIABLE to VALUE buffer-locally."
4807 (interactive
4808 (let* ((default-var (variable-at-point))
4809 (var (if (user-variable-p default-var)
4810 (read-variable (format "Set variable (default %s): " default-var)
4811 default-var)
4812 (read-variable "Set variable: ")))
4813 (minibuffer-help-form '(describe-variable var))
4814 (prop (get var 'variable-interactive))
4815 (obsolete (car (get var 'byte-obsolete-variable)))
4816 (prompt (format "Set %s %s to value: " var
4817 (cond ((local-variable-p var)
4818 "(buffer-local)")
4819 ((or current-prefix-arg
4820 (local-variable-if-set-p var))
4821 "buffer-locally")
4822 (t "globally"))))
4823 (val (progn
4824 (when obsolete
4825 (message (concat "`%S' is obsolete; "
4826 (if (symbolp obsolete) "use `%S' instead" "%s"))
4827 var obsolete)
4828 (sit-for 3))
4829 (if prop
4830 ;; Use VAR's `variable-interactive' property
4831 ;; as an interactive spec for prompting.
4832 (call-interactively `(lambda (arg)
4833 (interactive ,prop)
4834 arg))
4835 (read
4836 (read-string prompt nil
4837 'set-variable-value-history
4838 (format "%S" (symbol-value var))))))))
4839 (list var val current-prefix-arg)))
4841 (and (custom-variable-p variable)
4842 (not (get variable 'custom-type))
4843 (custom-load-symbol variable))
4844 (let ((type (get variable 'custom-type)))
4845 (when type
4846 ;; Match with custom type.
4847 (require 'cus-edit)
4848 (setq type (widget-convert type))
4849 (unless (widget-apply type :match value)
4850 (error "Value `%S' does not match type %S of %S"
4851 value (car type) variable))))
4853 (if make-local
4854 (make-local-variable variable))
4856 (set variable value)
4858 ;; Force a thorough redisplay for the case that the variable
4859 ;; has an effect on the display, like `tab-width' has.
4860 (force-mode-line-update))
4862 ;; Define the major mode for lists of completions.
4864 (defvar completion-list-mode-map nil
4865 "Local map for completion list buffers.")
4866 (or completion-list-mode-map
4867 (let ((map (make-sparse-keymap)))
4868 (define-key map [mouse-2] 'mouse-choose-completion)
4869 (define-key map [follow-link] 'mouse-face)
4870 (define-key map [down-mouse-2] nil)
4871 (define-key map "\C-m" 'choose-completion)
4872 (define-key map "\e\e\e" 'delete-completion-window)
4873 (define-key map [left] 'previous-completion)
4874 (define-key map [right] 'next-completion)
4875 (setq completion-list-mode-map map)))
4877 ;; Completion mode is suitable only for specially formatted data.
4878 (put 'completion-list-mode 'mode-class 'special)
4880 (defvar completion-reference-buffer nil
4881 "Record the buffer that was current when the completion list was requested.
4882 This is a local variable in the completion list buffer.
4883 Initial value is nil to avoid some compiler warnings.")
4885 (defvar completion-no-auto-exit nil
4886 "Non-nil means `choose-completion-string' should never exit the minibuffer.
4887 This also applies to other functions such as `choose-completion'
4888 and `mouse-choose-completion'.")
4890 (defvar completion-base-size nil
4891 "Number of chars at beginning of minibuffer not involved in completion.
4892 This is a local variable in the completion list buffer
4893 but it talks about the buffer in `completion-reference-buffer'.
4894 If this is nil, it means to compare text to determine which part
4895 of the tail end of the buffer's text is involved in completion.")
4897 (defun delete-completion-window ()
4898 "Delete the completion list window.
4899 Go to the window from which completion was requested."
4900 (interactive)
4901 (let ((buf completion-reference-buffer))
4902 (if (one-window-p t)
4903 (if (window-dedicated-p (selected-window))
4904 (delete-frame (selected-frame)))
4905 (delete-window (selected-window))
4906 (if (get-buffer-window buf)
4907 (select-window (get-buffer-window buf))))))
4909 (defun previous-completion (n)
4910 "Move to the previous item in the completion list."
4911 (interactive "p")
4912 (next-completion (- n)))
4914 (defun next-completion (n)
4915 "Move to the next item in the completion list.
4916 With prefix argument N, move N items (negative N means move backward)."
4917 (interactive "p")
4918 (let ((beg (point-min)) (end (point-max)))
4919 (while (and (> n 0) (not (eobp)))
4920 ;; If in a completion, move to the end of it.
4921 (when (get-text-property (point) 'mouse-face)
4922 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4923 ;; Move to start of next one.
4924 (unless (get-text-property (point) 'mouse-face)
4925 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4926 (setq n (1- n)))
4927 (while (and (< n 0) (not (bobp)))
4928 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
4929 ;; If in a completion, move to the start of it.
4930 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
4931 (goto-char (previous-single-property-change
4932 (point) 'mouse-face nil beg)))
4933 ;; Move to end of the previous completion.
4934 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
4935 (goto-char (previous-single-property-change
4936 (point) 'mouse-face nil beg)))
4937 ;; Move to the start of that one.
4938 (goto-char (previous-single-property-change
4939 (point) 'mouse-face nil beg))
4940 (setq n (1+ n))))))
4942 (defun choose-completion ()
4943 "Choose the completion that point is in or next to."
4944 (interactive)
4945 (let (beg end completion (buffer completion-reference-buffer)
4946 (base-size completion-base-size))
4947 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
4948 (setq end (point) beg (1+ (point))))
4949 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
4950 (setq end (1- (point)) beg (point)))
4951 (if (null beg)
4952 (error "No completion here"))
4953 (setq beg (previous-single-property-change beg 'mouse-face))
4954 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
4955 (setq completion (buffer-substring-no-properties beg end))
4956 (let ((owindow (selected-window)))
4957 (if (and (one-window-p t 'selected-frame)
4958 (window-dedicated-p (selected-window)))
4959 ;; This is a special buffer's frame
4960 (iconify-frame (selected-frame))
4961 (or (window-dedicated-p (selected-window))
4962 (bury-buffer)))
4963 (select-window owindow))
4964 (choose-completion-string completion buffer base-size)))
4966 ;; Delete the longest partial match for STRING
4967 ;; that can be found before POINT.
4968 (defun choose-completion-delete-max-match (string)
4969 (let ((opoint (point))
4970 len)
4971 ;; Try moving back by the length of the string.
4972 (goto-char (max (- (point) (length string))
4973 (minibuffer-prompt-end)))
4974 ;; See how far back we were actually able to move. That is the
4975 ;; upper bound on how much we can match and delete.
4976 (setq len (- opoint (point)))
4977 (if completion-ignore-case
4978 (setq string (downcase string)))
4979 (while (and (> len 0)
4980 (let ((tail (buffer-substring (point) opoint)))
4981 (if completion-ignore-case
4982 (setq tail (downcase tail)))
4983 (not (string= tail (substring string 0 len)))))
4984 (setq len (1- len))
4985 (forward-char 1))
4986 (delete-char len)))
4988 (defvar choose-completion-string-functions nil
4989 "Functions that may override the normal insertion of a completion choice.
4990 These functions are called in order with four arguments:
4991 CHOICE - the string to insert in the buffer,
4992 BUFFER - the buffer in which the choice should be inserted,
4993 MINI-P - non-nil if BUFFER is a minibuffer, and
4994 BASE-SIZE - the number of characters in BUFFER before
4995 the string being completed.
4997 If a function in the list returns non-nil, that function is supposed
4998 to have inserted the CHOICE in the BUFFER, and possibly exited
4999 the minibuffer; no further functions will be called.
5001 If all functions in the list return nil, that means to use
5002 the default method of inserting the completion in BUFFER.")
5004 (defun choose-completion-string (choice &optional buffer base-size)
5005 "Switch to BUFFER and insert the completion choice CHOICE.
5006 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
5007 to keep. If it is nil, we call `choose-completion-delete-max-match'
5008 to decide what to delete."
5010 ;; If BUFFER is the minibuffer, exit the minibuffer
5011 ;; unless it is reading a file name and CHOICE is a directory,
5012 ;; or completion-no-auto-exit is non-nil.
5014 (let* ((buffer (or buffer completion-reference-buffer))
5015 (mini-p (minibufferp buffer)))
5016 ;; If BUFFER is a minibuffer, barf unless it's the currently
5017 ;; active minibuffer.
5018 (if (and mini-p
5019 (or (not (active-minibuffer-window))
5020 (not (equal buffer
5021 (window-buffer (active-minibuffer-window))))))
5022 (error "Minibuffer is not active for completion")
5023 ;; Set buffer so buffer-local choose-completion-string-functions works.
5024 (set-buffer buffer)
5025 (unless (run-hook-with-args-until-success
5026 'choose-completion-string-functions
5027 choice buffer mini-p base-size)
5028 ;; Insert the completion into the buffer where it was requested.
5029 (if base-size
5030 (delete-region (+ base-size (if mini-p
5031 (minibuffer-prompt-end)
5032 (point-min)))
5033 (point))
5034 (choose-completion-delete-max-match choice))
5035 (insert choice)
5036 (remove-text-properties (- (point) (length choice)) (point)
5037 '(mouse-face nil))
5038 ;; Update point in the window that BUFFER is showing in.
5039 (let ((window (get-buffer-window buffer t)))
5040 (set-window-point window (point)))
5041 ;; If completing for the minibuffer, exit it with this choice.
5042 (and (not completion-no-auto-exit)
5043 (equal buffer (window-buffer (minibuffer-window)))
5044 minibuffer-completion-table
5045 ;; If this is reading a file name, and the file name chosen
5046 ;; is a directory, don't exit the minibuffer.
5047 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
5048 (file-directory-p (field-string (point-max))))
5049 (let ((mini (active-minibuffer-window)))
5050 (select-window mini)
5051 (when minibuffer-auto-raise
5052 (raise-frame (window-frame mini))))
5053 (exit-minibuffer)))))))
5055 (defun completion-list-mode ()
5056 "Major mode for buffers showing lists of possible completions.
5057 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
5058 to select the completion near point.
5059 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
5060 with the mouse."
5061 (interactive)
5062 (kill-all-local-variables)
5063 (use-local-map completion-list-mode-map)
5064 (setq mode-name "Completion List")
5065 (setq major-mode 'completion-list-mode)
5066 (make-local-variable 'completion-base-size)
5067 (setq completion-base-size nil)
5068 (run-mode-hooks 'completion-list-mode-hook))
5070 (defun completion-list-mode-finish ()
5071 "Finish setup of the completions buffer.
5072 Called from `temp-buffer-show-hook'."
5073 (when (eq major-mode 'completion-list-mode)
5074 (toggle-read-only 1)))
5076 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
5078 (defvar completion-setup-hook nil
5079 "Normal hook run at the end of setting up a completion list buffer.
5080 When this hook is run, the current buffer is the one in which the
5081 command to display the completion list buffer was run.
5082 The completion list buffer is available as the value of `standard-output'.
5083 The common prefix substring for completion may be available as the
5084 value of `completion-common-substring'. See also `display-completion-list'.")
5087 ;; Variables and faces used in `completion-setup-function'.
5089 (defcustom completion-show-help t
5090 "Non-nil means show help message in *Completions* buffer."
5091 :type 'boolean
5092 :version "22.1"
5093 :group 'completion)
5095 (defface completions-first-difference
5096 '((t (:inherit bold)))
5097 "Face put on the first uncommon character in completions in *Completions* buffer."
5098 :group 'completion)
5100 (defface completions-common-part
5101 '((t (:inherit default)))
5102 "Face put on the common prefix substring in completions in *Completions* buffer.
5103 The idea of `completions-common-part' is that you can use it to
5104 make the common parts less visible than normal, so that the rest
5105 of the differing parts is, by contrast, slightly highlighted."
5106 :group 'completion)
5108 ;; This is for packages that need to bind it to a non-default regexp
5109 ;; in order to make the first-differing character highlight work
5110 ;; to their liking
5111 (defvar completion-root-regexp "^/"
5112 "Regexp to use in `completion-setup-function' to find the root directory.")
5114 (defvar completion-common-substring nil
5115 "Common prefix substring to use in `completion-setup-function' to put faces.
5116 The value is set by `display-completion-list' during running `completion-setup-hook'.
5118 To put faces `completions-first-difference' and `completions-common-part'
5119 in the `*Completions*' buffer, the common prefix substring in completions
5120 is needed as a hint. (The minibuffer is a special case. The content
5121 of the minibuffer before point is always the common substring.)")
5123 ;; This function goes in completion-setup-hook, so that it is called
5124 ;; after the text of the completion list buffer is written.
5125 (defun completion-setup-function ()
5126 (let* ((mainbuf (current-buffer))
5127 (mbuf-contents (minibuffer-completion-contents))
5128 common-string-length)
5129 ;; When reading a file name in the minibuffer,
5130 ;; set default-directory in the minibuffer
5131 ;; so it will get copied into the completion list buffer.
5132 (if minibuffer-completing-file-name
5133 (with-current-buffer mainbuf
5134 (setq default-directory
5135 (file-name-directory (expand-file-name mbuf-contents)))))
5136 (with-current-buffer standard-output
5137 (completion-list-mode)
5138 (set (make-local-variable 'completion-reference-buffer) mainbuf)
5139 (setq completion-base-size
5140 (cond
5141 ((and (symbolp minibuffer-completion-table)
5142 (get minibuffer-completion-table 'completion-base-size-function))
5143 ;; To compute base size, a function can use the global value of
5144 ;; completion-common-substring or minibuffer-completion-contents.
5145 (with-current-buffer mainbuf
5146 (funcall (get minibuffer-completion-table
5147 'completion-base-size-function))))
5148 (minibuffer-completing-file-name
5149 ;; For file name completion, use the number of chars before
5150 ;; the start of the file name component at point.
5151 (with-current-buffer mainbuf
5152 (save-excursion
5153 (skip-chars-backward completion-root-regexp)
5154 (- (point) (minibuffer-prompt-end)))))
5155 (minibuffer-completing-symbol nil)
5156 ;; Otherwise, in minibuffer, the base size is 0.
5157 ((minibufferp mainbuf) 0)))
5158 (setq common-string-length
5159 (cond
5160 (completion-common-substring
5161 (length completion-common-substring))
5162 (completion-base-size
5163 (- (length mbuf-contents) completion-base-size))))
5164 ;; Put faces on first uncommon characters and common parts.
5165 (when (and (integerp common-string-length) (>= common-string-length 0))
5166 (let ((element-start (point-min))
5167 (maxp (point-max))
5168 element-common-end)
5169 (while (and (setq element-start
5170 (next-single-property-change
5171 element-start 'mouse-face))
5172 (< (setq element-common-end
5173 (+ element-start common-string-length))
5174 maxp))
5175 (when (get-char-property element-start 'mouse-face)
5176 (if (and (> common-string-length 0)
5177 (get-char-property (1- element-common-end) 'mouse-face))
5178 (put-text-property element-start element-common-end
5179 'font-lock-face 'completions-common-part))
5180 (if (get-char-property element-common-end 'mouse-face)
5181 (put-text-property element-common-end (1+ element-common-end)
5182 'font-lock-face 'completions-first-difference))))))
5183 ;; Maybe insert help string.
5184 (when completion-show-help
5185 (goto-char (point-min))
5186 (if (display-mouse-p)
5187 (insert (substitute-command-keys
5188 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
5189 (insert (substitute-command-keys
5190 "In this buffer, type \\[choose-completion] to \
5191 select the completion near point.\n\n"))))))
5193 (add-hook 'completion-setup-hook 'completion-setup-function)
5195 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
5196 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
5198 (defun switch-to-completions ()
5199 "Select the completion list window."
5200 (interactive)
5201 ;; Make sure we have a completions window.
5202 (or (get-buffer-window "*Completions*")
5203 (minibuffer-completion-help))
5204 (let ((window (get-buffer-window "*Completions*")))
5205 (when window
5206 (select-window window)
5207 (goto-char (point-min))
5208 (search-forward "\n\n" nil t)
5209 (forward-line 1))))
5211 ;;; Support keyboard commands to turn on various modifiers.
5213 ;; These functions -- which are not commands -- each add one modifier
5214 ;; to the following event.
5216 (defun event-apply-alt-modifier (ignore-prompt)
5217 "\\<function-key-map>Add the Alt modifier to the following event.
5218 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
5219 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
5220 (defun event-apply-super-modifier (ignore-prompt)
5221 "\\<function-key-map>Add the Super modifier to the following event.
5222 For example, type \\[event-apply-super-modifier] & to enter Super-&."
5223 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
5224 (defun event-apply-hyper-modifier (ignore-prompt)
5225 "\\<function-key-map>Add the Hyper modifier to the following event.
5226 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
5227 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
5228 (defun event-apply-shift-modifier (ignore-prompt)
5229 "\\<function-key-map>Add the Shift modifier to the following event.
5230 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
5231 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
5232 (defun event-apply-control-modifier (ignore-prompt)
5233 "\\<function-key-map>Add the Ctrl modifier to the following event.
5234 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
5235 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
5236 (defun event-apply-meta-modifier (ignore-prompt)
5237 "\\<function-key-map>Add the Meta modifier to the following event.
5238 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
5239 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
5241 (defun event-apply-modifier (event symbol lshiftby prefix)
5242 "Apply a modifier flag to event EVENT.
5243 SYMBOL is the name of this modifier, as a symbol.
5244 LSHIFTBY is the numeric value of this modifier, in keyboard events.
5245 PREFIX is the string that represents this modifier in an event type symbol."
5246 (if (numberp event)
5247 (cond ((eq symbol 'control)
5248 (if (and (<= (downcase event) ?z)
5249 (>= (downcase event) ?a))
5250 (- (downcase event) ?a -1)
5251 (if (and (<= (downcase event) ?Z)
5252 (>= (downcase event) ?A))
5253 (- (downcase event) ?A -1)
5254 (logior (lsh 1 lshiftby) event))))
5255 ((eq symbol 'shift)
5256 (if (and (<= (downcase event) ?z)
5257 (>= (downcase event) ?a))
5258 (upcase event)
5259 (logior (lsh 1 lshiftby) event)))
5261 (logior (lsh 1 lshiftby) event)))
5262 (if (memq symbol (event-modifiers event))
5263 event
5264 (let ((event-type (if (symbolp event) event (car event))))
5265 (setq event-type (intern (concat prefix (symbol-name event-type))))
5266 (if (symbolp event)
5267 event-type
5268 (cons event-type (cdr event)))))))
5270 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
5271 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
5272 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
5273 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
5274 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
5275 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
5277 ;;;; Keypad support.
5279 ;;; Make the keypad keys act like ordinary typing keys. If people add
5280 ;;; bindings for the function key symbols, then those bindings will
5281 ;;; override these, so this shouldn't interfere with any existing
5282 ;;; bindings.
5284 ;; Also tell read-char how to handle these keys.
5285 (mapc
5286 (lambda (keypad-normal)
5287 (let ((keypad (nth 0 keypad-normal))
5288 (normal (nth 1 keypad-normal)))
5289 (put keypad 'ascii-character normal)
5290 (define-key function-key-map (vector keypad) (vector normal))))
5291 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
5292 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
5293 (kp-space ?\s)
5294 (kp-tab ?\t)
5295 (kp-enter ?\r)
5296 (kp-multiply ?*)
5297 (kp-add ?+)
5298 (kp-separator ?,)
5299 (kp-subtract ?-)
5300 (kp-decimal ?.)
5301 (kp-divide ?/)
5302 (kp-equal ?=)))
5304 ;;;;
5305 ;;;; forking a twin copy of a buffer.
5306 ;;;;
5308 (defvar clone-buffer-hook nil
5309 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
5311 (defun clone-process (process &optional newname)
5312 "Create a twin copy of PROCESS.
5313 If NEWNAME is nil, it defaults to PROCESS' name;
5314 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
5315 If PROCESS is associated with a buffer, the new process will be associated
5316 with the current buffer instead.
5317 Returns nil if PROCESS has already terminated."
5318 (setq newname (or newname (process-name process)))
5319 (if (string-match "<[0-9]+>\\'" newname)
5320 (setq newname (substring newname 0 (match-beginning 0))))
5321 (when (memq (process-status process) '(run stop open))
5322 (let* ((process-connection-type (process-tty-name process))
5323 (new-process
5324 (if (memq (process-status process) '(open))
5325 (let ((args (process-contact process t)))
5326 (setq args (plist-put args :name newname))
5327 (setq args (plist-put args :buffer
5328 (if (process-buffer process)
5329 (current-buffer))))
5330 (apply 'make-network-process args))
5331 (apply 'start-process newname
5332 (if (process-buffer process) (current-buffer))
5333 (process-command process)))))
5334 (set-process-query-on-exit-flag
5335 new-process (process-query-on-exit-flag process))
5336 (set-process-inherit-coding-system-flag
5337 new-process (process-inherit-coding-system-flag process))
5338 (set-process-filter new-process (process-filter process))
5339 (set-process-sentinel new-process (process-sentinel process))
5340 (set-process-plist new-process (copy-sequence (process-plist process)))
5341 new-process)))
5343 ;; things to maybe add (currently partly covered by `funcall mode'):
5344 ;; - syntax-table
5345 ;; - overlays
5346 (defun clone-buffer (&optional newname display-flag)
5347 "Create and return a twin copy of the current buffer.
5348 Unlike an indirect buffer, the new buffer can be edited
5349 independently of the old one (if it is not read-only).
5350 NEWNAME is the name of the new buffer. It may be modified by
5351 adding or incrementing <N> at the end as necessary to create a
5352 unique buffer name. If nil, it defaults to the name of the
5353 current buffer, with the proper suffix. If DISPLAY-FLAG is
5354 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
5355 clone a file-visiting buffer, or a buffer whose major mode symbol
5356 has a non-nil `no-clone' property, results in an error.
5358 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
5359 current buffer with appropriate suffix. However, if a prefix
5360 argument is given, then the command prompts for NEWNAME in the
5361 minibuffer.
5363 This runs the normal hook `clone-buffer-hook' in the new buffer
5364 after it has been set up properly in other respects."
5365 (interactive
5366 (progn
5367 (if buffer-file-name
5368 (error "Cannot clone a file-visiting buffer"))
5369 (if (get major-mode 'no-clone)
5370 (error "Cannot clone a buffer in %s mode" mode-name))
5371 (list (if current-prefix-arg
5372 (read-buffer "Name of new cloned buffer: " (current-buffer)))
5373 t)))
5374 (if buffer-file-name
5375 (error "Cannot clone a file-visiting buffer"))
5376 (if (get major-mode 'no-clone)
5377 (error "Cannot clone a buffer in %s mode" mode-name))
5378 (setq newname (or newname (buffer-name)))
5379 (if (string-match "<[0-9]+>\\'" newname)
5380 (setq newname (substring newname 0 (match-beginning 0))))
5381 (let ((buf (current-buffer))
5382 (ptmin (point-min))
5383 (ptmax (point-max))
5384 (pt (point))
5385 (mk (if mark-active (mark t)))
5386 (modified (buffer-modified-p))
5387 (mode major-mode)
5388 (lvars (buffer-local-variables))
5389 (process (get-buffer-process (current-buffer)))
5390 (new (generate-new-buffer (or newname (buffer-name)))))
5391 (save-restriction
5392 (widen)
5393 (with-current-buffer new
5394 (insert-buffer-substring buf)))
5395 (with-current-buffer new
5396 (narrow-to-region ptmin ptmax)
5397 (goto-char pt)
5398 (if mk (set-mark mk))
5399 (set-buffer-modified-p modified)
5401 ;; Clone the old buffer's process, if any.
5402 (when process (clone-process process))
5404 ;; Now set up the major mode.
5405 (funcall mode)
5407 ;; Set up other local variables.
5408 (mapcar (lambda (v)
5409 (condition-case () ;in case var is read-only
5410 (if (symbolp v)
5411 (makunbound v)
5412 (set (make-local-variable (car v)) (cdr v)))
5413 (error nil)))
5414 lvars)
5416 ;; Run any hooks (typically set up by the major mode
5417 ;; for cloning to work properly).
5418 (run-hooks 'clone-buffer-hook))
5419 (if display-flag
5420 ;; Presumably the current buffer is shown in the selected frame, so
5421 ;; we want to display the clone elsewhere.
5422 (let ((same-window-regexps nil)
5423 (same-window-buffer-names))
5424 (pop-to-buffer new)))
5425 new))
5428 (defun clone-indirect-buffer (newname display-flag &optional norecord)
5429 "Create an indirect buffer that is a twin copy of the current buffer.
5431 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
5432 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
5433 or if not called with a prefix arg, NEWNAME defaults to the current
5434 buffer's name. The name is modified by adding a `<N>' suffix to it
5435 or by incrementing the N in an existing suffix.
5437 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
5438 This is always done when called interactively.
5440 Optional third arg NORECORD non-nil means do not put this buffer at the
5441 front of the list of recently selected ones."
5442 (interactive
5443 (progn
5444 (if (get major-mode 'no-clone-indirect)
5445 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5446 (list (if current-prefix-arg
5447 (read-buffer "Name of indirect buffer: " (current-buffer)))
5448 t)))
5449 (if (get major-mode 'no-clone-indirect)
5450 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5451 (setq newname (or newname (buffer-name)))
5452 (if (string-match "<[0-9]+>\\'" newname)
5453 (setq newname (substring newname 0 (match-beginning 0))))
5454 (let* ((name (generate-new-buffer-name newname))
5455 (buffer (make-indirect-buffer (current-buffer) name t)))
5456 (when display-flag
5457 (pop-to-buffer buffer norecord))
5458 buffer))
5461 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
5462 "Like `clone-indirect-buffer' but display in another window."
5463 (interactive
5464 (progn
5465 (if (get major-mode 'no-clone-indirect)
5466 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5467 (list (if current-prefix-arg
5468 (read-buffer "Name of indirect buffer: " (current-buffer)))
5469 t)))
5470 (let ((pop-up-windows t))
5471 (clone-indirect-buffer newname display-flag norecord)))
5474 ;;; Handling of Backspace and Delete keys.
5476 (defcustom normal-erase-is-backspace
5477 (and (not noninteractive)
5478 (or (memq system-type '(ms-dos windows-nt))
5479 (eq window-system 'mac)
5480 (and (memq window-system '(x))
5481 (fboundp 'x-backspace-delete-keys-p)
5482 (x-backspace-delete-keys-p))
5483 ;; If the terminal Emacs is running on has erase char
5484 ;; set to ^H, use the Backspace key for deleting
5485 ;; backward and, and the Delete key for deleting forward.
5486 (and (null window-system)
5487 (eq tty-erase-char ?\^H))))
5488 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
5490 On window systems, the default value of this option is chosen
5491 according to the keyboard used. If the keyboard has both a Backspace
5492 key and a Delete key, and both are mapped to their usual meanings, the
5493 option's default value is set to t, so that Backspace can be used to
5494 delete backward, and Delete can be used to delete forward.
5496 If not running under a window system, customizing this option accomplishes
5497 a similar effect by mapping C-h, which is usually generated by the
5498 Backspace key, to DEL, and by mapping DEL to C-d via
5499 `keyboard-translate'. The former functionality of C-h is available on
5500 the F1 key. You should probably not use this setting if you don't
5501 have both Backspace, Delete and F1 keys.
5503 Setting this variable with setq doesn't take effect. Programmatically,
5504 call `normal-erase-is-backspace-mode' (which see) instead."
5505 :type 'boolean
5506 :group 'editing-basics
5507 :version "21.1"
5508 :set (lambda (symbol value)
5509 ;; The fboundp is because of a problem with :set when
5510 ;; dumping Emacs. It doesn't really matter.
5511 (if (fboundp 'normal-erase-is-backspace-mode)
5512 (normal-erase-is-backspace-mode (or value 0))
5513 (set-default symbol value))))
5516 (defun normal-erase-is-backspace-mode (&optional arg)
5517 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
5519 With numeric arg, turn the mode on if and only if ARG is positive.
5521 On window systems, when this mode is on, Delete is mapped to C-d and
5522 Backspace is mapped to DEL; when this mode is off, both Delete and
5523 Backspace are mapped to DEL. (The remapping goes via
5524 `function-key-map', so binding Delete or Backspace in the global or
5525 local keymap will override that.)
5527 In addition, on window systems, the bindings of C-Delete, M-Delete,
5528 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
5529 the global keymap in accordance with the functionality of Delete and
5530 Backspace. For example, if Delete is remapped to C-d, which deletes
5531 forward, C-Delete is bound to `kill-word', but if Delete is remapped
5532 to DEL, which deletes backward, C-Delete is bound to
5533 `backward-kill-word'.
5535 If not running on a window system, a similar effect is accomplished by
5536 remapping C-h (normally produced by the Backspace key) and DEL via
5537 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
5538 to C-d; if it's off, the keys are not remapped.
5540 When not running on a window system, and this mode is turned on, the
5541 former functionality of C-h is available on the F1 key. You should
5542 probably not turn on this mode on a text-only terminal if you don't
5543 have both Backspace, Delete and F1 keys.
5545 See also `normal-erase-is-backspace'."
5546 (interactive "P")
5547 (setq normal-erase-is-backspace
5548 (if arg
5549 (> (prefix-numeric-value arg) 0)
5550 (not normal-erase-is-backspace)))
5552 (cond ((or (memq window-system '(x w32 mac pc))
5553 (memq system-type '(ms-dos windows-nt)))
5554 (let ((bindings
5555 `(([C-delete] [C-backspace])
5556 ([M-delete] [M-backspace])
5557 ([C-M-delete] [C-M-backspace])
5558 (,esc-map
5559 [C-delete] [C-backspace])))
5560 (old-state (lookup-key function-key-map [delete])))
5562 (if normal-erase-is-backspace
5563 (progn
5564 (define-key function-key-map [delete] [?\C-d])
5565 (define-key function-key-map [kp-delete] [?\C-d])
5566 (define-key function-key-map [backspace] [?\C-?]))
5567 (define-key function-key-map [delete] [?\C-?])
5568 (define-key function-key-map [kp-delete] [?\C-?])
5569 (define-key function-key-map [backspace] [?\C-?]))
5571 ;; Maybe swap bindings of C-delete and C-backspace, etc.
5572 (unless (equal old-state (lookup-key function-key-map [delete]))
5573 (dolist (binding bindings)
5574 (let ((map global-map))
5575 (when (keymapp (car binding))
5576 (setq map (car binding) binding (cdr binding)))
5577 (let* ((key1 (nth 0 binding))
5578 (key2 (nth 1 binding))
5579 (binding1 (lookup-key map key1))
5580 (binding2 (lookup-key map key2)))
5581 (define-key map key1 binding2)
5582 (define-key map key2 binding1)))))))
5584 (if normal-erase-is-backspace
5585 (progn
5586 (keyboard-translate ?\C-h ?\C-?)
5587 (keyboard-translate ?\C-? ?\C-d))
5588 (keyboard-translate ?\C-h ?\C-h)
5589 (keyboard-translate ?\C-? ?\C-?))))
5591 (run-hooks 'normal-erase-is-backspace-hook)
5592 (if (interactive-p)
5593 (message "Delete key deletes %s"
5594 (if normal-erase-is-backspace "forward" "backward"))))
5596 (defvar vis-mode-saved-buffer-invisibility-spec nil
5597 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
5599 (define-minor-mode visible-mode
5600 "Toggle Visible mode.
5601 With argument ARG turn Visible mode on if ARG is positive, otherwise
5602 turn it off.
5604 Enabling Visible mode makes all invisible text temporarily visible.
5605 Disabling Visible mode turns off that effect. Visible mode
5606 works by saving the value of `buffer-invisibility-spec' and setting it to nil."
5607 :lighter " Vis"
5608 :group 'editing-basics
5609 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
5610 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
5611 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
5612 (when visible-mode
5613 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
5614 buffer-invisibility-spec)
5615 (setq buffer-invisibility-spec nil)))
5617 ;; Minibuffer prompt stuff.
5619 ;(defun minibuffer-prompt-modification (start end)
5620 ; (error "You cannot modify the prompt"))
5623 ;(defun minibuffer-prompt-insertion (start end)
5624 ; (let ((inhibit-modification-hooks t))
5625 ; (delete-region start end)
5626 ; ;; Discard undo information for the text insertion itself
5627 ; ;; and for the text deletion.above.
5628 ; (when (consp buffer-undo-list)
5629 ; (setq buffer-undo-list (cddr buffer-undo-list)))
5630 ; (message "You cannot modify the prompt")))
5633 ;(setq minibuffer-prompt-properties
5634 ; (list 'modification-hooks '(minibuffer-prompt-modification)
5635 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
5639 ;;;; Problematic external packages.
5641 ;; rms says this should be done by specifying symbols that define
5642 ;; versions together with bad values. This is therefore not as
5643 ;; flexible as it could be. See the thread:
5644 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
5645 (defconst bad-packages-alist
5646 ;; Not sure exactly which semantic versions have problems.
5647 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
5648 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
5649 "The version of `semantic' loaded does not work in Emacs 22.
5650 It can cause constant high CPU load.
5651 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
5652 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
5653 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
5654 ;; provided the `CUA-mode' feature. Since this is no longer true,
5655 ;; we can warn the user if the `CUA-mode' feature is ever provided.
5656 (CUA-mode t nil
5657 "CUA-mode is now part of the standard GNU Emacs distribution,
5658 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
5660 You have loaded an older version of CUA-mode which does not work
5661 correctly with this version of Emacs. You should remove the old
5662 version and use the one distributed with Emacs."))
5663 "Alist of packages known to cause problems in this version of Emacs.
5664 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
5665 PACKAGE is either a regular expression to match file names, or a
5666 symbol (a feature name); see the documentation of
5667 `after-load-alist', to which this variable adds functions.
5668 SYMBOL is either the name of a string variable, or `t'. Upon
5669 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
5670 warning using STRING as the message.")
5672 (defun bad-package-check (package)
5673 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
5674 (condition-case nil
5675 (let* ((list (assoc package bad-packages-alist))
5676 (symbol (nth 1 list)))
5677 (and list
5678 (boundp symbol)
5679 (or (eq symbol t)
5680 (and (stringp (setq symbol (eval symbol)))
5681 (string-match (nth 2 list) symbol)))
5682 (display-warning :warning (nth 3 list))))
5683 (error nil)))
5685 (mapc (lambda (elem)
5686 (eval-after-load (car elem) `(bad-package-check ',(car elem))))
5687 bad-packages-alist)
5690 (provide 'simple)
5692 ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
5693 ;;; simple.el ends here