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