Backport the :end-of-capability fix
[emacs.git] / lisp / simple.el
blob497e4a1604fc47f220ee31cb69432d62d4fc36b7
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 whenever the mark is active. The mark is
4814 \"deactivated\" by changing the buffer, and after certain other
4815 operations that set the mark but whose main purpose is something
4816 else--for example, incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
4818 You can also deactivate the mark by typing \\[keyboard-quit] or
4819 \\[keyboard-escape-quit].
4821 Many commands change their behavior when Transient Mark mode is
4822 in effect and the mark is active, by acting on the region instead
4823 of their usual default part of the buffer's text. Examples of
4824 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
4825 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
4826 To see the documentation of commands which are sensitive to the
4827 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
4828 or \"mark.*active\" at the prompt."
4829 :global t
4830 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
4831 :variable transient-mark-mode)
4833 (defvar widen-automatically t
4834 "Non-nil means it is ok for commands to call `widen' when they want to.
4835 Some commands will do this in order to go to positions outside
4836 the current accessible part of the buffer.
4838 If `widen-automatically' is nil, these commands will do something else
4839 as a fallback, and won't change the buffer bounds.")
4841 (defvar non-essential nil
4842 "Whether the currently executing code is performing an essential task.
4843 This variable should be non-nil only when running code which should not
4844 disturb the user. E.g. it can be used to prevent Tramp from prompting the
4845 user for a password when we are simply scanning a set of files in the
4846 background or displaying possible completions before the user even asked
4847 for it.")
4849 (defun pop-global-mark ()
4850 "Pop off global mark ring and jump to the top location."
4851 (interactive)
4852 ;; Pop entries which refer to non-existent buffers.
4853 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
4854 (setq global-mark-ring (cdr global-mark-ring)))
4855 (or global-mark-ring
4856 (error "No global mark set"))
4857 (let* ((marker (car global-mark-ring))
4858 (buffer (marker-buffer marker))
4859 (position (marker-position marker)))
4860 (setq global-mark-ring (nconc (cdr global-mark-ring)
4861 (list (car global-mark-ring))))
4862 (set-buffer buffer)
4863 (or (and (>= position (point-min))
4864 (<= position (point-max)))
4865 (if widen-automatically
4866 (widen)
4867 (error "Global mark position is outside accessible part of buffer")))
4868 (goto-char position)
4869 (switch-to-buffer buffer)))
4871 (defcustom next-line-add-newlines nil
4872 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
4873 :type 'boolean
4874 :version "21.1"
4875 :group 'editing-basics)
4877 (defun next-line (&optional arg try-vscroll)
4878 "Move cursor vertically down ARG lines.
4879 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4880 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
4881 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
4882 function will not vscroll.
4884 ARG defaults to 1.
4886 If there is no character in the target line exactly under the current column,
4887 the cursor is positioned after the character in that line which spans this
4888 column, or at the end of the line if it is not long enough.
4889 If there is no line in the buffer after this one, behavior depends on the
4890 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
4891 to create a line, and moves the cursor to that line. Otherwise it moves the
4892 cursor to the end of the buffer.
4894 If the variable `line-move-visual' is non-nil, this command moves
4895 by display lines. Otherwise, it moves by buffer lines, without
4896 taking variable-width characters or continued lines into account.
4898 The command \\[set-goal-column] can be used to create
4899 a semipermanent goal column for this command.
4900 Then instead of trying to move exactly vertically (or as close as possible),
4901 this command moves to the specified goal column (or as close as possible).
4902 The goal column is stored in the variable `goal-column', which is nil
4903 when there is no goal column. Note that setting `goal-column'
4904 overrides `line-move-visual' and causes this command to move by buffer
4905 lines rather than by display lines.
4907 If you are thinking of using this in a Lisp program, consider
4908 using `forward-line' instead. It is usually easier to use
4909 and more reliable (no dependence on goal column, etc.)."
4910 (interactive "^p\np")
4911 (or arg (setq arg 1))
4912 (if (and next-line-add-newlines (= arg 1))
4913 (if (save-excursion (end-of-line) (eobp))
4914 ;; When adding a newline, don't expand an abbrev.
4915 (let ((abbrev-mode nil))
4916 (end-of-line)
4917 (insert (if use-hard-newlines hard-newline "\n")))
4918 (line-move arg nil nil try-vscroll))
4919 (if (called-interactively-p 'interactive)
4920 (condition-case err
4921 (line-move arg nil nil try-vscroll)
4922 ((beginning-of-buffer end-of-buffer)
4923 (signal (car err) (cdr err))))
4924 (line-move arg nil nil try-vscroll)))
4925 nil)
4926 (put 'next-line 'interactive-only 'forward-line)
4928 (defun previous-line (&optional arg try-vscroll)
4929 "Move cursor vertically up ARG lines.
4930 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4931 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
4932 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
4933 function will not vscroll.
4935 ARG defaults to 1.
4937 If there is no character in the target line exactly over the current column,
4938 the cursor is positioned after the character in that line which spans this
4939 column, or at the end of the line if it is not long enough.
4941 If the variable `line-move-visual' is non-nil, this command moves
4942 by display lines. Otherwise, it moves by buffer lines, without
4943 taking variable-width characters or continued lines into account.
4945 The command \\[set-goal-column] can be used to create
4946 a semipermanent goal column for this command.
4947 Then instead of trying to move exactly vertically (or as close as possible),
4948 this command moves to the specified goal column (or as close as possible).
4949 The goal column is stored in the variable `goal-column', which is nil
4950 when there is no goal column. Note that setting `goal-column'
4951 overrides `line-move-visual' and causes this command to move by buffer
4952 lines rather than by display lines.
4954 If you are thinking of using this in a Lisp program, consider using
4955 `forward-line' with a negative argument instead. It is usually easier
4956 to use and more reliable (no dependence on goal column, etc.)."
4957 (interactive "^p\np")
4958 (or arg (setq arg 1))
4959 (if (called-interactively-p 'interactive)
4960 (condition-case err
4961 (line-move (- arg) nil nil try-vscroll)
4962 ((beginning-of-buffer end-of-buffer)
4963 (signal (car err) (cdr err))))
4964 (line-move (- arg) nil nil try-vscroll))
4965 nil)
4966 (put 'previous-line 'interactive-only
4967 "use `forward-line' with negative argument instead.")
4969 (defcustom track-eol nil
4970 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
4971 This means moving to the end of each line moved onto.
4972 The beginning of a blank line does not count as the end of a line.
4973 This has no effect when the variable `line-move-visual' is non-nil."
4974 :type 'boolean
4975 :group 'editing-basics)
4977 (defcustom goal-column nil
4978 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
4979 A non-nil setting overrides the variable `line-move-visual', which see."
4980 :type '(choice integer
4981 (const :tag "None" nil))
4982 :group 'editing-basics)
4983 (make-variable-buffer-local 'goal-column)
4985 (defvar temporary-goal-column 0
4986 "Current goal column for vertical motion.
4987 It is the column where point was at the start of the current run
4988 of vertical motion commands.
4990 When moving by visual lines via the function `line-move-visual', it is a cons
4991 cell (COL . HSCROLL), where COL is the x-position, in pixels,
4992 divided by the default column width, and HSCROLL is the number of
4993 columns by which window is scrolled from left margin.
4995 When the `track-eol' feature is doing its job, the value is
4996 `most-positive-fixnum'.")
4998 (defcustom line-move-ignore-invisible t
4999 "Non-nil means commands that move by lines ignore invisible newlines.
5000 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5001 as if newlines that are invisible didn't exist, and count
5002 only visible newlines. Thus, moving across across 2 newlines
5003 one of which is invisible will be counted as a one-line move.
5004 Also, a non-nil value causes invisible text to be ignored when
5005 counting columns for the purposes of keeping point in the same
5006 column by \\[next-line] and \\[previous-line].
5008 Outline mode sets this."
5009 :type 'boolean
5010 :group 'editing-basics)
5012 (defcustom line-move-visual t
5013 "When non-nil, `line-move' moves point by visual lines.
5014 This movement is based on where the cursor is displayed on the
5015 screen, instead of relying on buffer contents alone. It takes
5016 into account variable-width characters and line continuation.
5017 If nil, `line-move' moves point by logical lines.
5018 A non-nil setting of `goal-column' overrides the value of this variable
5019 and forces movement by logical lines.
5020 A window that is horizontally scrolled also forces movement by logical
5021 lines."
5022 :type 'boolean
5023 :group 'editing-basics
5024 :version "23.1")
5026 ;; Only used if display-graphic-p.
5027 (declare-function font-info "font.c" (name &optional frame))
5029 (defun default-font-height ()
5030 "Return the height in pixels of the current buffer's default face font."
5031 (let ((default-font (face-font 'default)))
5032 (cond
5033 ((and (display-multi-font-p)
5034 ;; Avoid calling font-info if the frame's default font was
5035 ;; not changed since the frame was created. That's because
5036 ;; font-info is expensive for some fonts, see bug #14838.
5037 (not (string= (frame-parameter nil 'font) default-font)))
5038 (aref (font-info default-font) 3))
5039 (t (frame-char-height)))))
5041 (defun default-line-height ()
5042 "Return the pixel height of current buffer's default-face text line.
5044 The value includes `line-spacing', if any, defined for the buffer
5045 or the frame."
5046 (let ((dfh (default-font-height))
5047 (lsp (if (display-graphic-p)
5048 (or line-spacing
5049 (default-value 'line-spacing)
5050 (frame-parameter nil 'line-spacing)
5052 0)))
5053 (if (floatp lsp)
5054 (setq lsp (truncate (* (frame-char-height) lsp))))
5055 (+ dfh lsp)))
5057 (defun window-screen-lines ()
5058 "Return the number of screen lines in the text area of the selected window.
5060 This is different from `window-text-height' in that this function counts
5061 lines in units of the height of the font used by the default face displayed
5062 in the window, not in units of the frame's default font, and also accounts
5063 for `line-spacing', if any, defined for the window's buffer or frame.
5065 The value is a floating-point number."
5066 (let ((edges (window-inside-pixel-edges))
5067 (dlh (default-line-height)))
5068 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5070 ;; Returns non-nil if partial move was done.
5071 (defun line-move-partial (arg noerror to-end)
5072 (if (< arg 0)
5073 ;; Move backward (up).
5074 ;; If already vscrolled, reduce vscroll
5075 (let ((vs (window-vscroll nil t))
5076 (dlh (default-line-height)))
5077 (when (> vs dlh)
5078 (set-window-vscroll nil (- vs dlh) t)))
5080 ;; Move forward (down).
5081 (let* ((lh (window-line-height -1))
5082 (rowh (car lh))
5083 (vpos (nth 1 lh))
5084 (ypos (nth 2 lh))
5085 (rbot (nth 3 lh))
5086 (this-lh (window-line-height))
5087 (this-height (car this-lh))
5088 (this-ypos (nth 2 this-lh))
5089 (dlh (default-line-height))
5090 (wslines (window-screen-lines))
5091 (edges (window-inside-pixel-edges))
5092 (winh (- (nth 3 edges) (nth 1 edges) 1))
5093 py vs last-line)
5094 (if (> (mod wslines 1.0) 0.0)
5095 (setq wslines (round (+ wslines 0.5))))
5096 (when (or (null lh)
5097 (>= rbot dlh)
5098 (<= ypos (- dlh))
5099 (null this-lh)
5100 (<= this-ypos (- dlh)))
5101 (unless lh
5102 (let ((wend (pos-visible-in-window-p t nil t)))
5103 (setq rbot (nth 3 wend)
5104 rowh (nth 4 wend)
5105 vpos (nth 5 wend))))
5106 (unless this-lh
5107 (let ((wstart (pos-visible-in-window-p nil nil t)))
5108 (setq this-ypos (nth 2 wstart)
5109 this-height (nth 4 wstart))))
5110 (setq py
5111 (or (nth 1 this-lh)
5112 (let ((ppos (posn-at-point))
5113 col-row)
5114 (setq col-row (posn-actual-col-row ppos))
5115 (if col-row
5116 (- (cdr col-row) (window-vscroll))
5117 (cdr (posn-col-row ppos))))))
5118 ;; VPOS > 0 means the last line is only partially visible.
5119 ;; But if the part that is visible is at least as tall as the
5120 ;; default font, that means the line is actually fully
5121 ;; readable, and something like line-spacing is hidden. So in
5122 ;; that case we accept the last line in the window as still
5123 ;; visible, and consider the margin as starting one line
5124 ;; later.
5125 (if (and vpos (> vpos 0))
5126 (if (and rowh
5127 (>= rowh (default-font-height))
5128 (< rowh dlh))
5129 (setq last-line (min (- wslines scroll-margin) vpos))
5130 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
5131 (cond
5132 ;; If last line of window is fully visible, and vscrolling
5133 ;; more would make this line invisible, move forward.
5134 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
5135 (null this-height)
5136 (<= this-height dlh))
5137 (or (null rbot) (= rbot 0)))
5138 nil)
5139 ;; If cursor is not in the bottom scroll margin, and the
5140 ;; current line is is not too tall, move forward.
5141 ((and (or (null this-height) (<= this-height winh))
5142 vpos
5143 (> vpos 0)
5144 (< py last-line))
5145 nil)
5146 ;; When already vscrolled, we vscroll some more if we can,
5147 ;; or clear vscroll and move forward at end of tall image.
5148 ((> vs 0)
5149 (when (or (and rbot (> rbot 0))
5150 (and this-height (> this-height dlh)))
5151 (set-window-vscroll nil (+ vs dlh) t)))
5152 ;; If cursor just entered the bottom scroll margin, move forward,
5153 ;; but also optionally vscroll one line so redisplay won't recenter.
5154 ((and vpos
5155 (> vpos 0)
5156 (= py last-line))
5157 ;; Don't vscroll if the partially-visible line at window
5158 ;; bottom is not too tall (a.k.a. "just one more text
5159 ;; line"): in that case, we do want redisplay to behave
5160 ;; normally, i.e. recenter or whatever.
5162 ;; Note: ROWH + RBOT from the value returned by
5163 ;; pos-visible-in-window-p give the total height of the
5164 ;; partially-visible glyph row at the end of the window. As
5165 ;; we are dealing with floats, we disregard sub-pixel
5166 ;; discrepancies between that and DLH.
5167 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
5168 (set-window-vscroll nil dlh t))
5169 (line-move-1 arg noerror to-end)
5171 ;; If there are lines above the last line, scroll-up one line.
5172 ((and vpos (> vpos 0))
5173 (scroll-up 1)
5175 ;; Finally, start vscroll.
5177 (set-window-vscroll nil dlh t)))))))
5180 ;; This is like line-move-1 except that it also performs
5181 ;; vertical scrolling of tall images if appropriate.
5182 ;; That is not really a clean thing to do, since it mixes
5183 ;; scrolling with cursor motion. But so far we don't have
5184 ;; a cleaner solution to the problem of making C-n do something
5185 ;; useful given a tall image.
5186 (defun line-move (arg &optional noerror to-end try-vscroll)
5187 "Move forward ARG lines.
5188 If NOERROR, don't signal an error if we can't move ARG lines.
5189 TO-END is unused.
5190 TRY-VSCROLL controls whether to vscroll tall lines: if either
5191 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
5192 not vscroll."
5193 (if noninteractive
5194 (line-move-1 arg noerror to-end)
5195 (unless (and auto-window-vscroll try-vscroll
5196 ;; Only vscroll for single line moves
5197 (= (abs arg) 1)
5198 ;; Under scroll-conservatively, the display engine
5199 ;; does this better.
5200 (zerop scroll-conservatively)
5201 ;; But don't vscroll in a keyboard macro.
5202 (not defining-kbd-macro)
5203 (not executing-kbd-macro)
5204 (line-move-partial arg noerror to-end))
5205 (set-window-vscroll nil 0 t)
5206 (if (and line-move-visual
5207 ;; Display-based column are incompatible with goal-column.
5208 (not goal-column)
5209 ;; When the text in the window is scrolled to the left,
5210 ;; display-based motion doesn't make sense (because each
5211 ;; logical line occupies exactly one screen line).
5212 (not (> (window-hscroll) 0))
5213 ;; Likewise when the text _was_ scrolled to the left
5214 ;; when the current run of vertical motion commands
5215 ;; started.
5216 (not (and (memq last-command
5217 `(next-line previous-line ,this-command))
5218 auto-hscroll-mode
5219 (numberp temporary-goal-column)
5220 (>= temporary-goal-column
5221 (- (window-width) hscroll-margin)))))
5222 (prog1 (line-move-visual arg noerror)
5223 ;; If we moved into a tall line, set vscroll to make
5224 ;; scrolling through tall images more smooth.
5225 (let ((lh (line-pixel-height))
5226 (edges (window-inside-pixel-edges))
5227 (dlh (default-line-height))
5228 winh)
5229 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
5230 (if (and (< arg 0)
5231 (< (point) (window-start))
5232 (> lh winh))
5233 (set-window-vscroll
5235 (- lh dlh) t))))
5236 (line-move-1 arg noerror to-end)))))
5238 ;; Display-based alternative to line-move-1.
5239 ;; Arg says how many lines to move. The value is t if we can move the
5240 ;; specified number of lines.
5241 (defun line-move-visual (arg &optional noerror)
5242 "Move ARG lines forward.
5243 If NOERROR, don't signal an error if we can't move that many lines."
5244 (let ((opoint (point))
5245 (hscroll (window-hscroll))
5246 target-hscroll)
5247 ;; Check if the previous command was a line-motion command, or if
5248 ;; we were called from some other command.
5249 (if (and (consp temporary-goal-column)
5250 (memq last-command `(next-line previous-line ,this-command)))
5251 ;; If so, there's no need to reset `temporary-goal-column',
5252 ;; but we may need to hscroll.
5253 (if (or (/= (cdr temporary-goal-column) hscroll)
5254 (> (cdr temporary-goal-column) 0))
5255 (setq target-hscroll (cdr temporary-goal-column)))
5256 ;; Otherwise, we should reset `temporary-goal-column'.
5257 (let ((posn (posn-at-point))
5258 x-pos)
5259 (cond
5260 ;; Handle the `overflow-newline-into-fringe' case:
5261 ((eq (nth 1 posn) 'right-fringe)
5262 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
5263 ((car (posn-x-y posn))
5264 (setq x-pos (car (posn-x-y posn)))
5265 ;; In R2L lines, the X pixel coordinate is measured from the
5266 ;; left edge of the window, but columns are still counted
5267 ;; from the logical-order beginning of the line, i.e. from
5268 ;; the right edge in this case. We need to adjust for that.
5269 (if (eq (current-bidi-paragraph-direction) 'right-to-left)
5270 (setq x-pos (- (window-body-width nil t) 1 x-pos)))
5271 (setq temporary-goal-column
5272 (cons (/ (float x-pos)
5273 (frame-char-width))
5274 hscroll))))))
5275 (if target-hscroll
5276 (set-window-hscroll (selected-window) target-hscroll))
5277 ;; vertical-motion can move more than it was asked to if it moves
5278 ;; across display strings with newlines. We don't want to ring
5279 ;; the bell and announce beginning/end of buffer in that case.
5280 (or (and (or (and (>= arg 0)
5281 (>= (vertical-motion
5282 (cons (or goal-column
5283 (if (consp temporary-goal-column)
5284 (car temporary-goal-column)
5285 temporary-goal-column))
5286 arg))
5287 arg))
5288 (and (< arg 0)
5289 (<= (vertical-motion
5290 (cons (or goal-column
5291 (if (consp temporary-goal-column)
5292 (car temporary-goal-column)
5293 temporary-goal-column))
5294 arg))
5295 arg)))
5296 (or (>= arg 0)
5297 (/= (point) opoint)
5298 ;; If the goal column lies on a display string,
5299 ;; `vertical-motion' advances the cursor to the end
5300 ;; of the string. For arg < 0, this can cause the
5301 ;; cursor to get stuck. (Bug#3020).
5302 (= (vertical-motion arg) arg)))
5303 (unless noerror
5304 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
5305 nil)))))
5307 ;; This is the guts of next-line and previous-line.
5308 ;; Arg says how many lines to move.
5309 ;; The value is t if we can move the specified number of lines.
5310 (defun line-move-1 (arg &optional noerror _to-end)
5311 ;; Don't run any point-motion hooks, and disregard intangibility,
5312 ;; for intermediate positions.
5313 (let ((inhibit-point-motion-hooks t)
5314 (opoint (point))
5315 (orig-arg arg))
5316 (if (consp temporary-goal-column)
5317 (setq temporary-goal-column (+ (car temporary-goal-column)
5318 (cdr temporary-goal-column))))
5319 (unwind-protect
5320 (progn
5321 (if (not (memq last-command '(next-line previous-line)))
5322 (setq temporary-goal-column
5323 (if (and track-eol (eolp)
5324 ;; Don't count beg of empty line as end of line
5325 ;; unless we just did explicit end-of-line.
5326 (or (not (bolp)) (eq last-command 'move-end-of-line)))
5327 most-positive-fixnum
5328 (current-column))))
5330 (if (not (or (integerp selective-display)
5331 line-move-ignore-invisible))
5332 ;; Use just newline characters.
5333 ;; Set ARG to 0 if we move as many lines as requested.
5334 (or (if (> arg 0)
5335 (progn (if (> arg 1) (forward-line (1- arg)))
5336 ;; This way of moving forward ARG lines
5337 ;; verifies that we have a newline after the last one.
5338 ;; It doesn't get confused by intangible text.
5339 (end-of-line)
5340 (if (zerop (forward-line 1))
5341 (setq arg 0)))
5342 (and (zerop (forward-line arg))
5343 (bolp)
5344 (setq arg 0)))
5345 (unless noerror
5346 (signal (if (< arg 0)
5347 'beginning-of-buffer
5348 'end-of-buffer)
5349 nil)))
5350 ;; Move by arg lines, but ignore invisible ones.
5351 (let (done)
5352 (while (and (> arg 0) (not done))
5353 ;; If the following character is currently invisible,
5354 ;; skip all characters with that same `invisible' property value.
5355 (while (and (not (eobp)) (invisible-p (point)))
5356 (goto-char (next-char-property-change (point))))
5357 ;; Move a line.
5358 ;; We don't use `end-of-line', since we want to escape
5359 ;; from field boundaries occurring exactly at point.
5360 (goto-char (constrain-to-field
5361 (let ((inhibit-field-text-motion t))
5362 (line-end-position))
5363 (point) t t
5364 'inhibit-line-move-field-capture))
5365 ;; If there's no invisibility here, move over the newline.
5366 (cond
5367 ((eobp)
5368 (if (not noerror)
5369 (signal 'end-of-buffer nil)
5370 (setq done t)))
5371 ((and (> arg 1) ;; Use vertical-motion for last move
5372 (not (integerp selective-display))
5373 (not (invisible-p (point))))
5374 ;; We avoid vertical-motion when possible
5375 ;; because that has to fontify.
5376 (forward-line 1))
5377 ;; Otherwise move a more sophisticated way.
5378 ((zerop (vertical-motion 1))
5379 (if (not noerror)
5380 (signal 'end-of-buffer nil)
5381 (setq done t))))
5382 (unless done
5383 (setq arg (1- arg))))
5384 ;; The logic of this is the same as the loop above,
5385 ;; it just goes in the other direction.
5386 (while (and (< arg 0) (not done))
5387 ;; For completely consistency with the forward-motion
5388 ;; case, we should call beginning-of-line here.
5389 ;; However, if point is inside a field and on a
5390 ;; continued line, the call to (vertical-motion -1)
5391 ;; below won't move us back far enough; then we return
5392 ;; to the same column in line-move-finish, and point
5393 ;; gets stuck -- cyd
5394 (forward-line 0)
5395 (cond
5396 ((bobp)
5397 (if (not noerror)
5398 (signal 'beginning-of-buffer nil)
5399 (setq done t)))
5400 ((and (< arg -1) ;; Use vertical-motion for last move
5401 (not (integerp selective-display))
5402 (not (invisible-p (1- (point)))))
5403 (forward-line -1))
5404 ((zerop (vertical-motion -1))
5405 (if (not noerror)
5406 (signal 'beginning-of-buffer nil)
5407 (setq done t))))
5408 (unless done
5409 (setq arg (1+ arg))
5410 (while (and ;; Don't move over previous invis lines
5411 ;; if our target is the middle of this line.
5412 (or (zerop (or goal-column temporary-goal-column))
5413 (< arg 0))
5414 (not (bobp)) (invisible-p (1- (point))))
5415 (goto-char (previous-char-property-change (point))))))))
5416 ;; This is the value the function returns.
5417 (= arg 0))
5419 (cond ((> arg 0)
5420 ;; If we did not move down as far as desired, at least go
5421 ;; to end of line. Be sure to call point-entered and
5422 ;; point-left-hooks.
5423 (let* ((npoint (prog1 (line-end-position)
5424 (goto-char opoint)))
5425 (inhibit-point-motion-hooks nil))
5426 (goto-char npoint)))
5427 ((< arg 0)
5428 ;; If we did not move up as far as desired,
5429 ;; at least go to beginning of line.
5430 (let* ((npoint (prog1 (line-beginning-position)
5431 (goto-char opoint)))
5432 (inhibit-point-motion-hooks nil))
5433 (goto-char npoint)))
5435 (line-move-finish (or goal-column temporary-goal-column)
5436 opoint (> orig-arg 0)))))))
5438 (defun line-move-finish (column opoint forward)
5439 (let ((repeat t))
5440 (while repeat
5441 ;; Set REPEAT to t to repeat the whole thing.
5442 (setq repeat nil)
5444 (let (new
5445 (old (point))
5446 (line-beg (line-beginning-position))
5447 (line-end
5448 ;; Compute the end of the line
5449 ;; ignoring effectively invisible newlines.
5450 (save-excursion
5451 ;; Like end-of-line but ignores fields.
5452 (skip-chars-forward "^\n")
5453 (while (and (not (eobp)) (invisible-p (point)))
5454 (goto-char (next-char-property-change (point)))
5455 (skip-chars-forward "^\n"))
5456 (point))))
5458 ;; Move to the desired column.
5459 (line-move-to-column (truncate column))
5461 ;; Corner case: suppose we start out in a field boundary in
5462 ;; the middle of a continued line. When we get to
5463 ;; line-move-finish, point is at the start of a new *screen*
5464 ;; line but the same text line; then line-move-to-column would
5465 ;; move us backwards. Test using C-n with point on the "x" in
5466 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
5467 (and forward
5468 (< (point) old)
5469 (goto-char old))
5471 (setq new (point))
5473 ;; Process intangibility within a line.
5474 ;; With inhibit-point-motion-hooks bound to nil, a call to
5475 ;; goto-char moves point past intangible text.
5477 ;; However, inhibit-point-motion-hooks controls both the
5478 ;; intangibility and the point-entered/point-left hooks. The
5479 ;; following hack avoids calling the point-* hooks
5480 ;; unnecessarily. Note that we move *forward* past intangible
5481 ;; text when the initial and final points are the same.
5482 (goto-char new)
5483 (let ((inhibit-point-motion-hooks nil))
5484 (goto-char new)
5486 ;; If intangibility moves us to a different (later) place
5487 ;; in the same line, use that as the destination.
5488 (if (<= (point) line-end)
5489 (setq new (point))
5490 ;; If that position is "too late",
5491 ;; try the previous allowable position.
5492 ;; See if it is ok.
5493 (backward-char)
5494 (if (if forward
5495 ;; If going forward, don't accept the previous
5496 ;; allowable position if it is before the target line.
5497 (< line-beg (point))
5498 ;; If going backward, don't accept the previous
5499 ;; allowable position if it is still after the target line.
5500 (<= (point) line-end))
5501 (setq new (point))
5502 ;; As a last resort, use the end of the line.
5503 (setq new line-end))))
5505 ;; Now move to the updated destination, processing fields
5506 ;; as well as intangibility.
5507 (goto-char opoint)
5508 (let ((inhibit-point-motion-hooks nil))
5509 (goto-char
5510 ;; Ignore field boundaries if the initial and final
5511 ;; positions have the same `field' property, even if the
5512 ;; fields are non-contiguous. This seems to be "nicer"
5513 ;; behavior in many situations.
5514 (if (eq (get-char-property new 'field)
5515 (get-char-property opoint 'field))
5517 (constrain-to-field new opoint t t
5518 'inhibit-line-move-field-capture))))
5520 ;; If all this moved us to a different line,
5521 ;; retry everything within that new line.
5522 (when (or (< (point) line-beg) (> (point) line-end))
5523 ;; Repeat the intangibility and field processing.
5524 (setq repeat t))))))
5526 (defun line-move-to-column (col)
5527 "Try to find column COL, considering invisibility.
5528 This function works only in certain cases,
5529 because what we really need is for `move-to-column'
5530 and `current-column' to be able to ignore invisible text."
5531 (if (zerop col)
5532 (beginning-of-line)
5533 (move-to-column col))
5535 (when (and line-move-ignore-invisible
5536 (not (bolp)) (invisible-p (1- (point))))
5537 (let ((normal-location (point))
5538 (normal-column (current-column)))
5539 ;; If the following character is currently invisible,
5540 ;; skip all characters with that same `invisible' property value.
5541 (while (and (not (eobp))
5542 (invisible-p (point)))
5543 (goto-char (next-char-property-change (point))))
5544 ;; Have we advanced to a larger column position?
5545 (if (> (current-column) normal-column)
5546 ;; We have made some progress towards the desired column.
5547 ;; See if we can make any further progress.
5548 (line-move-to-column (+ (current-column) (- col normal-column)))
5549 ;; Otherwise, go to the place we originally found
5550 ;; and move back over invisible text.
5551 ;; that will get us to the same place on the screen
5552 ;; but with a more reasonable buffer position.
5553 (goto-char normal-location)
5554 (let ((line-beg (line-beginning-position)))
5555 (while (and (not (bolp)) (invisible-p (1- (point))))
5556 (goto-char (previous-char-property-change (point) line-beg))))))))
5558 (defun move-end-of-line (arg)
5559 "Move point to end of current line as displayed.
5560 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5561 If point reaches the beginning or end of buffer, it stops there.
5563 To ignore the effects of the `intangible' text or overlay
5564 property, bind `inhibit-point-motion-hooks' to t.
5565 If there is an image in the current line, this function
5566 disregards newlines that are part of the text on which the image
5567 rests."
5568 (interactive "^p")
5569 (or arg (setq arg 1))
5570 (let (done)
5571 (while (not done)
5572 (let ((newpos
5573 (save-excursion
5574 (let ((goal-column 0)
5575 (line-move-visual nil))
5576 (and (line-move arg t)
5577 ;; With bidi reordering, we may not be at bol,
5578 ;; so make sure we are.
5579 (skip-chars-backward "^\n")
5580 (not (bobp))
5581 (progn
5582 (while (and (not (bobp)) (invisible-p (1- (point))))
5583 (goto-char (previous-single-char-property-change
5584 (point) 'invisible)))
5585 (backward-char 1)))
5586 (point)))))
5587 (goto-char newpos)
5588 (if (and (> (point) newpos)
5589 (eq (preceding-char) ?\n))
5590 (backward-char 1)
5591 (if (and (> (point) newpos) (not (eobp))
5592 (not (eq (following-char) ?\n)))
5593 ;; If we skipped something intangible and now we're not
5594 ;; really at eol, keep going.
5595 (setq arg 1)
5596 (setq done t)))))))
5598 (defun move-beginning-of-line (arg)
5599 "Move point to beginning of current line as displayed.
5600 \(If there's an image in the line, this disregards newlines
5601 which are part of the text that the image rests on.)
5603 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5604 If point reaches the beginning or end of buffer, it stops there.
5605 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5606 (interactive "^p")
5607 (or arg (setq arg 1))
5609 (let ((orig (point))
5610 first-vis first-vis-field-value)
5612 ;; Move by lines, if ARG is not 1 (the default).
5613 (if (/= arg 1)
5614 (let ((line-move-visual nil))
5615 (line-move (1- arg) t)))
5617 ;; Move to beginning-of-line, ignoring fields and invisible text.
5618 (skip-chars-backward "^\n")
5619 (while (and (not (bobp)) (invisible-p (1- (point))))
5620 (goto-char (previous-char-property-change (point)))
5621 (skip-chars-backward "^\n"))
5623 ;; Now find first visible char in the line.
5624 (while (and (< (point) orig) (invisible-p (point)))
5625 (goto-char (next-char-property-change (point) orig)))
5626 (setq first-vis (point))
5628 ;; See if fields would stop us from reaching FIRST-VIS.
5629 (setq first-vis-field-value
5630 (constrain-to-field first-vis orig (/= arg 1) t nil))
5632 (goto-char (if (/= first-vis-field-value first-vis)
5633 ;; If yes, obey them.
5634 first-vis-field-value
5635 ;; Otherwise, move to START with attention to fields.
5636 ;; (It is possible that fields never matter in this case.)
5637 (constrain-to-field (point) orig
5638 (/= arg 1) t nil)))))
5641 ;; Many people have said they rarely use this feature, and often type
5642 ;; it by accident. Maybe it shouldn't even be on a key.
5643 (put 'set-goal-column 'disabled t)
5645 (defun set-goal-column (arg)
5646 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
5647 Those commands will move to this position in the line moved to
5648 rather than trying to keep the same horizontal position.
5649 With a non-nil argument ARG, clears out the goal column
5650 so that \\[next-line] and \\[previous-line] resume vertical motion.
5651 The goal column is stored in the variable `goal-column'."
5652 (interactive "P")
5653 (if arg
5654 (progn
5655 (setq goal-column nil)
5656 (message "No goal column"))
5657 (setq goal-column (current-column))
5658 ;; The older method below can be erroneous if `set-goal-column' is bound
5659 ;; to a sequence containing %
5660 ;;(message (substitute-command-keys
5661 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
5662 ;;goal-column)
5663 (message "%s"
5664 (concat
5665 (format "Goal column %d " goal-column)
5666 (substitute-command-keys
5667 "(use \\[set-goal-column] with an arg to unset it)")))
5670 nil)
5672 ;;; Editing based on visual lines, as opposed to logical lines.
5674 (defun end-of-visual-line (&optional n)
5675 "Move point to end of current visual line.
5676 With argument N not nil or 1, move forward N - 1 visual lines first.
5677 If point reaches the beginning or end of buffer, it stops there.
5678 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5679 (interactive "^p")
5680 (or n (setq n 1))
5681 (if (/= n 1)
5682 (let ((line-move-visual t))
5683 (line-move (1- n) t)))
5684 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
5685 ;; constrain to field boundaries, so we don't either.
5686 (vertical-motion (cons (window-width) 0)))
5688 (defun beginning-of-visual-line (&optional n)
5689 "Move point to beginning of current visual line.
5690 With argument N not nil or 1, move forward N - 1 visual lines first.
5691 If point reaches the beginning or end of buffer, it stops there.
5692 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5693 (interactive "^p")
5694 (or n (setq n 1))
5695 (let ((opoint (point)))
5696 (if (/= n 1)
5697 (let ((line-move-visual t))
5698 (line-move (1- n) t)))
5699 (vertical-motion 0)
5700 ;; Constrain to field boundaries, like `move-beginning-of-line'.
5701 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
5703 (defun kill-visual-line (&optional arg)
5704 "Kill the rest of the visual line.
5705 With prefix argument ARG, kill that many visual lines from point.
5706 If ARG is negative, kill visual lines backward.
5707 If ARG is zero, kill the text before point on the current visual
5708 line.
5710 If you want to append the killed line to the last killed text,
5711 use \\[append-next-kill] before \\[kill-line].
5713 If the buffer is read-only, Emacs will beep and refrain from deleting
5714 the line, but put the line in the kill ring anyway. This means that
5715 you can use this command to copy text from a read-only buffer.
5716 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5717 even beep.)"
5718 (interactive "P")
5719 ;; Like in `kill-line', it's better to move point to the other end
5720 ;; of the kill before killing.
5721 (let ((opoint (point))
5722 (kill-whole-line (and kill-whole-line (bolp))))
5723 (if arg
5724 (vertical-motion (prefix-numeric-value arg))
5725 (end-of-visual-line 1)
5726 (if (= (point) opoint)
5727 (vertical-motion 1)
5728 ;; Skip any trailing whitespace at the end of the visual line.
5729 ;; We used to do this only if `show-trailing-whitespace' is
5730 ;; nil, but that's wrong; the correct thing would be to check
5731 ;; whether the trailing whitespace is highlighted. But, it's
5732 ;; OK to just do this unconditionally.
5733 (skip-chars-forward " \t")))
5734 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
5735 (1+ (point))
5736 (point)))))
5738 (defun next-logical-line (&optional arg try-vscroll)
5739 "Move cursor vertically down ARG lines.
5740 This is identical to `next-line', except that it always moves
5741 by logical lines instead of visual lines, ignoring the value of
5742 the variable `line-move-visual'."
5743 (interactive "^p\np")
5744 (let ((line-move-visual nil))
5745 (with-no-warnings
5746 (next-line arg try-vscroll))))
5748 (defun previous-logical-line (&optional arg try-vscroll)
5749 "Move cursor vertically up ARG lines.
5750 This is identical to `previous-line', except that it always moves
5751 by logical lines instead of visual lines, ignoring the value of
5752 the variable `line-move-visual'."
5753 (interactive "^p\np")
5754 (let ((line-move-visual nil))
5755 (with-no-warnings
5756 (previous-line arg try-vscroll))))
5758 (defgroup visual-line nil
5759 "Editing based on visual lines."
5760 :group 'convenience
5761 :version "23.1")
5763 (defvar visual-line-mode-map
5764 (let ((map (make-sparse-keymap)))
5765 (define-key map [remap kill-line] 'kill-visual-line)
5766 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
5767 (define-key map [remap move-end-of-line] 'end-of-visual-line)
5768 ;; These keybindings interfere with xterm function keys. Are
5769 ;; there any other suitable bindings?
5770 ;; (define-key map "\M-[" 'previous-logical-line)
5771 ;; (define-key map "\M-]" 'next-logical-line)
5772 map))
5774 (defcustom visual-line-fringe-indicators '(nil nil)
5775 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
5776 The value should be a list of the form (LEFT RIGHT), where LEFT
5777 and RIGHT are symbols representing the bitmaps to display, to
5778 indicate wrapped lines, in the left and right fringes respectively.
5779 See also `fringe-indicator-alist'.
5780 The default is not to display fringe indicators for wrapped lines.
5781 This variable does not affect fringe indicators displayed for
5782 other purposes."
5783 :type '(list (choice (const :tag "Hide left indicator" nil)
5784 (const :tag "Left curly arrow" left-curly-arrow)
5785 (symbol :tag "Other bitmap"))
5786 (choice (const :tag "Hide right indicator" nil)
5787 (const :tag "Right curly arrow" right-curly-arrow)
5788 (symbol :tag "Other bitmap")))
5789 :set (lambda (symbol value)
5790 (dolist (buf (buffer-list))
5791 (with-current-buffer buf
5792 (when (and (boundp 'visual-line-mode)
5793 (symbol-value 'visual-line-mode))
5794 (setq fringe-indicator-alist
5795 (cons (cons 'continuation value)
5796 (assq-delete-all
5797 'continuation
5798 (copy-tree fringe-indicator-alist)))))))
5799 (set-default symbol value)))
5801 (defvar visual-line--saved-state nil)
5803 (define-minor-mode visual-line-mode
5804 "Toggle visual line based editing (Visual Line mode).
5805 With a prefix argument ARG, enable Visual Line mode if ARG is
5806 positive, and disable it otherwise. If called from Lisp, enable
5807 the mode if ARG is omitted or nil.
5809 When Visual Line mode is enabled, `word-wrap' is turned on in
5810 this buffer, and simple editing commands are redefined to act on
5811 visual lines, not logical lines. See Info node `Visual Line
5812 Mode' for details."
5813 :keymap visual-line-mode-map
5814 :group 'visual-line
5815 :lighter " Wrap"
5816 (if visual-line-mode
5817 (progn
5818 (set (make-local-variable 'visual-line--saved-state) nil)
5819 ;; Save the local values of some variables, to be restored if
5820 ;; visual-line-mode is turned off.
5821 (dolist (var '(line-move-visual truncate-lines
5822 truncate-partial-width-windows
5823 word-wrap fringe-indicator-alist))
5824 (if (local-variable-p var)
5825 (push (cons var (symbol-value var))
5826 visual-line--saved-state)))
5827 (set (make-local-variable 'line-move-visual) t)
5828 (set (make-local-variable 'truncate-partial-width-windows) nil)
5829 (setq truncate-lines nil
5830 word-wrap t
5831 fringe-indicator-alist
5832 (cons (cons 'continuation visual-line-fringe-indicators)
5833 fringe-indicator-alist)))
5834 (kill-local-variable 'line-move-visual)
5835 (kill-local-variable 'word-wrap)
5836 (kill-local-variable 'truncate-lines)
5837 (kill-local-variable 'truncate-partial-width-windows)
5838 (kill-local-variable 'fringe-indicator-alist)
5839 (dolist (saved visual-line--saved-state)
5840 (set (make-local-variable (car saved)) (cdr saved)))
5841 (kill-local-variable 'visual-line--saved-state)))
5843 (defun turn-on-visual-line-mode ()
5844 (visual-line-mode 1))
5846 (define-globalized-minor-mode global-visual-line-mode
5847 visual-line-mode turn-on-visual-line-mode)
5850 (defun transpose-chars (arg)
5851 "Interchange characters around point, moving forward one character.
5852 With prefix arg ARG, effect is to take character before point
5853 and drag it forward past ARG other characters (backward if ARG negative).
5854 If no argument and at end of line, the previous two chars are exchanged."
5855 (interactive "*P")
5856 (and (null arg) (eolp) (forward-char -1))
5857 (transpose-subr 'forward-char (prefix-numeric-value arg)))
5859 (defun transpose-words (arg)
5860 "Interchange words around point, leaving point at end of them.
5861 With prefix arg ARG, effect is to take word before or around point
5862 and drag it forward past ARG other words (backward if ARG negative).
5863 If ARG is zero, the words around or after point and around or after mark
5864 are interchanged."
5865 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
5866 (interactive "*p")
5867 (transpose-subr 'forward-word arg))
5869 (defun transpose-sexps (arg)
5870 "Like \\[transpose-words] but applies to sexps.
5871 Does not work on a sexp that point is in the middle of
5872 if it is a list or string."
5873 (interactive "*p")
5874 (transpose-subr
5875 (lambda (arg)
5876 ;; Here we should try to simulate the behavior of
5877 ;; (cons (progn (forward-sexp x) (point))
5878 ;; (progn (forward-sexp (- x)) (point)))
5879 ;; Except that we don't want to rely on the second forward-sexp
5880 ;; putting us back to where we want to be, since forward-sexp-function
5881 ;; might do funny things like infix-precedence.
5882 (if (if (> arg 0)
5883 (looking-at "\\sw\\|\\s_")
5884 (and (not (bobp))
5885 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
5886 ;; Jumping over a symbol. We might be inside it, mind you.
5887 (progn (funcall (if (> arg 0)
5888 'skip-syntax-backward 'skip-syntax-forward)
5889 "w_")
5890 (cons (save-excursion (forward-sexp arg) (point)) (point)))
5891 ;; Otherwise, we're between sexps. Take a step back before jumping
5892 ;; to make sure we'll obey the same precedence no matter which direction
5893 ;; we're going.
5894 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
5895 (cons (save-excursion (forward-sexp arg) (point))
5896 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
5897 (not (zerop (funcall (if (> arg 0)
5898 'skip-syntax-forward
5899 'skip-syntax-backward)
5900 ".")))))
5901 (point)))))
5902 arg 'special))
5904 (defun transpose-lines (arg)
5905 "Exchange current line and previous line, leaving point after both.
5906 With argument ARG, takes previous line and moves it past ARG lines.
5907 With argument 0, interchanges line point is in with line mark is in."
5908 (interactive "*p")
5909 (transpose-subr (function
5910 (lambda (arg)
5911 (if (> arg 0)
5912 (progn
5913 ;; Move forward over ARG lines,
5914 ;; but create newlines if necessary.
5915 (setq arg (forward-line arg))
5916 (if (/= (preceding-char) ?\n)
5917 (setq arg (1+ arg)))
5918 (if (> arg 0)
5919 (newline arg)))
5920 (forward-line arg))))
5921 arg))
5923 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
5924 ;; which seems inconsistent with the ARG /= 0 case.
5925 ;; FIXME document SPECIAL.
5926 (defun transpose-subr (mover arg &optional special)
5927 "Subroutine to do the work of transposing objects.
5928 Works for lines, sentences, paragraphs, etc. MOVER is a function that
5929 moves forward by units of the given object (e.g. forward-sentence,
5930 forward-paragraph). If ARG is zero, exchanges the current object
5931 with the one containing mark. If ARG is an integer, moves the
5932 current object past ARG following (if ARG is positive) or
5933 preceding (if ARG is negative) objects, leaving point after the
5934 current object."
5935 (let ((aux (if special mover
5936 (lambda (x)
5937 (cons (progn (funcall mover x) (point))
5938 (progn (funcall mover (- x)) (point))))))
5939 pos1 pos2)
5940 (cond
5941 ((= arg 0)
5942 (save-excursion
5943 (setq pos1 (funcall aux 1))
5944 (goto-char (or (mark) (error "No mark set in this buffer")))
5945 (setq pos2 (funcall aux 1))
5946 (transpose-subr-1 pos1 pos2))
5947 (exchange-point-and-mark))
5948 ((> arg 0)
5949 (setq pos1 (funcall aux -1))
5950 (setq pos2 (funcall aux arg))
5951 (transpose-subr-1 pos1 pos2)
5952 (goto-char (car pos2)))
5954 (setq pos1 (funcall aux -1))
5955 (goto-char (car pos1))
5956 (setq pos2 (funcall aux arg))
5957 (transpose-subr-1 pos1 pos2)))))
5959 (defun transpose-subr-1 (pos1 pos2)
5960 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
5961 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
5962 (when (> (car pos1) (car pos2))
5963 (let ((swap pos1))
5964 (setq pos1 pos2 pos2 swap)))
5965 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
5966 (atomic-change-group
5967 ;; This sequence of insertions attempts to preserve marker
5968 ;; positions at the start and end of the transposed objects.
5969 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
5970 (len1 (- (cdr pos1) (car pos1)))
5971 (len2 (length word))
5972 (boundary (make-marker)))
5973 (set-marker boundary (car pos2))
5974 (goto-char (cdr pos1))
5975 (insert-before-markers word)
5976 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
5977 (goto-char boundary)
5978 (insert word)
5979 (goto-char (+ boundary len1))
5980 (delete-region (point) (+ (point) len2))
5981 (set-marker boundary nil))))
5983 (defun backward-word (&optional arg)
5984 "Move backward until encountering the beginning of a word.
5985 With argument ARG, do this that many times.
5986 If ARG is omitted or nil, move point backward one word."
5987 (interactive "^p")
5988 (forward-word (- (or arg 1))))
5990 (defun mark-word (&optional arg allow-extend)
5991 "Set mark ARG words away from point.
5992 The place mark goes is the same place \\[forward-word] would
5993 move to with the same argument.
5994 Interactively, if this command is repeated
5995 or (in Transient Mark mode) if the mark is active,
5996 it marks the next ARG words after the ones already marked."
5997 (interactive "P\np")
5998 (cond ((and allow-extend
5999 (or (and (eq last-command this-command) (mark t))
6000 (region-active-p)))
6001 (setq arg (if arg (prefix-numeric-value arg)
6002 (if (< (mark) (point)) -1 1)))
6003 (set-mark
6004 (save-excursion
6005 (goto-char (mark))
6006 (forward-word arg)
6007 (point))))
6009 (push-mark
6010 (save-excursion
6011 (forward-word (prefix-numeric-value arg))
6012 (point))
6013 nil t))))
6015 (defun kill-word (arg)
6016 "Kill characters forward until encountering the end of a word.
6017 With argument ARG, do this that many times."
6018 (interactive "p")
6019 (kill-region (point) (progn (forward-word arg) (point))))
6021 (defun backward-kill-word (arg)
6022 "Kill characters backward until encountering the beginning of a word.
6023 With argument ARG, do this that many times."
6024 (interactive "p")
6025 (kill-word (- arg)))
6027 (defun current-word (&optional strict really-word)
6028 "Return the symbol or word that point is on (or a nearby one) as a string.
6029 The return value includes no text properties.
6030 If optional arg STRICT is non-nil, return nil unless point is within
6031 or adjacent to a symbol or word. In all cases the value can be nil
6032 if there is no word nearby.
6033 The function, belying its name, normally finds a symbol.
6034 If optional arg REALLY-WORD is non-nil, it finds just a word."
6035 (save-excursion
6036 (let* ((oldpoint (point)) (start (point)) (end (point))
6037 (syntaxes (if really-word "w" "w_"))
6038 (not-syntaxes (concat "^" syntaxes)))
6039 (skip-syntax-backward syntaxes) (setq start (point))
6040 (goto-char oldpoint)
6041 (skip-syntax-forward syntaxes) (setq end (point))
6042 (when (and (eq start oldpoint) (eq end oldpoint)
6043 ;; Point is neither within nor adjacent to a word.
6044 (not strict))
6045 ;; Look for preceding word in same line.
6046 (skip-syntax-backward not-syntaxes (line-beginning-position))
6047 (if (bolp)
6048 ;; No preceding word in same line.
6049 ;; Look for following word in same line.
6050 (progn
6051 (skip-syntax-forward not-syntaxes (line-end-position))
6052 (setq start (point))
6053 (skip-syntax-forward syntaxes)
6054 (setq end (point)))
6055 (setq end (point))
6056 (skip-syntax-backward syntaxes)
6057 (setq start (point))))
6058 ;; If we found something nonempty, return it as a string.
6059 (unless (= start end)
6060 (buffer-substring-no-properties start end)))))
6062 (defcustom fill-prefix nil
6063 "String for filling to insert at front of new line, or nil for none."
6064 :type '(choice (const :tag "None" nil)
6065 string)
6066 :group 'fill)
6067 (make-variable-buffer-local 'fill-prefix)
6068 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
6070 (defcustom auto-fill-inhibit-regexp nil
6071 "Regexp to match lines which should not be auto-filled."
6072 :type '(choice (const :tag "None" nil)
6073 regexp)
6074 :group 'fill)
6076 (defun do-auto-fill ()
6077 "The default value for `normal-auto-fill-function'.
6078 This is the default auto-fill function, some major modes use a different one.
6079 Returns t if it really did any work."
6080 (let (fc justify give-up
6081 (fill-prefix fill-prefix))
6082 (if (or (not (setq justify (current-justification)))
6083 (null (setq fc (current-fill-column)))
6084 (and (eq justify 'left)
6085 (<= (current-column) fc))
6086 (and auto-fill-inhibit-regexp
6087 (save-excursion (beginning-of-line)
6088 (looking-at auto-fill-inhibit-regexp))))
6089 nil ;; Auto-filling not required
6090 (if (memq justify '(full center right))
6091 (save-excursion (unjustify-current-line)))
6093 ;; Choose a fill-prefix automatically.
6094 (when (and adaptive-fill-mode
6095 (or (null fill-prefix) (string= fill-prefix "")))
6096 (let ((prefix
6097 (fill-context-prefix
6098 (save-excursion (fill-forward-paragraph -1) (point))
6099 (save-excursion (fill-forward-paragraph 1) (point)))))
6100 (and prefix (not (equal prefix ""))
6101 ;; Use auto-indentation rather than a guessed empty prefix.
6102 (not (and fill-indent-according-to-mode
6103 (string-match "\\`[ \t]*\\'" prefix)))
6104 (setq fill-prefix prefix))))
6106 (while (and (not give-up) (> (current-column) fc))
6107 ;; Determine where to split the line.
6108 (let* (after-prefix
6109 (fill-point
6110 (save-excursion
6111 (beginning-of-line)
6112 (setq after-prefix (point))
6113 (and fill-prefix
6114 (looking-at (regexp-quote fill-prefix))
6115 (setq after-prefix (match-end 0)))
6116 (move-to-column (1+ fc))
6117 (fill-move-to-break-point after-prefix)
6118 (point))))
6120 ;; See whether the place we found is any good.
6121 (if (save-excursion
6122 (goto-char fill-point)
6123 (or (bolp)
6124 ;; There is no use breaking at end of line.
6125 (save-excursion (skip-chars-forward " ") (eolp))
6126 ;; It is futile to split at the end of the prefix
6127 ;; since we would just insert the prefix again.
6128 (and after-prefix (<= (point) after-prefix))
6129 ;; Don't split right after a comment starter
6130 ;; since we would just make another comment starter.
6131 (and comment-start-skip
6132 (let ((limit (point)))
6133 (beginning-of-line)
6134 (and (re-search-forward comment-start-skip
6135 limit t)
6136 (eq (point) limit))))))
6137 ;; No good place to break => stop trying.
6138 (setq give-up t)
6139 ;; Ok, we have a useful place to break the line. Do it.
6140 (let ((prev-column (current-column)))
6141 ;; If point is at the fill-point, do not `save-excursion'.
6142 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6143 ;; point will end up before it rather than after it.
6144 (if (save-excursion
6145 (skip-chars-backward " \t")
6146 (= (point) fill-point))
6147 (default-indent-new-line t)
6148 (save-excursion
6149 (goto-char fill-point)
6150 (default-indent-new-line t)))
6151 ;; Now do justification, if required
6152 (if (not (eq justify 'left))
6153 (save-excursion
6154 (end-of-line 0)
6155 (justify-current-line justify nil t)))
6156 ;; If making the new line didn't reduce the hpos of
6157 ;; the end of the line, then give up now;
6158 ;; trying again will not help.
6159 (if (>= (current-column) prev-column)
6160 (setq give-up t))))))
6161 ;; Justify last line.
6162 (justify-current-line justify t t)
6163 t)))
6165 (defvar comment-line-break-function 'comment-indent-new-line
6166 "Mode-specific function which line breaks and continues a comment.
6167 This function is called during auto-filling when a comment syntax
6168 is defined.
6169 The function should take a single optional argument, which is a flag
6170 indicating whether it should use soft newlines.")
6172 (defun default-indent-new-line (&optional soft)
6173 "Break line at point and indent.
6174 If a comment syntax is defined, call `comment-indent-new-line'.
6176 The inserted newline is marked hard if variable `use-hard-newlines' is true,
6177 unless optional argument SOFT is non-nil."
6178 (interactive)
6179 (if comment-start
6180 (funcall comment-line-break-function soft)
6181 ;; Insert the newline before removing empty space so that markers
6182 ;; get preserved better.
6183 (if soft (insert-and-inherit ?\n) (newline 1))
6184 (save-excursion (forward-char -1) (delete-horizontal-space))
6185 (delete-horizontal-space)
6187 (if (and fill-prefix (not adaptive-fill-mode))
6188 ;; Blindly trust a non-adaptive fill-prefix.
6189 (progn
6190 (indent-to-left-margin)
6191 (insert-before-markers-and-inherit fill-prefix))
6193 (cond
6194 ;; If there's an adaptive prefix, use it unless we're inside
6195 ;; a comment and the prefix is not a comment starter.
6196 (fill-prefix
6197 (indent-to-left-margin)
6198 (insert-and-inherit fill-prefix))
6199 ;; If we're not inside a comment, just try to indent.
6200 (t (indent-according-to-mode))))))
6202 (defvar normal-auto-fill-function 'do-auto-fill
6203 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6204 Some major modes set this.")
6206 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
6207 ;; `functions' and `hooks' are usually unsafe to set, but setting
6208 ;; auto-fill-function to nil in a file-local setting is safe and
6209 ;; can be useful to prevent auto-filling.
6210 (put 'auto-fill-function 'safe-local-variable 'null)
6212 (define-minor-mode auto-fill-mode
6213 "Toggle automatic line breaking (Auto Fill mode).
6214 With a prefix argument ARG, enable Auto Fill mode if ARG is
6215 positive, and disable it otherwise. If called from Lisp, enable
6216 the mode if ARG is omitted or nil.
6218 When Auto Fill mode is enabled, inserting a space at a column
6219 beyond `current-fill-column' automatically breaks the line at a
6220 previous space.
6222 When `auto-fill-mode' is on, the `auto-fill-function' variable is
6223 non-`nil'.
6225 The value of `normal-auto-fill-function' specifies the function to use
6226 for `auto-fill-function' when turning Auto Fill mode on."
6227 :variable (auto-fill-function
6228 . (lambda (v) (setq auto-fill-function
6229 (if v normal-auto-fill-function)))))
6231 ;; This holds a document string used to document auto-fill-mode.
6232 (defun auto-fill-function ()
6233 "Automatically break line at a previous space, in insertion of text."
6234 nil)
6236 (defun turn-on-auto-fill ()
6237 "Unconditionally turn on Auto Fill mode."
6238 (auto-fill-mode 1))
6240 (defun turn-off-auto-fill ()
6241 "Unconditionally turn off Auto Fill mode."
6242 (auto-fill-mode -1))
6244 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
6246 (defun set-fill-column (arg)
6247 "Set `fill-column' to specified argument.
6248 Use \\[universal-argument] followed by a number to specify a column.
6249 Just \\[universal-argument] as argument means to use the current column."
6250 (interactive
6251 (list (or current-prefix-arg
6252 ;; We used to use current-column silently, but C-x f is too easily
6253 ;; typed as a typo for C-x C-f, so we turned it into an error and
6254 ;; now an interactive prompt.
6255 (read-number "Set fill-column to: " (current-column)))))
6256 (if (consp arg)
6257 (setq arg (current-column)))
6258 (if (not (integerp arg))
6259 ;; Disallow missing argument; it's probably a typo for C-x C-f.
6260 (error "set-fill-column requires an explicit argument")
6261 (message "Fill column set to %d (was %d)" arg fill-column)
6262 (setq fill-column arg)))
6264 (defun set-selective-display (arg)
6265 "Set `selective-display' to ARG; clear it if no arg.
6266 When the value of `selective-display' is a number > 0,
6267 lines whose indentation is >= that value are not displayed.
6268 The variable `selective-display' has a separate value for each buffer."
6269 (interactive "P")
6270 (if (eq selective-display t)
6271 (error "selective-display already in use for marked lines"))
6272 (let ((current-vpos
6273 (save-restriction
6274 (narrow-to-region (point-min) (point))
6275 (goto-char (window-start))
6276 (vertical-motion (window-height)))))
6277 (setq selective-display
6278 (and arg (prefix-numeric-value arg)))
6279 (recenter current-vpos))
6280 (set-window-start (selected-window) (window-start))
6281 (princ "selective-display set to " t)
6282 (prin1 selective-display t)
6283 (princ "." t))
6285 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
6287 (defun toggle-truncate-lines (&optional arg)
6288 "Toggle truncating of long lines for the current buffer.
6289 When truncating is off, long lines are folded.
6290 With prefix argument ARG, truncate long lines if ARG is positive,
6291 otherwise fold them. Note that in side-by-side windows, this
6292 command has no effect if `truncate-partial-width-windows' is
6293 non-nil."
6294 (interactive "P")
6295 (setq truncate-lines
6296 (if (null arg)
6297 (not truncate-lines)
6298 (> (prefix-numeric-value arg) 0)))
6299 (force-mode-line-update)
6300 (unless truncate-lines
6301 (let ((buffer (current-buffer)))
6302 (walk-windows (lambda (window)
6303 (if (eq buffer (window-buffer window))
6304 (set-window-hscroll window 0)))
6305 nil t)))
6306 (message "Truncate long lines %s"
6307 (if truncate-lines "enabled" "disabled")))
6309 (defun toggle-word-wrap (&optional arg)
6310 "Toggle whether to use word-wrapping for continuation lines.
6311 With prefix argument ARG, wrap continuation lines at word boundaries
6312 if ARG is positive, otherwise wrap them at the right screen edge.
6313 This command toggles the value of `word-wrap'. It has no effect
6314 if long lines are truncated."
6315 (interactive "P")
6316 (setq word-wrap
6317 (if (null arg)
6318 (not word-wrap)
6319 (> (prefix-numeric-value arg) 0)))
6320 (force-mode-line-update)
6321 (message "Word wrapping %s"
6322 (if word-wrap "enabled" "disabled")))
6324 (defvar overwrite-mode-textual (purecopy " Ovwrt")
6325 "The string displayed in the mode line when in overwrite mode.")
6326 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
6327 "The string displayed in the mode line when in binary overwrite mode.")
6329 (define-minor-mode overwrite-mode
6330 "Toggle Overwrite mode.
6331 With a prefix argument ARG, enable Overwrite mode if ARG is
6332 positive, and disable it otherwise. If called from Lisp, enable
6333 the mode if ARG is omitted or nil.
6335 When Overwrite mode is enabled, printing characters typed in
6336 replace existing text on a one-for-one basis, rather than pushing
6337 it to the right. At the end of a line, such characters extend
6338 the line. Before a tab, such characters insert until the tab is
6339 filled in. \\[quoted-insert] still inserts characters in
6340 overwrite mode; this is supposed to make it easier to insert
6341 characters when necessary."
6342 :variable (overwrite-mode
6343 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
6345 (define-minor-mode binary-overwrite-mode
6346 "Toggle Binary Overwrite mode.
6347 With a prefix argument ARG, enable Binary Overwrite mode if ARG
6348 is positive, and disable it otherwise. If called from Lisp,
6349 enable the mode if ARG is omitted or nil.
6351 When Binary Overwrite mode is enabled, printing characters typed
6352 in replace existing text. Newlines are not treated specially, so
6353 typing at the end of a line joins the line to the next, with the
6354 typed character between them. Typing before a tab character
6355 simply replaces the tab with the character typed.
6356 \\[quoted-insert] replaces the text at the cursor, just as
6357 ordinary typing characters do.
6359 Note that Binary Overwrite mode is not its own minor mode; it is
6360 a specialization of overwrite mode, entered by setting the
6361 `overwrite-mode' variable to `overwrite-mode-binary'."
6362 :variable (overwrite-mode
6363 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
6365 (define-minor-mode line-number-mode
6366 "Toggle line number display in the mode line (Line Number mode).
6367 With a prefix argument ARG, enable Line Number mode if ARG is
6368 positive, and disable it otherwise. If called from Lisp, enable
6369 the mode if ARG is omitted or nil.
6371 Line numbers do not appear for very large buffers and buffers
6372 with very long lines; see variables `line-number-display-limit'
6373 and `line-number-display-limit-width'."
6374 :init-value t :global t :group 'mode-line)
6376 (define-minor-mode column-number-mode
6377 "Toggle column number display in the mode line (Column Number mode).
6378 With a prefix argument ARG, enable Column Number mode if ARG is
6379 positive, and disable it otherwise.
6381 If called from Lisp, enable the mode if ARG is omitted or nil."
6382 :global t :group 'mode-line)
6384 (define-minor-mode size-indication-mode
6385 "Toggle buffer size display in the mode line (Size Indication mode).
6386 With a prefix argument ARG, enable Size Indication mode if ARG is
6387 positive, and disable it otherwise.
6389 If called from Lisp, enable the mode if ARG is omitted or nil."
6390 :global t :group 'mode-line)
6392 (define-minor-mode auto-save-mode
6393 "Toggle auto-saving in the current buffer (Auto Save mode).
6394 With a prefix argument ARG, enable Auto Save mode if ARG is
6395 positive, and disable it otherwise.
6397 If called from Lisp, enable the mode if ARG is omitted or nil."
6398 :variable ((and buffer-auto-save-file-name
6399 ;; If auto-save is off because buffer has shrunk,
6400 ;; then toggling should turn it on.
6401 (>= buffer-saved-size 0))
6402 . (lambda (val)
6403 (setq buffer-auto-save-file-name
6404 (cond
6405 ((null val) nil)
6406 ((and buffer-file-name auto-save-visited-file-name
6407 (not buffer-read-only))
6408 buffer-file-name)
6409 (t (make-auto-save-file-name))))))
6410 ;; If -1 was stored here, to temporarily turn off saving,
6411 ;; turn it back on.
6412 (and (< buffer-saved-size 0)
6413 (setq buffer-saved-size 0)))
6415 (defgroup paren-blinking nil
6416 "Blinking matching of parens and expressions."
6417 :prefix "blink-matching-"
6418 :group 'paren-matching)
6420 (defcustom blink-matching-paren t
6421 "Non-nil means show matching open-paren when close-paren is inserted.
6422 If t, highlight the paren. If `jump', move cursor to its position."
6423 :type '(choice
6424 (const :tag "Disable" nil)
6425 (const :tag "Highlight" t)
6426 (const :tag "Move cursor" jump))
6427 :group 'paren-blinking)
6429 (defcustom blink-matching-paren-on-screen t
6430 "Non-nil means show matching open-paren when it is on screen.
6431 If nil, don't show it (but the open-paren can still be shown
6432 when it is off screen).
6434 This variable has no effect if `blink-matching-paren' is nil.
6435 \(In that case, the open-paren is never shown.)
6436 It is also ignored if `show-paren-mode' is enabled."
6437 :type 'boolean
6438 :group 'paren-blinking)
6440 (defcustom blink-matching-paren-distance (* 100 1024)
6441 "If non-nil, maximum distance to search backwards for matching open-paren.
6442 If nil, search stops at the beginning of the accessible portion of the buffer."
6443 :version "23.2" ; 25->100k
6444 :type '(choice (const nil) integer)
6445 :group 'paren-blinking)
6447 (defcustom blink-matching-delay 1
6448 "Time in seconds to delay after showing a matching paren."
6449 :type 'number
6450 :group 'paren-blinking)
6452 (defcustom blink-matching-paren-dont-ignore-comments nil
6453 "If nil, `blink-matching-paren' ignores comments.
6454 More precisely, when looking for the matching parenthesis,
6455 it skips the contents of comments that end before point."
6456 :type 'boolean
6457 :group 'paren-blinking)
6459 (defun blink-matching-check-mismatch (start end)
6460 "Return whether or not START...END are matching parens.
6461 END is the current point and START is the blink position.
6462 START might be nil if no matching starter was found.
6463 Returns non-nil if we find there is a mismatch."
6464 (let* ((end-syntax (syntax-after (1- end)))
6465 (matching-paren (and (consp end-syntax)
6466 (eq (syntax-class end-syntax) 5)
6467 (cdr end-syntax))))
6468 ;; For self-matched chars like " and $, we can't know when they're
6469 ;; mismatched or unmatched, so we can only do it for parens.
6470 (when matching-paren
6471 (not (and start
6473 (eq (char-after start) matching-paren)
6474 ;; The cdr might hold a new paren-class info rather than
6475 ;; a matching-char info, in which case the two CDRs
6476 ;; should match.
6477 (eq matching-paren (cdr-safe (syntax-after start)))))))))
6479 (defvar blink-matching-check-function #'blink-matching-check-mismatch
6480 "Function to check parentheses mismatches.
6481 The function takes two arguments (START and END) where START is the
6482 position just before the opening token and END is the position right after.
6483 START can be nil, if it was not found.
6484 The function should return non-nil if the two tokens do not match.")
6486 (defvar blink-matching--overlay
6487 (let ((ol (make-overlay (point) (point) nil t)))
6488 (overlay-put ol 'face 'show-paren-match)
6489 (delete-overlay ol)
6491 "Overlay used to highlight the matching paren.")
6493 (defun blink-matching-open ()
6494 "Momentarily highlight the beginning of the sexp before point."
6495 (interactive)
6496 (when (and (not (bobp))
6497 blink-matching-paren)
6498 (let* ((oldpos (point))
6499 (message-log-max nil) ; Don't log messages about paren matching.
6500 (blinkpos
6501 (save-excursion
6502 (save-restriction
6503 (if blink-matching-paren-distance
6504 (narrow-to-region
6505 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
6506 (- (point) blink-matching-paren-distance))
6507 oldpos))
6508 (let ((parse-sexp-ignore-comments
6509 (and parse-sexp-ignore-comments
6510 (not blink-matching-paren-dont-ignore-comments))))
6511 (condition-case ()
6512 (progn
6513 (forward-sexp -1)
6514 ;; backward-sexp skips backward over prefix chars,
6515 ;; so move back to the matching paren.
6516 (while (and (< (point) (1- oldpos))
6517 (let ((code (syntax-after (point))))
6518 (or (eq (syntax-class code) 6)
6519 (eq (logand 1048576 (car code))
6520 1048576))))
6521 (forward-char 1))
6522 (point))
6523 (error nil))))))
6524 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
6525 (cond
6526 (mismatch
6527 (if blinkpos
6528 (if (minibufferp)
6529 (minibuffer-message "Mismatched parentheses")
6530 (message "Mismatched parentheses"))
6531 (if (minibufferp)
6532 (minibuffer-message "No matching parenthesis found")
6533 (message "No matching parenthesis found"))))
6534 ((not blinkpos) nil)
6535 ((pos-visible-in-window-p blinkpos)
6536 ;; Matching open within window, temporarily move to or highlight
6537 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
6538 ;; is non-nil.
6539 (and blink-matching-paren-on-screen
6540 (not show-paren-mode)
6541 (if (eq blink-matching-paren 'jump)
6542 (save-excursion
6543 (goto-char blinkpos)
6544 (sit-for blink-matching-delay))
6545 (unwind-protect
6546 (progn
6547 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
6548 (current-buffer))
6549 (sit-for blink-matching-delay))
6550 (delete-overlay blink-matching--overlay)))))
6552 (save-excursion
6553 (goto-char blinkpos)
6554 (let ((open-paren-line-string
6555 ;; Show what precedes the open in its line, if anything.
6556 (cond
6557 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
6558 (buffer-substring (line-beginning-position)
6559 (1+ blinkpos)))
6560 ;; Show what follows the open in its line, if anything.
6561 ((save-excursion
6562 (forward-char 1)
6563 (skip-chars-forward " \t")
6564 (not (eolp)))
6565 (buffer-substring blinkpos
6566 (line-end-position)))
6567 ;; Otherwise show the previous nonblank line,
6568 ;; if there is one.
6569 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
6570 (concat
6571 (buffer-substring (progn
6572 (skip-chars-backward "\n \t")
6573 (line-beginning-position))
6574 (progn (end-of-line)
6575 (skip-chars-backward " \t")
6576 (point)))
6577 ;; Replace the newline and other whitespace with `...'.
6578 "..."
6579 (buffer-substring blinkpos (1+ blinkpos))))
6580 ;; There is nothing to show except the char itself.
6581 (t (buffer-substring blinkpos (1+ blinkpos))))))
6582 (message "Matches %s"
6583 (substring-no-properties open-paren-line-string)))))))))
6585 (defvar blink-paren-function 'blink-matching-open
6586 "Function called, if non-nil, whenever a close parenthesis is inserted.
6587 More precisely, a char with closeparen syntax is self-inserted.")
6589 (defun blink-paren-post-self-insert-function ()
6590 (when (and (eq (char-before) last-command-event) ; Sanity check.
6591 (memq (char-syntax last-command-event) '(?\) ?\$))
6592 blink-paren-function
6593 (not executing-kbd-macro)
6594 (not noninteractive)
6595 ;; Verify an even number of quoting characters precede the close.
6596 (= 1 (logand 1 (- (point)
6597 (save-excursion
6598 (forward-char -1)
6599 (skip-syntax-backward "/\\")
6600 (point))))))
6601 (funcall blink-paren-function)))
6603 (put 'blink-paren-post-self-insert-function 'priority 100)
6605 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
6606 ;; Most likely, this hook is nil, so this arg doesn't matter,
6607 ;; but I use it as a reminder that this function usually
6608 ;; likes to be run after others since it does
6609 ;; `sit-for'. That's also the reason it get a `priority' prop
6610 ;; of 100.
6611 'append)
6613 ;; This executes C-g typed while Emacs is waiting for a command.
6614 ;; Quitting out of a program does not go through here;
6615 ;; that happens in the QUIT macro at the C code level.
6616 (defun keyboard-quit ()
6617 "Signal a `quit' condition.
6618 During execution of Lisp code, this character causes a quit directly.
6619 At top-level, as an editor command, this simply beeps."
6620 (interactive)
6621 ;; Avoid adding the region to the window selection.
6622 (setq saved-region-selection nil)
6623 (let (select-active-regions)
6624 (deactivate-mark))
6625 (if (fboundp 'kmacro-keyboard-quit)
6626 (kmacro-keyboard-quit))
6627 ;; Force the next redisplay cycle to remove the "Def" indicator from
6628 ;; all the mode lines.
6629 (if defining-kbd-macro
6630 (force-mode-line-update t))
6631 (setq defining-kbd-macro nil)
6632 (let ((debug-on-quit nil))
6633 (signal 'quit nil)))
6635 (defvar buffer-quit-function nil
6636 "Function to call to \"quit\" the current buffer, or nil if none.
6637 \\[keyboard-escape-quit] calls this function when its more local actions
6638 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
6640 (defun keyboard-escape-quit ()
6641 "Exit the current \"mode\" (in a generalized sense of the word).
6642 This command can exit an interactive command such as `query-replace',
6643 can clear out a prefix argument or a region,
6644 can get out of the minibuffer or other recursive edit,
6645 cancel the use of the current buffer (for special-purpose buffers),
6646 or go back to just one window (by deleting all but the selected window)."
6647 (interactive)
6648 (cond ((eq last-command 'mode-exited) nil)
6649 ((region-active-p)
6650 (deactivate-mark))
6651 ((> (minibuffer-depth) 0)
6652 (abort-recursive-edit))
6653 (current-prefix-arg
6654 nil)
6655 ((> (recursion-depth) 0)
6656 (exit-recursive-edit))
6657 (buffer-quit-function
6658 (funcall buffer-quit-function))
6659 ((not (one-window-p t))
6660 (delete-other-windows))
6661 ((string-match "^ \\*" (buffer-name (current-buffer)))
6662 (bury-buffer))))
6664 (defun play-sound-file (file &optional volume device)
6665 "Play sound stored in FILE.
6666 VOLUME and DEVICE correspond to the keywords of the sound
6667 specification for `play-sound'."
6668 (interactive "fPlay sound file: ")
6669 (let ((sound (list :file file)))
6670 (if volume
6671 (plist-put sound :volume volume))
6672 (if device
6673 (plist-put sound :device device))
6674 (push 'sound sound)
6675 (play-sound sound)))
6678 (defcustom read-mail-command 'rmail
6679 "Your preference for a mail reading package.
6680 This is used by some keybindings which support reading mail.
6681 See also `mail-user-agent' concerning sending mail."
6682 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
6683 (function-item :tag "Gnus" :format "%t\n" gnus)
6684 (function-item :tag "Emacs interface to MH"
6685 :format "%t\n" mh-rmail)
6686 (function :tag "Other"))
6687 :version "21.1"
6688 :group 'mail)
6690 (defcustom mail-user-agent 'message-user-agent
6691 "Your preference for a mail composition package.
6692 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
6693 outgoing email message. This variable lets you specify which
6694 mail-sending package you prefer.
6696 Valid values include:
6698 `message-user-agent' -- use the Message package.
6699 See Info node `(message)'.
6700 `sendmail-user-agent' -- use the Mail package.
6701 See Info node `(emacs)Sending Mail'.
6702 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
6703 See Info node `(mh-e)'.
6704 `gnus-user-agent' -- like `message-user-agent', but with Gnus
6705 paraphernalia if Gnus is running, particularly
6706 the Gcc: header for archiving.
6708 Additional valid symbols may be available; check with the author of
6709 your package for details. The function should return non-nil if it
6710 succeeds.
6712 See also `read-mail-command' concerning reading mail."
6713 :type '(radio (function-item :tag "Message package"
6714 :format "%t\n"
6715 message-user-agent)
6716 (function-item :tag "Mail package"
6717 :format "%t\n"
6718 sendmail-user-agent)
6719 (function-item :tag "Emacs interface to MH"
6720 :format "%t\n"
6721 mh-e-user-agent)
6722 (function-item :tag "Message with full Gnus features"
6723 :format "%t\n"
6724 gnus-user-agent)
6725 (function :tag "Other"))
6726 :version "23.2" ; sendmail->message
6727 :group 'mail)
6729 (defcustom compose-mail-user-agent-warnings t
6730 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
6731 If the value of `mail-user-agent' is the default, and the user
6732 appears to have customizations applying to the old default,
6733 `compose-mail' issues a warning."
6734 :type 'boolean
6735 :version "23.2"
6736 :group 'mail)
6738 (defun rfc822-goto-eoh ()
6739 "If the buffer starts with a mail header, move point to the header's end.
6740 Otherwise, moves to `point-min'.
6741 The end of the header is the start of the next line, if there is one,
6742 else the end of the last line. This function obeys RFC822."
6743 (goto-char (point-min))
6744 (when (re-search-forward
6745 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
6746 (goto-char (match-beginning 0))))
6748 ;; Used by Rmail (e.g., rmail-forward).
6749 (defvar mail-encode-mml nil
6750 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
6751 the outgoing message before sending it.")
6753 (defun compose-mail (&optional to subject other-headers continue
6754 switch-function yank-action send-actions
6755 return-action)
6756 "Start composing a mail message to send.
6757 This uses the user's chosen mail composition package
6758 as selected with the variable `mail-user-agent'.
6759 The optional arguments TO and SUBJECT specify recipients
6760 and the initial Subject field, respectively.
6762 OTHER-HEADERS is an alist specifying additional
6763 header fields. Elements look like (HEADER . VALUE) where both
6764 HEADER and VALUE are strings.
6766 CONTINUE, if non-nil, says to continue editing a message already
6767 being composed. Interactively, CONTINUE is the prefix argument.
6769 SWITCH-FUNCTION, if non-nil, is a function to use to
6770 switch to and display the buffer used for mail composition.
6772 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
6773 to insert the raw text of the message being replied to.
6774 It has the form (FUNCTION . ARGS). The user agent will apply
6775 FUNCTION to ARGS, to insert the raw text of the original message.
6776 \(The user agent will also run `mail-citation-hook', *after* the
6777 original text has been inserted in this way.)
6779 SEND-ACTIONS is a list of actions to call when the message is sent.
6780 Each action has the form (FUNCTION . ARGS).
6782 RETURN-ACTION, if non-nil, is an action for returning to the
6783 caller. It has the form (FUNCTION . ARGS). The function is
6784 called after the mail has been sent or put aside, and the mail
6785 buffer buried."
6786 (interactive
6787 (list nil nil nil current-prefix-arg))
6789 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
6790 ;; from sendmail-user-agent to message-user-agent. Some users may
6791 ;; encounter incompatibilities. This hack tries to detect problems
6792 ;; and warn about them.
6793 (and compose-mail-user-agent-warnings
6794 (eq mail-user-agent 'message-user-agent)
6795 (let (warn-vars)
6796 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
6797 mail-yank-hooks mail-archive-file-name
6798 mail-default-reply-to mail-mailing-lists
6799 mail-self-blind))
6800 (and (boundp var)
6801 (symbol-value var)
6802 (push var warn-vars)))
6803 (when warn-vars
6804 (display-warning 'mail
6805 (format "\
6806 The default mail mode is now Message mode.
6807 You have the following Mail mode variable%s customized:
6808 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
6809 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
6810 (if (> (length warn-vars) 1) "s" "")
6811 (mapconcat 'symbol-name
6812 warn-vars " "))))))
6814 (let ((function (get mail-user-agent 'composefunc)))
6815 (funcall function to subject other-headers continue switch-function
6816 yank-action send-actions return-action)))
6818 (defun compose-mail-other-window (&optional to subject other-headers continue
6819 yank-action send-actions
6820 return-action)
6821 "Like \\[compose-mail], but edit the outgoing message in another window."
6822 (interactive (list nil nil nil current-prefix-arg))
6823 (compose-mail to subject other-headers continue
6824 'switch-to-buffer-other-window yank-action send-actions
6825 return-action))
6827 (defun compose-mail-other-frame (&optional to subject other-headers continue
6828 yank-action send-actions
6829 return-action)
6830 "Like \\[compose-mail], but edit the outgoing message in another frame."
6831 (interactive (list nil nil nil current-prefix-arg))
6832 (compose-mail to subject other-headers continue
6833 'switch-to-buffer-other-frame yank-action send-actions
6834 return-action))
6837 (defvar set-variable-value-history nil
6838 "History of values entered with `set-variable'.
6840 Maximum length of the history list is determined by the value
6841 of `history-length', which see.")
6843 (defun set-variable (variable value &optional make-local)
6844 "Set VARIABLE to VALUE. VALUE is a Lisp object.
6845 VARIABLE should be a user option variable name, a Lisp variable
6846 meant to be customized by users. You should enter VALUE in Lisp syntax,
6847 so if you want VALUE to be a string, you must surround it with doublequotes.
6848 VALUE is used literally, not evaluated.
6850 If VARIABLE has a `variable-interactive' property, that is used as if
6851 it were the arg to `interactive' (which see) to interactively read VALUE.
6853 If VARIABLE has been defined with `defcustom', then the type information
6854 in the definition is used to check that VALUE is valid.
6856 With a prefix argument, set VARIABLE to VALUE buffer-locally."
6857 (interactive
6858 (let* ((default-var (variable-at-point))
6859 (var (if (custom-variable-p default-var)
6860 (read-variable (format "Set variable (default %s): " default-var)
6861 default-var)
6862 (read-variable "Set variable: ")))
6863 (minibuffer-help-form '(describe-variable var))
6864 (prop (get var 'variable-interactive))
6865 (obsolete (car (get var 'byte-obsolete-variable)))
6866 (prompt (format "Set %s %s to value: " var
6867 (cond ((local-variable-p var)
6868 "(buffer-local)")
6869 ((or current-prefix-arg
6870 (local-variable-if-set-p var))
6871 "buffer-locally")
6872 (t "globally"))))
6873 (val (progn
6874 (when obsolete
6875 (message (concat "`%S' is obsolete; "
6876 (if (symbolp obsolete) "use `%S' instead" "%s"))
6877 var obsolete)
6878 (sit-for 3))
6879 (if prop
6880 ;; Use VAR's `variable-interactive' property
6881 ;; as an interactive spec for prompting.
6882 (call-interactively `(lambda (arg)
6883 (interactive ,prop)
6884 arg))
6885 (read-from-minibuffer prompt nil
6886 read-expression-map t
6887 'set-variable-value-history
6888 (format "%S" (symbol-value var)))))))
6889 (list var val current-prefix-arg)))
6891 (and (custom-variable-p variable)
6892 (not (get variable 'custom-type))
6893 (custom-load-symbol variable))
6894 (let ((type (get variable 'custom-type)))
6895 (when type
6896 ;; Match with custom type.
6897 (require 'cus-edit)
6898 (setq type (widget-convert type))
6899 (unless (widget-apply type :match value)
6900 (error "Value `%S' does not match type %S of %S"
6901 value (car type) variable))))
6903 (if make-local
6904 (make-local-variable variable))
6906 (set variable value)
6908 ;; Force a thorough redisplay for the case that the variable
6909 ;; has an effect on the display, like `tab-width' has.
6910 (force-mode-line-update))
6912 ;; Define the major mode for lists of completions.
6914 (defvar completion-list-mode-map
6915 (let ((map (make-sparse-keymap)))
6916 (define-key map [mouse-2] 'choose-completion)
6917 (define-key map [follow-link] 'mouse-face)
6918 (define-key map [down-mouse-2] nil)
6919 (define-key map "\C-m" 'choose-completion)
6920 (define-key map "\e\e\e" 'delete-completion-window)
6921 (define-key map [left] 'previous-completion)
6922 (define-key map [right] 'next-completion)
6923 (define-key map "q" 'quit-window)
6924 (define-key map "z" 'kill-this-buffer)
6925 map)
6926 "Local map for completion list buffers.")
6928 ;; Completion mode is suitable only for specially formatted data.
6929 (put 'completion-list-mode 'mode-class 'special)
6931 (defvar completion-reference-buffer nil
6932 "Record the buffer that was current when the completion list was requested.
6933 This is a local variable in the completion list buffer.
6934 Initial value is nil to avoid some compiler warnings.")
6936 (defvar completion-no-auto-exit nil
6937 "Non-nil means `choose-completion-string' should never exit the minibuffer.
6938 This also applies to other functions such as `choose-completion'.")
6940 (defvar completion-base-position nil
6941 "Position of the base of the text corresponding to the shown completions.
6942 This variable is used in the *Completions* buffers.
6943 Its value is a list of the form (START END) where START is the place
6944 where the completion should be inserted and END (if non-nil) is the end
6945 of the text to replace. If END is nil, point is used instead.")
6947 (defvar completion-list-insert-choice-function #'completion--replace
6948 "Function to use to insert the text chosen in *Completions*.
6949 Called with three arguments (BEG END TEXT), it should replace the text
6950 between BEG and END with TEXT. Expected to be set buffer-locally
6951 in the *Completions* buffer.")
6953 (defvar completion-base-size nil
6954 "Number of chars before point not involved in completion.
6955 This is a local variable in the completion list buffer.
6956 It refers to the chars in the minibuffer if completing in the
6957 minibuffer, or in `completion-reference-buffer' otherwise.
6958 Only characters in the field at point are included.
6960 If nil, Emacs determines which part of the tail end of the
6961 buffer's text is involved in completion by comparing the text
6962 directly.")
6963 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
6965 (defun delete-completion-window ()
6966 "Delete the completion list window.
6967 Go to the window from which completion was requested."
6968 (interactive)
6969 (let ((buf completion-reference-buffer))
6970 (if (one-window-p t)
6971 (if (window-dedicated-p) (delete-frame))
6972 (delete-window (selected-window))
6973 (if (get-buffer-window buf)
6974 (select-window (get-buffer-window buf))))))
6976 (defun previous-completion (n)
6977 "Move to the previous item in the completion list."
6978 (interactive "p")
6979 (next-completion (- n)))
6981 (defun next-completion (n)
6982 "Move to the next item in the completion list.
6983 With prefix argument N, move N items (negative N means move backward)."
6984 (interactive "p")
6985 (let ((beg (point-min)) (end (point-max)))
6986 (while (and (> n 0) (not (eobp)))
6987 ;; If in a completion, move to the end of it.
6988 (when (get-text-property (point) 'mouse-face)
6989 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
6990 ;; Move to start of next one.
6991 (unless (get-text-property (point) 'mouse-face)
6992 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
6993 (setq n (1- n)))
6994 (while (and (< n 0) (not (bobp)))
6995 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
6996 ;; If in a completion, move to the start of it.
6997 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
6998 (goto-char (previous-single-property-change
6999 (point) 'mouse-face nil beg)))
7000 ;; Move to end of the previous completion.
7001 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
7002 (goto-char (previous-single-property-change
7003 (point) 'mouse-face nil beg)))
7004 ;; Move to the start of that one.
7005 (goto-char (previous-single-property-change
7006 (point) 'mouse-face nil beg))
7007 (setq n (1+ n))))))
7009 (defun choose-completion (&optional event)
7010 "Choose the completion at point.
7011 If EVENT, use EVENT's position to determine the starting position."
7012 (interactive (list last-nonmenu-event))
7013 ;; In case this is run via the mouse, give temporary modes such as
7014 ;; isearch a chance to turn off.
7015 (run-hooks 'mouse-leave-buffer-hook)
7016 (with-current-buffer (window-buffer (posn-window (event-start event)))
7017 (let ((buffer completion-reference-buffer)
7018 (base-size completion-base-size)
7019 (base-position completion-base-position)
7020 (insert-function completion-list-insert-choice-function)
7021 (choice
7022 (save-excursion
7023 (goto-char (posn-point (event-start event)))
7024 (let (beg end)
7025 (cond
7026 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7027 (setq end (point) beg (1+ (point))))
7028 ((and (not (bobp))
7029 (get-text-property (1- (point)) 'mouse-face))
7030 (setq end (1- (point)) beg (point)))
7031 (t (error "No completion here")))
7032 (setq beg (previous-single-property-change beg 'mouse-face))
7033 (setq end (or (next-single-property-change end 'mouse-face)
7034 (point-max)))
7035 (buffer-substring-no-properties beg end)))))
7037 (unless (buffer-live-p buffer)
7038 (error "Destination buffer is dead"))
7039 (quit-window nil (posn-window (event-start event)))
7041 (with-current-buffer buffer
7042 (choose-completion-string
7043 choice buffer
7044 (or base-position
7045 (when base-size
7046 ;; Someone's using old completion code that doesn't know
7047 ;; about base-position yet.
7048 (list (+ base-size (field-beginning))))
7049 ;; If all else fails, just guess.
7050 (list (choose-completion-guess-base-position choice)))
7051 insert-function)))))
7053 ;; Delete the longest partial match for STRING
7054 ;; that can be found before POINT.
7055 (defun choose-completion-guess-base-position (string)
7056 (save-excursion
7057 (let ((opoint (point))
7058 len)
7059 ;; Try moving back by the length of the string.
7060 (goto-char (max (- (point) (length string))
7061 (minibuffer-prompt-end)))
7062 ;; See how far back we were actually able to move. That is the
7063 ;; upper bound on how much we can match and delete.
7064 (setq len (- opoint (point)))
7065 (if completion-ignore-case
7066 (setq string (downcase string)))
7067 (while (and (> len 0)
7068 (let ((tail (buffer-substring (point) opoint)))
7069 (if completion-ignore-case
7070 (setq tail (downcase tail)))
7071 (not (string= tail (substring string 0 len)))))
7072 (setq len (1- len))
7073 (forward-char 1))
7074 (point))))
7076 (defun choose-completion-delete-max-match (string)
7077 (declare (obsolete choose-completion-guess-base-position "23.2"))
7078 (delete-region (choose-completion-guess-base-position string) (point)))
7080 (defvar choose-completion-string-functions nil
7081 "Functions that may override the normal insertion of a completion choice.
7082 These functions are called in order with three arguments:
7083 CHOICE - the string to insert in the buffer,
7084 BUFFER - the buffer in which the choice should be inserted,
7085 BASE-POSITION - where to insert the completion.
7087 If a function in the list returns non-nil, that function is supposed
7088 to have inserted the CHOICE in the BUFFER, and possibly exited
7089 the minibuffer; no further functions will be called.
7091 If all functions in the list return nil, that means to use
7092 the default method of inserting the completion in BUFFER.")
7094 (defun choose-completion-string (choice &optional
7095 buffer base-position insert-function)
7096 "Switch to BUFFER and insert the completion choice CHOICE.
7097 BASE-POSITION says where to insert the completion.
7098 INSERT-FUNCTION says how to insert the completion and falls
7099 back on `completion-list-insert-choice-function' when nil."
7101 ;; If BUFFER is the minibuffer, exit the minibuffer
7102 ;; unless it is reading a file name and CHOICE is a directory,
7103 ;; or completion-no-auto-exit is non-nil.
7105 ;; Some older code may call us passing `base-size' instead of
7106 ;; `base-position'. It's difficult to make any use of `base-size',
7107 ;; so we just ignore it.
7108 (unless (consp base-position)
7109 (message "Obsolete `base-size' passed to choose-completion-string")
7110 (setq base-position nil))
7112 (let* ((buffer (or buffer completion-reference-buffer))
7113 (mini-p (minibufferp buffer)))
7114 ;; If BUFFER is a minibuffer, barf unless it's the currently
7115 ;; active minibuffer.
7116 (if (and mini-p
7117 (not (and (active-minibuffer-window)
7118 (equal buffer
7119 (window-buffer (active-minibuffer-window))))))
7120 (error "Minibuffer is not active for completion")
7121 ;; Set buffer so buffer-local choose-completion-string-functions works.
7122 (set-buffer buffer)
7123 (unless (run-hook-with-args-until-success
7124 'choose-completion-string-functions
7125 ;; The fourth arg used to be `mini-p' but was useless
7126 ;; (since minibufferp can be used on the `buffer' arg)
7127 ;; and indeed unused. The last used to be `base-size', so we
7128 ;; keep it to try and avoid breaking old code.
7129 choice buffer base-position nil)
7130 ;; This remove-text-properties should be unnecessary since `choice'
7131 ;; comes from buffer-substring-no-properties.
7132 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7133 ;; Insert the completion into the buffer where it was requested.
7134 (funcall (or insert-function completion-list-insert-choice-function)
7135 (or (car base-position) (point))
7136 (or (cadr base-position) (point))
7137 choice)
7138 ;; Update point in the window that BUFFER is showing in.
7139 (let ((window (get-buffer-window buffer t)))
7140 (set-window-point window (point)))
7141 ;; If completing for the minibuffer, exit it with this choice.
7142 (and (not completion-no-auto-exit)
7143 (minibufferp buffer)
7144 minibuffer-completion-table
7145 ;; If this is reading a file name, and the file name chosen
7146 ;; is a directory, don't exit the minibuffer.
7147 (let* ((result (buffer-substring (field-beginning) (point)))
7148 (bounds
7149 (completion-boundaries result minibuffer-completion-table
7150 minibuffer-completion-predicate
7151 "")))
7152 (if (eq (car bounds) (length result))
7153 ;; The completion chosen leads to a new set of completions
7154 ;; (e.g. it's a directory): don't exit the minibuffer yet.
7155 (let ((mini (active-minibuffer-window)))
7156 (select-window mini)
7157 (when minibuffer-auto-raise
7158 (raise-frame (window-frame mini))))
7159 (exit-minibuffer))))))))
7161 (define-derived-mode completion-list-mode nil "Completion List"
7162 "Major mode for buffers showing lists of possible completions.
7163 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
7164 to select the completion near point.
7165 Or click to select one with the mouse.
7167 \\{completion-list-mode-map}"
7168 (set (make-local-variable 'completion-base-size) nil))
7170 (defun completion-list-mode-finish ()
7171 "Finish setup of the completions buffer.
7172 Called from `temp-buffer-show-hook'."
7173 (when (eq major-mode 'completion-list-mode)
7174 (setq buffer-read-only t)))
7176 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
7179 ;; Variables and faces used in `completion-setup-function'.
7181 (defcustom completion-show-help t
7182 "Non-nil means show help message in *Completions* buffer."
7183 :type 'boolean
7184 :version "22.1"
7185 :group 'completion)
7187 ;; This function goes in completion-setup-hook, so that it is called
7188 ;; after the text of the completion list buffer is written.
7189 (defun completion-setup-function ()
7190 (let* ((mainbuf (current-buffer))
7191 (base-dir
7192 ;; FIXME: This is a bad hack. We try to set the default-directory
7193 ;; in the *Completions* buffer so that the relative file names
7194 ;; displayed there can be treated as valid file names, independently
7195 ;; from the completion context. But this suffers from many problems:
7196 ;; - It's not clear when the completions are file names. With some
7197 ;; completion tables (e.g. bzr revision specs), the listed
7198 ;; completions can mix file names and other things.
7199 ;; - It doesn't pay attention to possible quoting.
7200 ;; - With fancy completion styles, the code below will not always
7201 ;; find the right base directory.
7202 (if minibuffer-completing-file-name
7203 (file-name-as-directory
7204 (expand-file-name
7205 (buffer-substring (minibuffer-prompt-end)
7206 (- (point) (or completion-base-size 0))))))))
7207 (with-current-buffer standard-output
7208 (let ((base-size completion-base-size) ;Read before killing localvars.
7209 (base-position completion-base-position)
7210 (insert-fun completion-list-insert-choice-function))
7211 (completion-list-mode)
7212 (set (make-local-variable 'completion-base-size) base-size)
7213 (set (make-local-variable 'completion-base-position) base-position)
7214 (set (make-local-variable 'completion-list-insert-choice-function)
7215 insert-fun))
7216 (set (make-local-variable 'completion-reference-buffer) mainbuf)
7217 (if base-dir (setq default-directory base-dir))
7218 ;; Maybe insert help string.
7219 (when completion-show-help
7220 (goto-char (point-min))
7221 (if (display-mouse-p)
7222 (insert (substitute-command-keys
7223 "Click on a completion to select it.\n")))
7224 (insert (substitute-command-keys
7225 "In this buffer, type \\[choose-completion] to \
7226 select the completion near point.\n\n"))))))
7228 (add-hook 'completion-setup-hook 'completion-setup-function)
7230 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
7231 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
7233 (defun switch-to-completions ()
7234 "Select the completion list window."
7235 (interactive)
7236 (let ((window (or (get-buffer-window "*Completions*" 0)
7237 ;; Make sure we have a completions window.
7238 (progn (minibuffer-completion-help)
7239 (get-buffer-window "*Completions*" 0)))))
7240 (when window
7241 (select-window window)
7242 ;; In the new buffer, go to the first completion.
7243 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
7244 (when (bobp)
7245 (next-completion 1)))))
7247 ;;; Support keyboard commands to turn on various modifiers.
7249 ;; These functions -- which are not commands -- each add one modifier
7250 ;; to the following event.
7252 (defun event-apply-alt-modifier (_ignore-prompt)
7253 "\\<function-key-map>Add the Alt modifier to the following event.
7254 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
7255 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
7256 (defun event-apply-super-modifier (_ignore-prompt)
7257 "\\<function-key-map>Add the Super modifier to the following event.
7258 For example, type \\[event-apply-super-modifier] & to enter Super-&."
7259 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
7260 (defun event-apply-hyper-modifier (_ignore-prompt)
7261 "\\<function-key-map>Add the Hyper modifier to the following event.
7262 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
7263 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
7264 (defun event-apply-shift-modifier (_ignore-prompt)
7265 "\\<function-key-map>Add the Shift modifier to the following event.
7266 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
7267 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
7268 (defun event-apply-control-modifier (_ignore-prompt)
7269 "\\<function-key-map>Add the Ctrl modifier to the following event.
7270 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
7271 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
7272 (defun event-apply-meta-modifier (_ignore-prompt)
7273 "\\<function-key-map>Add the Meta modifier to the following event.
7274 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
7275 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
7277 (defun event-apply-modifier (event symbol lshiftby prefix)
7278 "Apply a modifier flag to event EVENT.
7279 SYMBOL is the name of this modifier, as a symbol.
7280 LSHIFTBY is the numeric value of this modifier, in keyboard events.
7281 PREFIX is the string that represents this modifier in an event type symbol."
7282 (if (numberp event)
7283 (cond ((eq symbol 'control)
7284 (if (and (<= (downcase event) ?z)
7285 (>= (downcase event) ?a))
7286 (- (downcase event) ?a -1)
7287 (if (and (<= (downcase event) ?Z)
7288 (>= (downcase event) ?A))
7289 (- (downcase event) ?A -1)
7290 (logior (lsh 1 lshiftby) event))))
7291 ((eq symbol 'shift)
7292 (if (and (<= (downcase event) ?z)
7293 (>= (downcase event) ?a))
7294 (upcase event)
7295 (logior (lsh 1 lshiftby) event)))
7297 (logior (lsh 1 lshiftby) event)))
7298 (if (memq symbol (event-modifiers event))
7299 event
7300 (let ((event-type (if (symbolp event) event (car event))))
7301 (setq event-type (intern (concat prefix (symbol-name event-type))))
7302 (if (symbolp event)
7303 event-type
7304 (cons event-type (cdr event)))))))
7306 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
7307 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
7308 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
7309 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
7310 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
7311 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
7313 ;;;; Keypad support.
7315 ;; Make the keypad keys act like ordinary typing keys. If people add
7316 ;; bindings for the function key symbols, then those bindings will
7317 ;; override these, so this shouldn't interfere with any existing
7318 ;; bindings.
7320 ;; Also tell read-char how to handle these keys.
7321 (mapc
7322 (lambda (keypad-normal)
7323 (let ((keypad (nth 0 keypad-normal))
7324 (normal (nth 1 keypad-normal)))
7325 (put keypad 'ascii-character normal)
7326 (define-key function-key-map (vector keypad) (vector normal))))
7327 ;; See also kp-keys bound in bindings.el.
7328 '((kp-space ?\s)
7329 (kp-tab ?\t)
7330 (kp-enter ?\r)
7331 (kp-separator ?,)
7332 (kp-equal ?=)
7333 ;; Do the same for various keys that are represented as symbols under
7334 ;; GUIs but naturally correspond to characters.
7335 (backspace 127)
7336 (delete 127)
7337 (tab ?\t)
7338 (linefeed ?\n)
7339 (clear ?\C-l)
7340 (return ?\C-m)
7341 (escape ?\e)
7344 ;;;;
7345 ;;;; forking a twin copy of a buffer.
7346 ;;;;
7348 (defvar clone-buffer-hook nil
7349 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
7351 (defvar clone-indirect-buffer-hook nil
7352 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
7354 (defun clone-process (process &optional newname)
7355 "Create a twin copy of PROCESS.
7356 If NEWNAME is nil, it defaults to PROCESS' name;
7357 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
7358 If PROCESS is associated with a buffer, the new process will be associated
7359 with the current buffer instead.
7360 Returns nil if PROCESS has already terminated."
7361 (setq newname (or newname (process-name process)))
7362 (if (string-match "<[0-9]+>\\'" newname)
7363 (setq newname (substring newname 0 (match-beginning 0))))
7364 (when (memq (process-status process) '(run stop open))
7365 (let* ((process-connection-type (process-tty-name process))
7366 (new-process
7367 (if (memq (process-status process) '(open))
7368 (let ((args (process-contact process t)))
7369 (setq args (plist-put args :name newname))
7370 (setq args (plist-put args :buffer
7371 (if (process-buffer process)
7372 (current-buffer))))
7373 (apply 'make-network-process args))
7374 (apply 'start-process newname
7375 (if (process-buffer process) (current-buffer))
7376 (process-command process)))))
7377 (set-process-query-on-exit-flag
7378 new-process (process-query-on-exit-flag process))
7379 (set-process-inherit-coding-system-flag
7380 new-process (process-inherit-coding-system-flag process))
7381 (set-process-filter new-process (process-filter process))
7382 (set-process-sentinel new-process (process-sentinel process))
7383 (set-process-plist new-process (copy-sequence (process-plist process)))
7384 new-process)))
7386 ;; things to maybe add (currently partly covered by `funcall mode'):
7387 ;; - syntax-table
7388 ;; - overlays
7389 (defun clone-buffer (&optional newname display-flag)
7390 "Create and return a twin copy of the current buffer.
7391 Unlike an indirect buffer, the new buffer can be edited
7392 independently of the old one (if it is not read-only).
7393 NEWNAME is the name of the new buffer. It may be modified by
7394 adding or incrementing <N> at the end as necessary to create a
7395 unique buffer name. If nil, it defaults to the name of the
7396 current buffer, with the proper suffix. If DISPLAY-FLAG is
7397 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
7398 clone a file-visiting buffer, or a buffer whose major mode symbol
7399 has a non-nil `no-clone' property, results in an error.
7401 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
7402 current buffer with appropriate suffix. However, if a prefix
7403 argument is given, then the command prompts for NEWNAME in the
7404 minibuffer.
7406 This runs the normal hook `clone-buffer-hook' in the new buffer
7407 after it has been set up properly in other respects."
7408 (interactive
7409 (progn
7410 (if buffer-file-name
7411 (error "Cannot clone a file-visiting buffer"))
7412 (if (get major-mode 'no-clone)
7413 (error "Cannot clone a buffer in %s mode" mode-name))
7414 (list (if current-prefix-arg
7415 (read-buffer "Name of new cloned buffer: " (current-buffer)))
7416 t)))
7417 (if buffer-file-name
7418 (error "Cannot clone a file-visiting buffer"))
7419 (if (get major-mode 'no-clone)
7420 (error "Cannot clone a buffer in %s mode" mode-name))
7421 (setq newname (or newname (buffer-name)))
7422 (if (string-match "<[0-9]+>\\'" newname)
7423 (setq newname (substring newname 0 (match-beginning 0))))
7424 (let ((buf (current-buffer))
7425 (ptmin (point-min))
7426 (ptmax (point-max))
7427 (pt (point))
7428 (mk (if mark-active (mark t)))
7429 (modified (buffer-modified-p))
7430 (mode major-mode)
7431 (lvars (buffer-local-variables))
7432 (process (get-buffer-process (current-buffer)))
7433 (new (generate-new-buffer (or newname (buffer-name)))))
7434 (save-restriction
7435 (widen)
7436 (with-current-buffer new
7437 (insert-buffer-substring buf)))
7438 (with-current-buffer new
7439 (narrow-to-region ptmin ptmax)
7440 (goto-char pt)
7441 (if mk (set-mark mk))
7442 (set-buffer-modified-p modified)
7444 ;; Clone the old buffer's process, if any.
7445 (when process (clone-process process))
7447 ;; Now set up the major mode.
7448 (funcall mode)
7450 ;; Set up other local variables.
7451 (mapc (lambda (v)
7452 (condition-case () ;in case var is read-only
7453 (if (symbolp v)
7454 (makunbound v)
7455 (set (make-local-variable (car v)) (cdr v)))
7456 (error nil)))
7457 lvars)
7459 ;; Run any hooks (typically set up by the major mode
7460 ;; for cloning to work properly).
7461 (run-hooks 'clone-buffer-hook))
7462 (if display-flag
7463 ;; Presumably the current buffer is shown in the selected frame, so
7464 ;; we want to display the clone elsewhere.
7465 (let ((same-window-regexps nil)
7466 (same-window-buffer-names))
7467 (pop-to-buffer new)))
7468 new))
7471 (defun clone-indirect-buffer (newname display-flag &optional norecord)
7472 "Create an indirect buffer that is a twin copy of the current buffer.
7474 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
7475 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
7476 or if not called with a prefix arg, NEWNAME defaults to the current
7477 buffer's name. The name is modified by adding a `<N>' suffix to it
7478 or by incrementing the N in an existing suffix. Trying to clone a
7479 buffer whose major mode symbol has a non-nil `no-clone-indirect'
7480 property results in an error.
7482 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7483 This is always done when called interactively.
7485 Optional third arg NORECORD non-nil means do not put this buffer at the
7486 front of the list of recently selected ones."
7487 (interactive
7488 (progn
7489 (if (get major-mode 'no-clone-indirect)
7490 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7491 (list (if current-prefix-arg
7492 (read-buffer "Name of indirect buffer: " (current-buffer)))
7493 t)))
7494 (if (get major-mode 'no-clone-indirect)
7495 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7496 (setq newname (or newname (buffer-name)))
7497 (if (string-match "<[0-9]+>\\'" newname)
7498 (setq newname (substring newname 0 (match-beginning 0))))
7499 (let* ((name (generate-new-buffer-name newname))
7500 (buffer (make-indirect-buffer (current-buffer) name t)))
7501 (with-current-buffer buffer
7502 (run-hooks 'clone-indirect-buffer-hook))
7503 (when display-flag
7504 (pop-to-buffer buffer norecord))
7505 buffer))
7508 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
7509 "Like `clone-indirect-buffer' but display in another window."
7510 (interactive
7511 (progn
7512 (if (get major-mode 'no-clone-indirect)
7513 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7514 (list (if current-prefix-arg
7515 (read-buffer "Name of indirect buffer: " (current-buffer)))
7516 t)))
7517 (let ((pop-up-windows t))
7518 (clone-indirect-buffer newname display-flag norecord)))
7521 ;;; Handling of Backspace and Delete keys.
7523 (defcustom normal-erase-is-backspace 'maybe
7524 "Set the default behavior of the Delete and Backspace keys.
7526 If set to t, Delete key deletes forward and Backspace key deletes
7527 backward.
7529 If set to nil, both Delete and Backspace keys delete backward.
7531 If set to 'maybe (which is the default), Emacs automatically
7532 selects a behavior. On window systems, the behavior depends on
7533 the keyboard used. If the keyboard has both a Backspace key and
7534 a Delete key, and both are mapped to their usual meanings, the
7535 option's default value is set to t, so that Backspace can be used
7536 to delete backward, and Delete can be used to delete forward.
7538 If not running under a window system, customizing this option
7539 accomplishes a similar effect by mapping C-h, which is usually
7540 generated by the Backspace key, to DEL, and by mapping DEL to C-d
7541 via `keyboard-translate'. The former functionality of C-h is
7542 available on the F1 key. You should probably not use this
7543 setting if you don't have both Backspace, Delete and F1 keys.
7545 Setting this variable with setq doesn't take effect. Programmatically,
7546 call `normal-erase-is-backspace-mode' (which see) instead."
7547 :type '(choice (const :tag "Off" nil)
7548 (const :tag "Maybe" maybe)
7549 (other :tag "On" t))
7550 :group 'editing-basics
7551 :version "21.1"
7552 :set (lambda (symbol value)
7553 ;; The fboundp is because of a problem with :set when
7554 ;; dumping Emacs. It doesn't really matter.
7555 (if (fboundp 'normal-erase-is-backspace-mode)
7556 (normal-erase-is-backspace-mode (or value 0))
7557 (set-default symbol value))))
7559 (defun normal-erase-is-backspace-setup-frame (&optional frame)
7560 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
7561 (unless frame (setq frame (selected-frame)))
7562 (with-selected-frame frame
7563 (unless (terminal-parameter nil 'normal-erase-is-backspace)
7564 (normal-erase-is-backspace-mode
7565 (if (if (eq normal-erase-is-backspace 'maybe)
7566 (and (not noninteractive)
7567 (or (memq system-type '(ms-dos windows-nt))
7568 (memq window-system '(w32 ns))
7569 (and (memq window-system '(x))
7570 (fboundp 'x-backspace-delete-keys-p)
7571 (x-backspace-delete-keys-p))
7572 ;; If the terminal Emacs is running on has erase char
7573 ;; set to ^H, use the Backspace key for deleting
7574 ;; backward, and the Delete key for deleting forward.
7575 (and (null window-system)
7576 (eq tty-erase-char ?\^H))))
7577 normal-erase-is-backspace)
7578 1 0)))))
7580 (define-minor-mode normal-erase-is-backspace-mode
7581 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
7582 With a prefix argument ARG, enable this feature if ARG is
7583 positive, and disable it otherwise. If called from Lisp, enable
7584 the mode if ARG is omitted or nil.
7586 On window systems, when this mode is on, Delete is mapped to C-d
7587 and Backspace is mapped to DEL; when this mode is off, both
7588 Delete and Backspace are mapped to DEL. (The remapping goes via
7589 `local-function-key-map', so binding Delete or Backspace in the
7590 global or local keymap will override that.)
7592 In addition, on window systems, the bindings of C-Delete, M-Delete,
7593 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
7594 the global keymap in accordance with the functionality of Delete and
7595 Backspace. For example, if Delete is remapped to C-d, which deletes
7596 forward, C-Delete is bound to `kill-word', but if Delete is remapped
7597 to DEL, which deletes backward, C-Delete is bound to
7598 `backward-kill-word'.
7600 If not running on a window system, a similar effect is accomplished by
7601 remapping C-h (normally produced by the Backspace key) and DEL via
7602 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
7603 to C-d; if it's off, the keys are not remapped.
7605 When not running on a window system, and this mode is turned on, the
7606 former functionality of C-h is available on the F1 key. You should
7607 probably not turn on this mode on a text-only terminal if you don't
7608 have both Backspace, Delete and F1 keys.
7610 See also `normal-erase-is-backspace'."
7611 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
7612 . (lambda (v)
7613 (setf (terminal-parameter nil 'normal-erase-is-backspace)
7614 (if v 1 0))))
7615 (let ((enabled (eq 1 (terminal-parameter
7616 nil 'normal-erase-is-backspace))))
7618 (cond ((or (memq window-system '(x w32 ns pc))
7619 (memq system-type '(ms-dos windows-nt)))
7620 (let ((bindings
7621 `(([M-delete] [M-backspace])
7622 ([C-M-delete] [C-M-backspace])
7623 ([?\e C-delete] [?\e C-backspace]))))
7625 (if enabled
7626 (progn
7627 (define-key local-function-key-map [delete] [deletechar])
7628 (define-key local-function-key-map [kp-delete] [deletechar])
7629 (define-key local-function-key-map [backspace] [?\C-?])
7630 (dolist (b bindings)
7631 ;; Not sure if input-decode-map is really right, but
7632 ;; keyboard-translate-table (used below) only works
7633 ;; for integer events, and key-translation-table is
7634 ;; global (like the global-map, used earlier).
7635 (define-key input-decode-map (car b) nil)
7636 (define-key input-decode-map (cadr b) nil)))
7637 (define-key local-function-key-map [delete] [?\C-?])
7638 (define-key local-function-key-map [kp-delete] [?\C-?])
7639 (define-key local-function-key-map [backspace] [?\C-?])
7640 (dolist (b bindings)
7641 (define-key input-decode-map (car b) (cadr b))
7642 (define-key input-decode-map (cadr b) (car b))))))
7644 (if enabled
7645 (progn
7646 (keyboard-translate ?\C-h ?\C-?)
7647 (keyboard-translate ?\C-? ?\C-d))
7648 (keyboard-translate ?\C-h ?\C-h)
7649 (keyboard-translate ?\C-? ?\C-?))))
7651 (if (called-interactively-p 'interactive)
7652 (message "Delete key deletes %s"
7653 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
7654 "forward" "backward")))))
7656 (defvar vis-mode-saved-buffer-invisibility-spec nil
7657 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
7659 (define-minor-mode read-only-mode
7660 "Change whether the current buffer is read-only.
7661 With prefix argument ARG, make the buffer read-only if ARG is
7662 positive, otherwise make it writable. If buffer is read-only
7663 and `view-read-only' is non-nil, enter view mode.
7665 Do not call this from a Lisp program unless you really intend to
7666 do the same thing as the \\[read-only-mode] command, including
7667 possibly enabling or disabling View mode. Also, note that this
7668 command works by setting the variable `buffer-read-only', which
7669 does not affect read-only regions caused by text properties. To
7670 ignore read-only status in a Lisp program (whether due to text
7671 properties or buffer state), bind `inhibit-read-only' temporarily
7672 to a non-nil value."
7673 :variable buffer-read-only
7674 (cond
7675 ((and (not buffer-read-only) view-mode)
7676 (View-exit-and-edit)
7677 (make-local-variable 'view-read-only)
7678 (setq view-read-only t)) ; Must leave view mode.
7679 ((and buffer-read-only view-read-only
7680 ;; If view-mode is already active, `view-mode-enter' is a nop.
7681 (not view-mode)
7682 (not (eq (get major-mode 'mode-class) 'special)))
7683 (view-mode-enter))))
7685 (define-minor-mode visible-mode
7686 "Toggle making all invisible text temporarily visible (Visible mode).
7687 With a prefix argument ARG, enable Visible mode if ARG is
7688 positive, and disable it otherwise. If called from Lisp, enable
7689 the mode if ARG is omitted or nil.
7691 This mode works by saving the value of `buffer-invisibility-spec'
7692 and setting it to nil."
7693 :lighter " Vis"
7694 :group 'editing-basics
7695 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
7696 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
7697 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
7698 (when visible-mode
7699 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
7700 buffer-invisibility-spec)
7701 (setq buffer-invisibility-spec nil)))
7703 (defvar messages-buffer-mode-map
7704 (let ((map (make-sparse-keymap)))
7705 (set-keymap-parent map special-mode-map)
7706 (define-key map "g" nil) ; nothing to revert
7707 map))
7709 (define-derived-mode messages-buffer-mode special-mode "Messages"
7710 "Major mode used in the \"*Messages*\" buffer.")
7712 (defun messages-buffer ()
7713 "Return the \"*Messages*\" buffer.
7714 If it does not exist, create and it switch it to `messages-buffer-mode'."
7715 (or (get-buffer "*Messages*")
7716 (with-current-buffer (get-buffer-create "*Messages*")
7717 (messages-buffer-mode)
7718 (current-buffer))))
7721 ;; Minibuffer prompt stuff.
7723 ;;(defun minibuffer-prompt-modification (start end)
7724 ;; (error "You cannot modify the prompt"))
7727 ;;(defun minibuffer-prompt-insertion (start end)
7728 ;; (let ((inhibit-modification-hooks t))
7729 ;; (delete-region start end)
7730 ;; ;; Discard undo information for the text insertion itself
7731 ;; ;; and for the text deletion.above.
7732 ;; (when (consp buffer-undo-list)
7733 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
7734 ;; (message "You cannot modify the prompt")))
7737 ;;(setq minibuffer-prompt-properties
7738 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
7739 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
7742 ;;;; Problematic external packages.
7744 ;; rms says this should be done by specifying symbols that define
7745 ;; versions together with bad values. This is therefore not as
7746 ;; flexible as it could be. See the thread:
7747 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
7748 (defconst bad-packages-alist
7749 ;; Not sure exactly which semantic versions have problems.
7750 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
7751 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
7752 "The version of `semantic' loaded does not work in Emacs 22.
7753 It can cause constant high CPU load.
7754 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
7755 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
7756 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
7757 ;; provided the `CUA-mode' feature. Since this is no longer true,
7758 ;; we can warn the user if the `CUA-mode' feature is ever provided.
7759 (CUA-mode t nil
7760 "CUA-mode is now part of the standard GNU Emacs distribution,
7761 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
7763 You have loaded an older version of CUA-mode which does not work
7764 correctly with this version of Emacs. You should remove the old
7765 version and use the one distributed with Emacs."))
7766 "Alist of packages known to cause problems in this version of Emacs.
7767 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
7768 PACKAGE is either a regular expression to match file names, or a
7769 symbol (a feature name), like for `with-eval-after-load'.
7770 SYMBOL is either the name of a string variable, or `t'. Upon
7771 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
7772 warning using STRING as the message.")
7774 (defun bad-package-check (package)
7775 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
7776 (condition-case nil
7777 (let* ((list (assoc package bad-packages-alist))
7778 (symbol (nth 1 list)))
7779 (and list
7780 (boundp symbol)
7781 (or (eq symbol t)
7782 (and (stringp (setq symbol (eval symbol)))
7783 (string-match-p (nth 2 list) symbol)))
7784 (display-warning package (nth 3 list) :warning)))
7785 (error nil)))
7787 (dolist (elem bad-packages-alist)
7788 (let ((pkg (car elem)))
7789 (with-eval-after-load pkg
7790 (bad-package-check pkg))))
7793 ;;; Generic dispatcher commands
7795 ;; Macro `define-alternatives' is used to create generic commands.
7796 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
7797 ;; that can have different alternative implementations where choosing
7798 ;; among them is exclusively a matter of user preference.
7800 ;; (define-alternatives COMMAND) creates a new interactive command
7801 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
7802 ;; Typically, the user will not need to customize this variable; packages
7803 ;; wanting to add alternative implementations should use
7805 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
7807 (defmacro define-alternatives (command &rest customizations)
7808 "Define the new command `COMMAND'.
7810 The argument `COMMAND' should be a symbol.
7812 Running `M-x COMMAND RET' for the first time prompts for which
7813 alternative to use and records the selected command as a custom
7814 variable.
7816 Running `C-u M-x COMMAND RET' prompts again for an alternative
7817 and overwrites the previous choice.
7819 The variable `COMMAND-alternatives' contains an alist with
7820 alternative implementations of COMMAND. `define-alternatives'
7821 does not have any effect until this variable is set.
7823 CUSTOMIZATIONS, if non-nil, should be composed of alternating
7824 `defcustom' keywords and values to add to the declaration of
7825 `COMMAND-alternatives' (typically :group and :version)."
7826 (let* ((command-name (symbol-name command))
7827 (varalt-name (concat command-name "-alternatives"))
7828 (varalt-sym (intern varalt-name))
7829 (varimp-sym (intern (concat command-name "--implementation"))))
7830 `(progn
7832 (defcustom ,varalt-sym nil
7833 ,(format "Alist of alternative implementations for the `%s' command.
7835 Each entry must be a pair (ALTNAME . ALTFUN), where:
7836 ALTNAME - The name shown at user to describe the alternative implementation.
7837 ALTFUN - The function called to implement this alternative."
7838 command-name)
7839 :type '(alist :key-type string :value-type function)
7840 ,@customizations)
7842 (put ',varalt-sym 'definition-name ',command)
7843 (defvar ,varimp-sym nil "Internal use only.")
7845 (defun ,command (&optional arg)
7846 ,(format "Run generic command `%s'.
7847 If used for the first time, or with interactive ARG, ask the user which
7848 implementation to use for `%s'. The variable `%s'
7849 contains the list of implementations currently supported for this command."
7850 command-name command-name varalt-name)
7851 (interactive "P")
7852 (when (or arg (null ,varimp-sym))
7853 (let ((val (completing-read
7854 ,(format "Select implementation for command `%s': "
7855 command-name)
7856 ,varalt-sym nil t)))
7857 (unless (string-equal val "")
7858 (when (null ,varimp-sym)
7859 (message
7860 "Use `C-u M-x %s RET' to select another implementation"
7861 ,command-name)
7862 (sit-for 3))
7863 (customize-save-variable ',varimp-sym
7864 (cdr (assoc-string val ,varalt-sym))))))
7865 (if ,varimp-sym
7866 (call-interactively ,varimp-sym)
7867 (message ,(format "No implementation selected for command `%s'"
7868 command-name)))))))
7871 ;; This is here because files in obsolete/ are not scanned for autoloads.
7873 (defvar iswitchb-mode nil "\
7874 Non-nil if Iswitchb mode is enabled.
7875 See the command `iswitchb-mode' for a description of this minor mode.
7876 Setting this variable directly does not take effect;
7877 either customize it (see the info node `Easy Customization')
7878 or call the function `iswitchb-mode'.")
7880 (custom-autoload 'iswitchb-mode "iswitchb" nil)
7882 (autoload 'iswitchb-mode "iswitchb" "\
7883 Toggle Iswitchb mode.
7884 With a prefix argument ARG, enable Iswitchb mode if ARG is
7885 positive, and disable it otherwise. If called from Lisp, enable
7886 the mode if ARG is omitted or nil.
7888 Iswitchb mode is a global minor mode that enables switching
7889 between buffers using substrings. See `iswitchb' for details.
7891 \(fn &optional ARG)" t nil)
7893 (make-obsolete 'iswitchb-mode
7894 "use `icomplete-mode' or `ido-mode' instead." "24.4")
7897 (provide 'simple)
7899 ;;; simple.el ends here