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