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