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