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