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