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