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