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