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