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