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