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