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