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