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