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