Backport fix to bug #18749 to Emacs-24 branch.
[emacs.git] / lisp / simple.el
blob0c0e81583037a313bcb871a2a8fd690f9b68c4a4
1 ;;; simple.el --- basic editing commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1993-2014 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: internal
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; A grab-bag of basic Emacs commands not specifically related to some
27 ;; major mode or to file-handling.
29 ;;; Code:
31 (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)
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)))
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" "passphrase" "pass phrase"
2608 ; These are sorted according to the GNU en_US locale.
2609 "암호" ; ko
2610 "パスワード" ; ja
2611 "ପ୍ରବେଶ ସଙ୍କେତ" ; or
2612 "ពាក្យសម្ងាត់" ; km
2613 "adgangskode" ; da
2614 "contraseña" ; es
2615 "contrasenya" ; ca
2616 "geslo" ; sl
2617 "hasło" ; pl
2618 "heslo" ; cs, sk
2619 "iphasiwedi" ; zu
2620 "jelszó" ; hu
2621 "lösenord" ; sv
2622 "lozinka" ; hr, sr
2623 "mật khẩu" ; vi
2624 "mot de passe" ; fr
2625 "parola" ; tr
2626 "pasahitza" ; eu
2627 "passord" ; nb
2628 "passwort" ; de
2629 "pasvorto" ; eo
2630 "salasana" ; fi
2631 "senha" ; pt
2632 "slaptažodis" ; lt
2633 "wachtwoord" ; nl
2634 "كلمة السر" ; ar
2635 "ססמה" ; he
2636 "лозинка" ; sr
2637 "пароль" ; kk, ru, uk
2638 "गुप्तशब्द" ; mr
2639 "शब्दकूट" ; hi
2640 "પાસવર્ડ" ; gu
2641 "సంకేతపదము" ; te
2642 "ਪਾਸਵਰਡ" ; pa
2643 "ಗುಪ್ತಪದ" ; kn
2644 "கடவுச்சொல்" ; ta
2645 "അടയാളവാക്ക്" ; ml
2646 "গুপ্তশব্দ" ; as
2647 "পাসওয়ার্ড" ; bn_IN
2648 "රහස්පදය" ; si
2649 "密码" ; zh_CN
2650 "密碼" ; zh_TW
2652 "List of words equivalent to \"password\".
2653 This is used by Shell mode and other parts of Emacs to recognize
2654 password prompts, including prompts in languages other than
2655 English. Different case choices should not be assumed to be
2656 included; callers should bind `case-fold-search' to t."
2657 :type '(repeat string)
2658 :version "24.4"
2659 :group 'processes)
2661 (defvar shell-command-history nil
2662 "History list for some commands that read shell commands.
2664 Maximum length of the history list is determined by the value
2665 of `history-length', which see.")
2667 (defvar shell-command-switch (purecopy "-c")
2668 "Switch used to have the shell execute its command line argument.")
2670 (defvar shell-command-default-error-buffer nil
2671 "Buffer name for `shell-command' and `shell-command-on-region' error output.
2672 This buffer is used when `shell-command' or `shell-command-on-region'
2673 is run interactively. A value of nil means that output to stderr and
2674 stdout will be intermixed in the output stream.")
2676 (declare-function mailcap-file-default-commands "mailcap" (files))
2677 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2679 (defun minibuffer-default-add-shell-commands ()
2680 "Return a list of all commands associated with the current file.
2681 This function is used to add all related commands retrieved by `mailcap'
2682 to the end of the list of defaults just after the default value."
2683 (interactive)
2684 (let* ((filename (if (listp minibuffer-default)
2685 (car minibuffer-default)
2686 minibuffer-default))
2687 (commands (and filename (require 'mailcap nil t)
2688 (mailcap-file-default-commands (list filename)))))
2689 (setq commands (mapcar (lambda (command)
2690 (concat command " " filename))
2691 commands))
2692 (if (listp minibuffer-default)
2693 (append minibuffer-default commands)
2694 (cons minibuffer-default commands))))
2696 (declare-function shell-completion-vars "shell" ())
2698 (defvar minibuffer-local-shell-command-map
2699 (let ((map (make-sparse-keymap)))
2700 (set-keymap-parent map minibuffer-local-map)
2701 (define-key map "\t" 'completion-at-point)
2702 map)
2703 "Keymap used for completing shell commands in minibuffer.")
2705 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
2706 "Read a shell command from the minibuffer.
2707 The arguments are the same as the ones of `read-from-minibuffer',
2708 except READ and KEYMAP are missing and HIST defaults
2709 to `shell-command-history'."
2710 (require 'shell)
2711 (minibuffer-with-setup-hook
2712 (lambda ()
2713 (shell-completion-vars)
2714 (set (make-local-variable 'minibuffer-default-add-function)
2715 'minibuffer-default-add-shell-commands))
2716 (apply 'read-from-minibuffer prompt initial-contents
2717 minibuffer-local-shell-command-map
2719 (or hist 'shell-command-history)
2720 args)))
2722 (defcustom async-shell-command-buffer 'confirm-new-buffer
2723 "What to do when the output buffer is used by another shell command.
2724 This option specifies how to resolve the conflict where a new command
2725 wants to direct its output to the buffer `*Async Shell Command*',
2726 but this buffer is already taken by another running shell command.
2728 The value `confirm-kill-process' is used to ask for confirmation before
2729 killing the already running process and running a new process
2730 in the same buffer, `confirm-new-buffer' for confirmation before running
2731 the command in a new buffer with a name other than the default buffer name,
2732 `new-buffer' for doing the same without confirmation,
2733 `confirm-rename-buffer' for confirmation before renaming the existing
2734 output buffer and running a new command in the default buffer,
2735 `rename-buffer' for doing the same without confirmation."
2736 :type '(choice (const :tag "Confirm killing of running command"
2737 confirm-kill-process)
2738 (const :tag "Confirm creation of a new buffer"
2739 confirm-new-buffer)
2740 (const :tag "Create a new buffer"
2741 new-buffer)
2742 (const :tag "Confirm renaming of existing buffer"
2743 confirm-rename-buffer)
2744 (const :tag "Rename the existing buffer"
2745 rename-buffer))
2746 :group 'shell
2747 :version "24.3")
2749 (defun async-shell-command (command &optional output-buffer error-buffer)
2750 "Execute string COMMAND asynchronously in background.
2752 Like `shell-command', but adds `&' at the end of COMMAND
2753 to execute it asynchronously.
2755 The output appears in the buffer `*Async Shell Command*'.
2756 That buffer is in shell mode.
2758 You can configure `async-shell-command-buffer' to specify what to do in
2759 case when `*Async Shell Command*' buffer is already taken by another
2760 running shell command. To run COMMAND without displaying the output
2761 in a window you can configure `display-buffer-alist' to use the action
2762 `display-buffer-no-window' for the buffer `*Async Shell Command*'.
2764 In Elisp, you will often be better served by calling `start-process'
2765 directly, since it offers more control and does not impose the use of a
2766 shell (with its need to quote arguments)."
2767 (interactive
2768 (list
2769 (read-shell-command "Async shell command: " nil nil
2770 (let ((filename
2771 (cond
2772 (buffer-file-name)
2773 ((eq major-mode 'dired-mode)
2774 (dired-get-filename nil t)))))
2775 (and filename (file-relative-name filename))))
2776 current-prefix-arg
2777 shell-command-default-error-buffer))
2778 (unless (string-match "&[ \t]*\\'" command)
2779 (setq command (concat command " &")))
2780 (shell-command command output-buffer error-buffer))
2782 (defun shell-command (command &optional output-buffer error-buffer)
2783 "Execute string COMMAND in inferior shell; display output, if any.
2784 With prefix argument, insert the COMMAND's output at point.
2786 If COMMAND ends in `&', execute it asynchronously.
2787 The output appears in the buffer `*Async Shell Command*'.
2788 That buffer is in shell mode. You can also use
2789 `async-shell-command' that automatically adds `&'.
2791 Otherwise, COMMAND is executed synchronously. The output appears in
2792 the buffer `*Shell Command Output*'. If the output is short enough to
2793 display in the echo area (which is determined by the variables
2794 `resize-mini-windows' and `max-mini-window-height'), it is shown
2795 there, but it is nonetheless available in buffer `*Shell Command
2796 Output*' even though that buffer is not automatically displayed.
2798 To specify a coding system for converting non-ASCII characters
2799 in the shell command output, use \\[universal-coding-system-argument] \
2800 before this command.
2802 Noninteractive callers can specify coding systems by binding
2803 `coding-system-for-read' and `coding-system-for-write'.
2805 The optional second argument OUTPUT-BUFFER, if non-nil,
2806 says to put the output in some other buffer.
2807 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2808 If OUTPUT-BUFFER is not a buffer and not nil,
2809 insert output in current buffer. (This cannot be done asynchronously.)
2810 In either case, the buffer is first erased, and the output is
2811 inserted after point (leaving mark after it).
2813 If the command terminates without error, but generates output,
2814 and you did not specify \"insert it in the current buffer\",
2815 the output can be displayed in the echo area or in its buffer.
2816 If the output is short enough to display in the echo area
2817 \(determined by the variable `max-mini-window-height' if
2818 `resize-mini-windows' is non-nil), it is shown there.
2819 Otherwise,the buffer containing the output is displayed.
2821 If there is output and an error, and you did not specify \"insert it
2822 in the current buffer\", a message about the error goes at the end
2823 of the output.
2825 If there is no output, or if output is inserted in the current buffer,
2826 then `*Shell Command Output*' is deleted.
2828 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2829 or buffer name to which to direct the command's standard error output.
2830 If it is nil, error output is mingled with regular output.
2831 In an interactive call, the variable `shell-command-default-error-buffer'
2832 specifies the value of ERROR-BUFFER.
2834 In Elisp, you will often be better served by calling `call-process' or
2835 `start-process' directly, since it offers more control and does not impose
2836 the use of a shell (with its need to quote arguments)."
2838 (interactive
2839 (list
2840 (read-shell-command "Shell command: " nil nil
2841 (let ((filename
2842 (cond
2843 (buffer-file-name)
2844 ((eq major-mode 'dired-mode)
2845 (dired-get-filename nil t)))))
2846 (and filename (file-relative-name filename))))
2847 current-prefix-arg
2848 shell-command-default-error-buffer))
2849 ;; Look for a handler in case default-directory is a remote file name.
2850 (let ((handler
2851 (find-file-name-handler (directory-file-name default-directory)
2852 'shell-command)))
2853 (if handler
2854 (funcall handler 'shell-command command output-buffer error-buffer)
2855 (if (and output-buffer
2856 (not (or (bufferp output-buffer) (stringp output-buffer))))
2857 ;; Output goes in current buffer.
2858 (let ((error-file
2859 (if error-buffer
2860 (make-temp-file
2861 (expand-file-name "scor"
2862 (or small-temporary-file-directory
2863 temporary-file-directory)))
2864 nil)))
2865 (barf-if-buffer-read-only)
2866 (push-mark nil t)
2867 ;; We do not use -f for csh; we will not support broken use of
2868 ;; .cshrcs. Even the BSD csh manual says to use
2869 ;; "if ($?prompt) exit" before things which are not useful
2870 ;; non-interactively. Besides, if someone wants their other
2871 ;; aliases for shell commands then they can still have them.
2872 (call-process shell-file-name nil
2873 (if error-file
2874 (list t error-file)
2876 nil shell-command-switch command)
2877 (when (and error-file (file-exists-p error-file))
2878 (if (< 0 (nth 7 (file-attributes error-file)))
2879 (with-current-buffer (get-buffer-create error-buffer)
2880 (let ((pos-from-end (- (point-max) (point))))
2881 (or (bobp)
2882 (insert "\f\n"))
2883 ;; Do no formatting while reading error file,
2884 ;; because that can run a shell command, and we
2885 ;; don't want that to cause an infinite recursion.
2886 (format-insert-file error-file nil)
2887 ;; Put point after the inserted errors.
2888 (goto-char (- (point-max) pos-from-end)))
2889 (display-buffer (current-buffer))))
2890 (delete-file error-file))
2891 ;; This is like exchange-point-and-mark, but doesn't
2892 ;; activate the mark. It is cleaner to avoid activation,
2893 ;; even though the command loop would deactivate the mark
2894 ;; because we inserted text.
2895 (goto-char (prog1 (mark t)
2896 (set-marker (mark-marker) (point)
2897 (current-buffer)))))
2898 ;; Output goes in a separate buffer.
2899 ;; Preserve the match data in case called from a program.
2900 (save-match-data
2901 (if (string-match "[ \t]*&[ \t]*\\'" command)
2902 ;; Command ending with ampersand means asynchronous.
2903 (let ((buffer (get-buffer-create
2904 (or output-buffer "*Async Shell Command*")))
2905 (directory default-directory)
2906 proc)
2907 ;; Remove the ampersand.
2908 (setq command (substring command 0 (match-beginning 0)))
2909 ;; Ask the user what to do with already running process.
2910 (setq proc (get-buffer-process buffer))
2911 (when proc
2912 (cond
2913 ((eq async-shell-command-buffer 'confirm-kill-process)
2914 ;; If will kill a process, query first.
2915 (if (yes-or-no-p "A command is running in the default buffer. Kill it? ")
2916 (kill-process proc)
2917 (error "Shell command in progress")))
2918 ((eq async-shell-command-buffer 'confirm-new-buffer)
2919 ;; If will create a new buffer, query first.
2920 (if (yes-or-no-p "A command is running in the default buffer. Use a new buffer? ")
2921 (setq buffer (generate-new-buffer
2922 (or output-buffer "*Async Shell Command*")))
2923 (error "Shell command in progress")))
2924 ((eq async-shell-command-buffer 'new-buffer)
2925 ;; It will create a new buffer.
2926 (setq buffer (generate-new-buffer
2927 (or output-buffer "*Async Shell Command*"))))
2928 ((eq async-shell-command-buffer 'confirm-rename-buffer)
2929 ;; If will rename the buffer, query first.
2930 (if (yes-or-no-p "A command is running in the default buffer. Rename it? ")
2931 (progn
2932 (with-current-buffer buffer
2933 (rename-uniquely))
2934 (setq buffer (get-buffer-create
2935 (or output-buffer "*Async Shell Command*"))))
2936 (error "Shell command in progress")))
2937 ((eq async-shell-command-buffer 'rename-buffer)
2938 ;; It will rename the buffer.
2939 (with-current-buffer buffer
2940 (rename-uniquely))
2941 (setq buffer (get-buffer-create
2942 (or output-buffer "*Async Shell Command*"))))))
2943 (with-current-buffer buffer
2944 (setq buffer-read-only nil)
2945 ;; Setting buffer-read-only to nil doesn't suffice
2946 ;; if some text has a non-nil read-only property,
2947 ;; which comint sometimes adds for prompts.
2948 (let ((inhibit-read-only t))
2949 (erase-buffer))
2950 (display-buffer buffer '(nil (allow-no-window . t)))
2951 (setq default-directory directory)
2952 (setq proc (start-process "Shell" buffer shell-file-name
2953 shell-command-switch command))
2954 (setq mode-line-process '(":%s"))
2955 (require 'shell) (shell-mode)
2956 (set-process-sentinel proc 'shell-command-sentinel)
2957 ;; Use the comint filter for proper handling of carriage motion
2958 ;; (see `comint-inhibit-carriage-motion'),.
2959 (set-process-filter proc 'comint-output-filter)
2961 ;; Otherwise, command is executed synchronously.
2962 (shell-command-on-region (point) (point) command
2963 output-buffer nil error-buffer)))))))
2965 (defun display-message-or-buffer (message
2966 &optional buffer-name not-this-window frame)
2967 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2968 MESSAGE may be either a string or a buffer.
2970 A buffer is displayed using `display-buffer' if MESSAGE is too long for
2971 the maximum height of the echo area, as defined by `max-mini-window-height'
2972 if `resize-mini-windows' is non-nil.
2974 Returns either the string shown in the echo area, or when a pop-up
2975 buffer is used, the window used to display it.
2977 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2978 name of the buffer used to display it in the case where a pop-up buffer
2979 is used, defaulting to `*Message*'. In the case where MESSAGE is a
2980 string and it is displayed in the echo area, it is not specified whether
2981 the contents are inserted into the buffer anyway.
2983 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
2984 and only used if a buffer is displayed."
2985 (cond ((and (stringp message) (not (string-match "\n" message)))
2986 ;; Trivial case where we can use the echo area
2987 (message "%s" message))
2988 ((and (stringp message)
2989 (= (string-match "\n" message) (1- (length message))))
2990 ;; Trivial case where we can just remove single trailing newline
2991 (message "%s" (substring message 0 (1- (length message)))))
2993 ;; General case
2994 (with-current-buffer
2995 (if (bufferp message)
2996 message
2997 (get-buffer-create (or buffer-name "*Message*")))
2999 (unless (bufferp message)
3000 (erase-buffer)
3001 (insert message))
3003 (let ((lines
3004 (if (= (buffer-size) 0)
3006 (count-screen-lines nil nil nil (minibuffer-window)))))
3007 (cond ((= lines 0))
3008 ((and (or (<= lines 1)
3009 (<= lines
3010 (if resize-mini-windows
3011 (cond ((floatp max-mini-window-height)
3012 (* (frame-height)
3013 max-mini-window-height))
3014 ((integerp max-mini-window-height)
3015 max-mini-window-height)
3018 1)))
3019 ;; Don't use the echo area if the output buffer is
3020 ;; already displayed in the selected frame.
3021 (not (get-buffer-window (current-buffer))))
3022 ;; Echo area
3023 (goto-char (point-max))
3024 (when (bolp)
3025 (backward-char 1))
3026 (message "%s" (buffer-substring (point-min) (point))))
3028 ;; Buffer
3029 (goto-char (point-min))
3030 (display-buffer (current-buffer)
3031 not-this-window frame))))))))
3034 ;; We have a sentinel to prevent insertion of a termination message
3035 ;; in the buffer itself.
3036 (defun shell-command-sentinel (process signal)
3037 (if (memq (process-status process) '(exit signal))
3038 (message "%s: %s."
3039 (car (cdr (cdr (process-command process))))
3040 (substring signal 0 -1))))
3042 (defun shell-command-on-region (start end command
3043 &optional output-buffer replace
3044 error-buffer display-error-buffer)
3045 "Execute string COMMAND in inferior shell with region as input.
3046 Normally display output (if any) in temp buffer `*Shell Command Output*';
3047 Prefix arg means replace the region with it. Return the exit code of
3048 COMMAND.
3050 To specify a coding system for converting non-ASCII characters
3051 in the input and output to the shell command, use \\[universal-coding-system-argument]
3052 before this command. By default, the input (from the current buffer)
3053 is encoded using coding-system specified by `process-coding-system-alist',
3054 falling back to `default-process-coding-system' if no match for COMMAND
3055 is found in `process-coding-system-alist'.
3057 Noninteractive callers can specify coding systems by binding
3058 `coding-system-for-read' and `coding-system-for-write'.
3060 If the command generates output, the output may be displayed
3061 in the echo area or in a buffer.
3062 If the output is short enough to display in the echo area
3063 \(determined by the variable `max-mini-window-height' if
3064 `resize-mini-windows' is non-nil), it is shown there.
3065 Otherwise it is displayed in the buffer `*Shell Command Output*'.
3066 The output is available in that buffer in both cases.
3068 If there is output and an error, a message about the error
3069 appears at the end of the output. If there is no output, or if
3070 output is inserted in the current buffer, the buffer `*Shell
3071 Command Output*' is deleted.
3073 Optional fourth arg OUTPUT-BUFFER specifies where to put the
3074 command's output. If the value is a buffer or buffer name,
3075 put the output there. If the value is nil, use the buffer
3076 `*Shell Command Output*'. Any other value, excluding nil,
3077 means to insert the output in the current buffer. In either case,
3078 the output is inserted after point (leaving mark after it).
3080 Optional fifth arg REPLACE, if non-nil, means to insert the
3081 output in place of text from START to END, putting point and mark
3082 around it.
3084 Optional sixth arg ERROR-BUFFER, if non-nil, specifies a buffer
3085 or buffer name to which to direct the command's standard error
3086 output. If nil, error output is mingled with regular output.
3087 When called interactively, `shell-command-default-error-buffer'
3088 is used for ERROR-BUFFER.
3090 Optional seventh arg DISPLAY-ERROR-BUFFER, if non-nil, means to
3091 display the error buffer if there were any errors. When called
3092 interactively, this is t."
3093 (interactive (let (string)
3094 (unless (mark)
3095 (error "The mark is not set now, so there is no region"))
3096 ;; Do this before calling region-beginning
3097 ;; and region-end, in case subprocess output
3098 ;; relocates them while we are in the minibuffer.
3099 (setq string (read-shell-command "Shell command on region: "))
3100 ;; call-interactively recognizes region-beginning and
3101 ;; region-end specially, leaving them in the history.
3102 (list (region-beginning) (region-end)
3103 string
3104 current-prefix-arg
3105 current-prefix-arg
3106 shell-command-default-error-buffer
3107 t)))
3108 (let ((error-file
3109 (if error-buffer
3110 (make-temp-file
3111 (expand-file-name "scor"
3112 (or small-temporary-file-directory
3113 temporary-file-directory)))
3114 nil))
3115 exit-status)
3116 (if (or replace
3117 (and output-buffer
3118 (not (or (bufferp output-buffer) (stringp output-buffer)))))
3119 ;; Replace specified region with output from command.
3120 (let ((swap (and replace (< start end))))
3121 ;; Don't muck with mark unless REPLACE says we should.
3122 (goto-char start)
3123 (and replace (push-mark (point) 'nomsg))
3124 (setq exit-status
3125 (call-process-region start end shell-file-name replace
3126 (if error-file
3127 (list t error-file)
3129 nil shell-command-switch command))
3130 ;; It is rude to delete a buffer which the command is not using.
3131 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
3132 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
3133 ;; (kill-buffer shell-buffer)))
3134 ;; Don't muck with mark unless REPLACE says we should.
3135 (and replace swap (exchange-point-and-mark)))
3136 ;; No prefix argument: put the output in a temp buffer,
3137 ;; replacing its entire contents.
3138 (let ((buffer (get-buffer-create
3139 (or output-buffer "*Shell Command Output*"))))
3140 (unwind-protect
3141 (if (eq buffer (current-buffer))
3142 ;; If the input is the same buffer as the output,
3143 ;; delete everything but the specified region,
3144 ;; then replace that region with the output.
3145 (progn (setq buffer-read-only nil)
3146 (delete-region (max start end) (point-max))
3147 (delete-region (point-min) (min start end))
3148 (setq exit-status
3149 (call-process-region (point-min) (point-max)
3150 shell-file-name t
3151 (if error-file
3152 (list t error-file)
3154 nil shell-command-switch
3155 command)))
3156 ;; Clear the output buffer, then run the command with
3157 ;; output there.
3158 (let ((directory default-directory))
3159 (with-current-buffer buffer
3160 (setq buffer-read-only nil)
3161 (if (not output-buffer)
3162 (setq default-directory directory))
3163 (erase-buffer)))
3164 (setq exit-status
3165 (call-process-region start end shell-file-name nil
3166 (if error-file
3167 (list buffer error-file)
3168 buffer)
3169 nil shell-command-switch command)))
3170 ;; Report the output.
3171 (with-current-buffer buffer
3172 (setq mode-line-process
3173 (cond ((null exit-status)
3174 " - Error")
3175 ((stringp exit-status)
3176 (format " - Signal [%s]" exit-status))
3177 ((not (equal 0 exit-status))
3178 (format " - Exit [%d]" exit-status)))))
3179 (if (with-current-buffer buffer (> (point-max) (point-min)))
3180 ;; There's some output, display it
3181 (display-message-or-buffer buffer)
3182 ;; No output; error?
3183 (let ((output
3184 (if (and error-file
3185 (< 0 (nth 7 (file-attributes error-file))))
3186 (format "some error output%s"
3187 (if shell-command-default-error-buffer
3188 (format " to the \"%s\" buffer"
3189 shell-command-default-error-buffer)
3190 ""))
3191 "no output")))
3192 (cond ((null exit-status)
3193 (message "(Shell command failed with error)"))
3194 ((equal 0 exit-status)
3195 (message "(Shell command succeeded with %s)"
3196 output))
3197 ((stringp exit-status)
3198 (message "(Shell command killed by signal %s)"
3199 exit-status))
3201 (message "(Shell command failed with code %d and %s)"
3202 exit-status output))))
3203 ;; Don't kill: there might be useful info in the undo-log.
3204 ;; (kill-buffer buffer)
3205 ))))
3207 (when (and error-file (file-exists-p error-file))
3208 (if (< 0 (nth 7 (file-attributes error-file)))
3209 (with-current-buffer (get-buffer-create error-buffer)
3210 (let ((pos-from-end (- (point-max) (point))))
3211 (or (bobp)
3212 (insert "\f\n"))
3213 ;; Do no formatting while reading error file,
3214 ;; because that can run a shell command, and we
3215 ;; don't want that to cause an infinite recursion.
3216 (format-insert-file error-file nil)
3217 ;; Put point after the inserted errors.
3218 (goto-char (- (point-max) pos-from-end)))
3219 (and display-error-buffer
3220 (display-buffer (current-buffer)))))
3221 (delete-file error-file))
3222 exit-status))
3224 (defun shell-command-to-string (command)
3225 "Execute shell command COMMAND and return its output as a string."
3226 (with-output-to-string
3227 (with-current-buffer
3228 standard-output
3229 (process-file shell-file-name nil t nil shell-command-switch command))))
3231 (defun process-file (program &optional infile buffer display &rest args)
3232 "Process files synchronously in a separate process.
3233 Similar to `call-process', but may invoke a file handler based on
3234 `default-directory'. The current working directory of the
3235 subprocess is `default-directory'.
3237 File names in INFILE and BUFFER are handled normally, but file
3238 names in ARGS should be relative to `default-directory', as they
3239 are passed to the process verbatim. (This is a difference to
3240 `call-process' which does not support file handlers for INFILE
3241 and BUFFER.)
3243 Some file handlers might not support all variants, for example
3244 they might behave as if DISPLAY was nil, regardless of the actual
3245 value passed."
3246 (let ((fh (find-file-name-handler default-directory 'process-file))
3247 lc stderr-file)
3248 (unwind-protect
3249 (if fh (apply fh 'process-file program infile buffer display args)
3250 (when infile (setq lc (file-local-copy infile)))
3251 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
3252 (make-temp-file "emacs")))
3253 (prog1
3254 (apply 'call-process program
3255 (or lc infile)
3256 (if stderr-file (list (car buffer) stderr-file) buffer)
3257 display args)
3258 (when stderr-file (copy-file stderr-file (cadr buffer) t))))
3259 (when stderr-file (delete-file stderr-file))
3260 (when lc (delete-file lc)))))
3262 (defvar process-file-side-effects t
3263 "Whether a call of `process-file' changes remote files.
3265 By default, this variable is always set to `t', meaning that a
3266 call of `process-file' could potentially change any file on a
3267 remote host. When set to `nil', a file handler could optimize
3268 its behavior with respect to remote file attribute caching.
3270 You should only ever change this variable with a let-binding;
3271 never with `setq'.")
3273 (defun start-file-process (name buffer program &rest program-args)
3274 "Start a program in a subprocess. Return the process object for it.
3276 Similar to `start-process', but may invoke a file handler based on
3277 `default-directory'. See Info node `(elisp)Magic File Names'.
3279 This handler ought to run PROGRAM, perhaps on the local host,
3280 perhaps on a remote host that corresponds to `default-directory'.
3281 In the latter case, the local part of `default-directory' becomes
3282 the working directory of the process.
3284 PROGRAM and PROGRAM-ARGS might be file names. They are not
3285 objects of file handler invocation. File handlers might not
3286 support pty association, if PROGRAM is nil."
3287 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
3288 (if fh (apply fh 'start-file-process name buffer program program-args)
3289 (apply 'start-process name buffer program program-args))))
3291 ;;;; Process menu
3293 (defvar tabulated-list-format)
3294 (defvar tabulated-list-entries)
3295 (defvar tabulated-list-sort-key)
3296 (declare-function tabulated-list-init-header "tabulated-list" ())
3297 (declare-function tabulated-list-print "tabulated-list"
3298 (&optional remember-pos))
3300 (defvar process-menu-query-only nil)
3302 (define-derived-mode process-menu-mode tabulated-list-mode "Process Menu"
3303 "Major mode for listing the processes called by Emacs."
3304 (setq tabulated-list-format [("Process" 15 t)
3305 ("Status" 7 t)
3306 ("Buffer" 15 t)
3307 ("TTY" 12 t)
3308 ("Command" 0 t)])
3309 (make-local-variable 'process-menu-query-only)
3310 (setq tabulated-list-sort-key (cons "Process" nil))
3311 (add-hook 'tabulated-list-revert-hook 'list-processes--refresh nil t)
3312 (tabulated-list-init-header))
3314 (defun list-processes--refresh ()
3315 "Recompute the list of processes for the Process List buffer.
3316 Also, delete any process that is exited or signaled."
3317 (setq tabulated-list-entries nil)
3318 (dolist (p (process-list))
3319 (cond ((memq (process-status p) '(exit signal closed))
3320 (delete-process p))
3321 ((or (not process-menu-query-only)
3322 (process-query-on-exit-flag p))
3323 (let* ((buf (process-buffer p))
3324 (type (process-type p))
3325 (name (process-name p))
3326 (status (symbol-name (process-status p)))
3327 (buf-label (if (buffer-live-p buf)
3328 `(,(buffer-name buf)
3329 face link
3330 help-echo ,(concat "Visit buffer `"
3331 (buffer-name buf) "'")
3332 follow-link t
3333 process-buffer ,buf
3334 action process-menu-visit-buffer)
3335 "--"))
3336 (tty (or (process-tty-name p) "--"))
3337 (cmd
3338 (if (memq type '(network serial))
3339 (let ((contact (process-contact p t)))
3340 (if (eq type 'network)
3341 (format "(%s %s)"
3342 (if (plist-get contact :type)
3343 "datagram"
3344 "network")
3345 (if (plist-get contact :server)
3346 (format "server on %s"
3348 (plist-get contact :host)
3349 (plist-get contact :local)))
3350 (format "connection to %s"
3351 (plist-get contact :host))))
3352 (format "(serial port %s%s)"
3353 (or (plist-get contact :port) "?")
3354 (let ((speed (plist-get contact :speed)))
3355 (if speed
3356 (format " at %s b/s" speed)
3357 "")))))
3358 (mapconcat 'identity (process-command p) " "))))
3359 (push (list p (vector name status buf-label tty cmd))
3360 tabulated-list-entries))))))
3362 (defun process-menu-visit-buffer (button)
3363 (display-buffer (button-get button 'process-buffer)))
3365 (defun list-processes (&optional query-only buffer)
3366 "Display a list of all processes that are Emacs sub-processes.
3367 If optional argument QUERY-ONLY is non-nil, only processes with
3368 the query-on-exit flag set are listed.
3369 Any process listed as exited or signaled is actually eliminated
3370 after the listing is made.
3371 Optional argument BUFFER specifies a buffer to use, instead of
3372 \"*Process List*\".
3373 The return value is always nil.
3375 This function lists only processes that were launched by Emacs. To
3376 see other processes running on the system, use `list-system-processes'."
3377 (interactive)
3378 (or (fboundp 'process-list)
3379 (error "Asynchronous subprocesses are not supported on this system"))
3380 (unless (bufferp buffer)
3381 (setq buffer (get-buffer-create "*Process List*")))
3382 (with-current-buffer buffer
3383 (process-menu-mode)
3384 (setq process-menu-query-only query-only)
3385 (list-processes--refresh)
3386 (tabulated-list-print))
3387 (display-buffer buffer)
3388 nil)
3390 (defvar universal-argument-map
3391 (let ((map (make-sparse-keymap))
3392 (universal-argument-minus
3393 ;; For backward compatibility, minus with no modifiers is an ordinary
3394 ;; command if digits have already been entered.
3395 `(menu-item "" negative-argument
3396 :filter ,(lambda (cmd)
3397 (if (integerp prefix-arg) nil cmd)))))
3398 (define-key map [switch-frame]
3399 (lambda (e) (interactive "e")
3400 (handle-switch-frame e) (universal-argument--mode)))
3401 (define-key map [?\C-u] 'universal-argument-more)
3402 (define-key map [?-] universal-argument-minus)
3403 (define-key map [?0] 'digit-argument)
3404 (define-key map [?1] 'digit-argument)
3405 (define-key map [?2] 'digit-argument)
3406 (define-key map [?3] 'digit-argument)
3407 (define-key map [?4] 'digit-argument)
3408 (define-key map [?5] 'digit-argument)
3409 (define-key map [?6] 'digit-argument)
3410 (define-key map [?7] 'digit-argument)
3411 (define-key map [?8] 'digit-argument)
3412 (define-key map [?9] 'digit-argument)
3413 (define-key map [kp-0] 'digit-argument)
3414 (define-key map [kp-1] 'digit-argument)
3415 (define-key map [kp-2] 'digit-argument)
3416 (define-key map [kp-3] 'digit-argument)
3417 (define-key map [kp-4] 'digit-argument)
3418 (define-key map [kp-5] 'digit-argument)
3419 (define-key map [kp-6] 'digit-argument)
3420 (define-key map [kp-7] 'digit-argument)
3421 (define-key map [kp-8] 'digit-argument)
3422 (define-key map [kp-9] 'digit-argument)
3423 (define-key map [kp-subtract] universal-argument-minus)
3424 map)
3425 "Keymap used while processing \\[universal-argument].")
3427 (defun universal-argument--mode ()
3428 (set-transient-map universal-argument-map))
3430 (defun universal-argument ()
3431 "Begin a numeric argument for the following command.
3432 Digits or minus sign following \\[universal-argument] make up the numeric argument.
3433 \\[universal-argument] following the digits or minus sign ends the argument.
3434 \\[universal-argument] without digits or minus sign provides 4 as argument.
3435 Repeating \\[universal-argument] without digits or minus sign
3436 multiplies the argument by 4 each time.
3437 For some commands, just \\[universal-argument] by itself serves as a flag
3438 which is different in effect from any particular numeric argument.
3439 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
3440 (interactive)
3441 (setq prefix-arg (list 4))
3442 (universal-argument--mode))
3444 (defun universal-argument-more (arg)
3445 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
3446 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
3447 (interactive "P")
3448 (setq prefix-arg (if (consp arg)
3449 (list (* 4 (car arg)))
3450 (if (eq arg '-)
3451 (list -4)
3452 arg)))
3453 (when (consp prefix-arg) (universal-argument--mode)))
3455 (defun negative-argument (arg)
3456 "Begin a negative numeric argument for the next command.
3457 \\[universal-argument] following digits or minus sign ends the argument."
3458 (interactive "P")
3459 (setq prefix-arg (cond ((integerp arg) (- arg))
3460 ((eq arg '-) nil)
3461 (t '-)))
3462 (universal-argument--mode))
3464 (defun digit-argument (arg)
3465 "Part of the numeric argument for the next command.
3466 \\[universal-argument] following digits or minus sign ends the argument."
3467 (interactive "P")
3468 (let* ((char (if (integerp last-command-event)
3469 last-command-event
3470 (get last-command-event 'ascii-character)))
3471 (digit (- (logand char ?\177) ?0)))
3472 (setq prefix-arg (cond ((integerp arg)
3473 (+ (* arg 10)
3474 (if (< arg 0) (- digit) digit)))
3475 ((eq arg '-)
3476 ;; Treat -0 as just -, so that -01 will work.
3477 (if (zerop digit) '- (- digit)))
3479 digit))))
3480 (universal-argument--mode))
3483 (defvar filter-buffer-substring-functions nil
3484 "This variable is a wrapper hook around `buffer-substring--filter'.")
3485 (make-obsolete-variable 'filter-buffer-substring-functions
3486 'filter-buffer-substring-function "24.4")
3488 (defvar filter-buffer-substring-function #'buffer-substring--filter
3489 "Function to perform the filtering in `filter-buffer-substring'.
3490 The function is called with the same 3 arguments (BEG END DELETE)
3491 that `filter-buffer-substring' received. It should return the
3492 buffer substring between BEG and END, after filtering. If DELETE is
3493 non-nil, it should delete the text between BEG and END from the buffer.")
3495 (defvar buffer-substring-filters nil
3496 "List of filter functions for `buffer-substring--filter'.
3497 Each function must accept a single argument, a string, and return a string.
3498 The buffer substring is passed to the first function in the list,
3499 and the return value of each function is passed to the next.
3500 As a special convention, point is set to the start of the buffer text
3501 being operated on (i.e., the first argument of `buffer-substring--filter')
3502 before these functions are called.")
3503 (make-obsolete-variable 'buffer-substring-filters
3504 'filter-buffer-substring-function "24.1")
3506 (defun filter-buffer-substring (beg end &optional delete)
3507 "Return the buffer substring between BEG and END, after filtering.
3508 If DELETE is non-nil, delete the text between BEG and END from the buffer.
3510 This calls the function that `filter-buffer-substring-function' specifies
3511 \(passing the same three arguments that it received) to do the work,
3512 and returns whatever it does. The default function does no filtering,
3513 unless a hook has been set.
3515 Use `filter-buffer-substring' instead of `buffer-substring',
3516 `buffer-substring-no-properties', or `delete-and-extract-region' when
3517 you want to allow filtering to take place. For example, major or minor
3518 modes can use `filter-buffer-substring-function' to extract characters
3519 that are special to a buffer, and should not be copied into other buffers."
3520 (funcall filter-buffer-substring-function beg end delete))
3522 (defun buffer-substring--filter (beg end &optional delete)
3523 "Default function to use for `filter-buffer-substring-function'.
3524 Its arguments and return value are as specified for `filter-buffer-substring'.
3525 This respects the wrapper hook `filter-buffer-substring-functions',
3526 and the abnormal hook `buffer-substring-filters'.
3527 No filtering is done unless a hook says to."
3528 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
3529 (cond
3530 ((or delete buffer-substring-filters)
3531 (save-excursion
3532 (goto-char beg)
3533 (let ((string (if delete (delete-and-extract-region beg end)
3534 (buffer-substring beg end))))
3535 (dolist (filter buffer-substring-filters)
3536 (setq string (funcall filter string)))
3537 string)))
3539 (buffer-substring beg end)))))
3542 ;;;; Window system cut and paste hooks.
3544 (defvar interprogram-cut-function nil
3545 "Function to call to make a killed region available to other programs.
3546 Most window systems provide a facility for cutting and pasting
3547 text between different programs, such as the clipboard on X and
3548 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3550 This variable holds a function that Emacs calls whenever text is
3551 put in the kill ring, to make the new kill available to other
3552 programs. The function takes one argument, TEXT, which is a
3553 string containing the text which should be made available.")
3555 (defvar interprogram-paste-function nil
3556 "Function to call to get text cut from other programs.
3557 Most window systems provide a facility for cutting and pasting
3558 text between different programs, such as the clipboard on X and
3559 MS-Windows, or the pasteboard on Nextstep/Mac OS.
3561 This variable holds a function that Emacs calls to obtain text
3562 that other programs have provided for pasting. The function is
3563 called with no arguments. If no other program has provided text
3564 to paste, the function should return nil (in which case the
3565 caller, usually `current-kill', should use the top of the Emacs
3566 kill ring). If another program has provided text to paste, the
3567 function should return that text as a string (in which case the
3568 caller should put this string in the kill ring as the latest
3569 kill).
3571 The function may also return a list of strings if the window
3572 system supports multiple selections. The first string will be
3573 used as the pasted text, but the other will be placed in the kill
3574 ring for easy access via `yank-pop'.
3576 Note that the function should return a string only if a program
3577 other than Emacs has provided a string for pasting; if Emacs
3578 provided the most recent string, the function should return nil.
3579 If it is difficult to tell whether Emacs or some other program
3580 provided the current string, it is probably good enough to return
3581 nil if the string is equal (according to `string=') to the last
3582 text Emacs provided.")
3586 ;;;; The kill ring data structure.
3588 (defvar kill-ring nil
3589 "List of killed text sequences.
3590 Since the kill ring is supposed to interact nicely with cut-and-paste
3591 facilities offered by window systems, use of this variable should
3592 interact nicely with `interprogram-cut-function' and
3593 `interprogram-paste-function'. The functions `kill-new',
3594 `kill-append', and `current-kill' are supposed to implement this
3595 interaction; you may want to use them instead of manipulating the kill
3596 ring directly.")
3598 (defcustom kill-ring-max 60
3599 "Maximum length of kill ring before oldest elements are thrown away."
3600 :type 'integer
3601 :group 'killing)
3603 (defvar kill-ring-yank-pointer nil
3604 "The tail of the kill ring whose car is the last thing yanked.")
3606 (defcustom save-interprogram-paste-before-kill nil
3607 "Save clipboard strings into kill ring before replacing them.
3608 When one selects something in another program to paste it into Emacs,
3609 but kills something in Emacs before actually pasting it,
3610 this selection is gone unless this variable is non-nil,
3611 in which case the other program's selection is saved in the `kill-ring'
3612 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
3613 :type 'boolean
3614 :group 'killing
3615 :version "23.2")
3617 (defcustom kill-do-not-save-duplicates nil
3618 "Do not add a new string to `kill-ring' if it duplicates the last one.
3619 The comparison is done using `equal-including-properties'."
3620 :type 'boolean
3621 :group 'killing
3622 :version "23.2")
3624 (defun kill-new (string &optional replace)
3625 "Make STRING the latest kill in the kill ring.
3626 Set `kill-ring-yank-pointer' to point to it.
3627 If `interprogram-cut-function' is non-nil, apply it to STRING.
3628 Optional second argument REPLACE non-nil means that STRING will replace
3629 the front of the kill ring, rather than being added to the list.
3631 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
3632 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3633 STRING.
3635 When the yank handler has a non-nil PARAM element, the original STRING
3636 argument is not used by `insert-for-yank'. However, since Lisp code
3637 may access and use elements from the kill ring directly, the STRING
3638 argument should still be a \"useful\" string for such uses."
3639 (unless (and kill-do-not-save-duplicates
3640 ;; Due to text properties such as 'yank-handler that
3641 ;; can alter the contents to yank, comparison using
3642 ;; `equal' is unsafe.
3643 (equal-including-properties string (car kill-ring)))
3644 (if (fboundp 'menu-bar-update-yank-menu)
3645 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
3646 (when save-interprogram-paste-before-kill
3647 (let ((interprogram-paste (and interprogram-paste-function
3648 (funcall interprogram-paste-function))))
3649 (when interprogram-paste
3650 (dolist (s (if (listp interprogram-paste)
3651 (nreverse interprogram-paste)
3652 (list interprogram-paste)))
3653 (unless (and kill-do-not-save-duplicates
3654 (equal-including-properties s (car kill-ring)))
3655 (push s kill-ring))))))
3656 (unless (and kill-do-not-save-duplicates
3657 (equal-including-properties string (car kill-ring)))
3658 (if (and replace kill-ring)
3659 (setcar kill-ring string)
3660 (push string kill-ring)
3661 (if (> (length kill-ring) kill-ring-max)
3662 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
3663 (setq kill-ring-yank-pointer kill-ring)
3664 (if interprogram-cut-function
3665 (funcall interprogram-cut-function string)))
3667 (defun kill-append (string before-p)
3668 "Append STRING to the end of the latest kill in the kill ring.
3669 If BEFORE-P is non-nil, prepend STRING to the kill.
3670 If `interprogram-cut-function' is set, pass the resulting kill to it."
3671 (let* ((cur (car kill-ring)))
3672 (kill-new (if before-p (concat string cur) (concat cur string))
3673 (or (= (length cur) 0)
3674 (equal nil (get-text-property 0 'yank-handler cur))))))
3676 (defcustom yank-pop-change-selection nil
3677 "Whether rotating the kill ring changes the window system selection.
3678 If non-nil, whenever the kill ring is rotated (usually via the
3679 `yank-pop' command), Emacs also calls `interprogram-cut-function'
3680 to copy the new kill to the window system selection."
3681 :type 'boolean
3682 :group 'killing
3683 :version "23.1")
3685 (defun current-kill (n &optional do-not-move)
3686 "Rotate the yanking point by N places, and then return that kill.
3687 If N is zero and `interprogram-paste-function' is set to a
3688 function that returns a string or a list of strings, and if that
3689 function doesn't return nil, then that string (or list) is added
3690 to the front of the kill ring and the string (or first string in
3691 the list) is returned as the latest kill.
3693 If N is not zero, and if `yank-pop-change-selection' is
3694 non-nil, use `interprogram-cut-function' to transfer the
3695 kill at the new yank point into the window system selection.
3697 If optional arg DO-NOT-MOVE is non-nil, then don't actually
3698 move the yanking point; just return the Nth kill forward."
3700 (let ((interprogram-paste (and (= n 0)
3701 interprogram-paste-function
3702 (funcall interprogram-paste-function))))
3703 (if interprogram-paste
3704 (progn
3705 ;; Disable the interprogram cut function when we add the new
3706 ;; text to the kill ring, so Emacs doesn't try to own the
3707 ;; selection, with identical text.
3708 (let ((interprogram-cut-function nil))
3709 (if (listp interprogram-paste)
3710 (mapc 'kill-new (nreverse interprogram-paste))
3711 (kill-new interprogram-paste)))
3712 (car kill-ring))
3713 (or kill-ring (error "Kill ring is empty"))
3714 (let ((ARGth-kill-element
3715 (nthcdr (mod (- n (length kill-ring-yank-pointer))
3716 (length kill-ring))
3717 kill-ring)))
3718 (unless do-not-move
3719 (setq kill-ring-yank-pointer ARGth-kill-element)
3720 (when (and yank-pop-change-selection
3721 (> n 0)
3722 interprogram-cut-function)
3723 (funcall interprogram-cut-function (car ARGth-kill-element))))
3724 (car ARGth-kill-element)))))
3728 ;;;; Commands for manipulating the kill ring.
3730 (defcustom kill-read-only-ok nil
3731 "Non-nil means don't signal an error for killing read-only text."
3732 :type 'boolean
3733 :group 'killing)
3735 (defun kill-region (beg end &optional region)
3736 "Kill (\"cut\") text between point and mark.
3737 This deletes the text from the buffer and saves it in the kill ring.
3738 The command \\[yank] can retrieve it from there.
3739 \(If you want to save the region without killing it, use \\[kill-ring-save].)
3741 If you want to append the killed region to the last killed text,
3742 use \\[append-next-kill] before \\[kill-region].
3744 If the buffer is read-only, Emacs will beep and refrain from deleting
3745 the text, but put the text in the kill ring anyway. This means that
3746 you can use the killing commands to copy text from a read-only buffer.
3748 Lisp programs should use this function for killing text.
3749 (To delete text, use `delete-region'.)
3750 Supply two arguments, character positions indicating the stretch of text
3751 to be killed.
3752 Any command that calls this function is a \"kill command\".
3753 If the previous command was also a kill command,
3754 the text killed this time appends to the text killed last time
3755 to make one entry in the kill ring.
3757 The optional argument REGION if non-nil, indicates that we're not just killing
3758 some text between BEG and END, but we're killing the region."
3759 ;; Pass mark first, then point, because the order matters when
3760 ;; calling `kill-append'.
3761 (interactive (list (mark) (point) 'region))
3762 (unless (and beg end)
3763 (error "The mark is not set now, so there is no region"))
3764 (condition-case nil
3765 (let ((string (if region
3766 (funcall region-extract-function 'delete)
3767 (filter-buffer-substring beg end 'delete))))
3768 (when string ;STRING is nil if BEG = END
3769 ;; Add that string to the kill ring, one way or another.
3770 (if (eq last-command 'kill-region)
3771 (kill-append string (< end beg))
3772 (kill-new string nil)))
3773 (when (or string (eq last-command 'kill-region))
3774 (setq this-command 'kill-region))
3775 (setq deactivate-mark t)
3776 nil)
3777 ((buffer-read-only text-read-only)
3778 ;; The code above failed because the buffer, or some of the characters
3779 ;; in the region, are read-only.
3780 ;; We should beep, in case the user just isn't aware of this.
3781 ;; However, there's no harm in putting
3782 ;; the region's text in the kill ring, anyway.
3783 (copy-region-as-kill beg end region)
3784 ;; Set this-command now, so it will be set even if we get an error.
3785 (setq this-command 'kill-region)
3786 ;; This should barf, if appropriate, and give us the correct error.
3787 (if kill-read-only-ok
3788 (progn (message "Read only text copied to kill ring") nil)
3789 ;; Signal an error if the buffer is read-only.
3790 (barf-if-buffer-read-only)
3791 ;; If the buffer isn't read-only, the text is.
3792 (signal 'text-read-only (list (current-buffer)))))))
3794 ;; copy-region-as-kill no longer sets this-command, because it's confusing
3795 ;; to get two copies of the text when the user accidentally types M-w and
3796 ;; then corrects it with the intended C-w.
3797 (defun copy-region-as-kill (beg end &optional region)
3798 "Save the region as if killed, but don't kill it.
3799 In Transient Mark mode, deactivate the mark.
3800 If `interprogram-cut-function' is non-nil, also save the text for a window
3801 system cut and paste.
3803 The optional argument REGION if non-nil, indicates that we're not just copying
3804 some text between BEG and END, but we're copying the region.
3806 This command's old key binding has been given to `kill-ring-save'."
3807 ;; Pass mark first, then point, because the order matters when
3808 ;; calling `kill-append'.
3809 (interactive (list (mark) (point)
3810 (prefix-numeric-value current-prefix-arg)))
3811 (let ((str (if region
3812 (funcall region-extract-function nil)
3813 (filter-buffer-substring beg end))))
3814 (if (eq last-command 'kill-region)
3815 (kill-append str (< end beg))
3816 (kill-new str)))
3817 (setq deactivate-mark t)
3818 nil)
3820 (defun kill-ring-save (beg end &optional region)
3821 "Save the region as if killed, but don't kill it.
3822 In Transient Mark mode, deactivate the mark.
3823 If `interprogram-cut-function' is non-nil, also save the text for a window
3824 system cut and paste.
3826 If you want to append the killed line to the last killed text,
3827 use \\[append-next-kill] before \\[kill-ring-save].
3829 The optional argument REGION if non-nil, indicates that we're not just copying
3830 some text between BEG and END, but we're copying the region.
3832 This command is similar to `copy-region-as-kill', except that it gives
3833 visual feedback indicating the extent of the region being copied."
3834 ;; Pass mark first, then point, because the order matters when
3835 ;; calling `kill-append'.
3836 (interactive (list (mark) (point)
3837 (prefix-numeric-value current-prefix-arg)))
3838 (copy-region-as-kill beg end region)
3839 ;; This use of called-interactively-p is correct because the code it
3840 ;; controls just gives the user visual feedback.
3841 (if (called-interactively-p 'interactive)
3842 (indicate-copied-region)))
3844 (defun indicate-copied-region (&optional message-len)
3845 "Indicate that the region text has been copied interactively.
3846 If the mark is visible in the selected window, blink the cursor
3847 between point and mark if there is currently no active region
3848 highlighting.
3850 If the mark lies outside the selected window, display an
3851 informative message containing a sample of the copied text. The
3852 optional argument MESSAGE-LEN, if non-nil, specifies the length
3853 of this sample text; it defaults to 40."
3854 (let ((mark (mark t))
3855 (point (point))
3856 ;; Inhibit quitting so we can make a quit here
3857 ;; look like a C-g typed as a command.
3858 (inhibit-quit t))
3859 (if (pos-visible-in-window-p mark (selected-window))
3860 ;; Swap point-and-mark quickly so as to show the region that
3861 ;; was selected. Don't do it if the region is highlighted.
3862 (unless (and (region-active-p)
3863 (face-background 'region))
3864 ;; Swap point and mark.
3865 (set-marker (mark-marker) (point) (current-buffer))
3866 (goto-char mark)
3867 (sit-for blink-matching-delay)
3868 ;; Swap back.
3869 (set-marker (mark-marker) mark (current-buffer))
3870 (goto-char point)
3871 ;; If user quit, deactivate the mark
3872 ;; as C-g would as a command.
3873 (and quit-flag mark-active
3874 (deactivate-mark)))
3875 (let ((len (min (abs (- mark point))
3876 (or message-len 40))))
3877 (if (< point mark)
3878 ;; Don't say "killed"; that is misleading.
3879 (message "Saved text until \"%s\""
3880 (buffer-substring-no-properties (- mark len) mark))
3881 (message "Saved text from \"%s\""
3882 (buffer-substring-no-properties mark (+ mark len))))))))
3884 (defun append-next-kill (&optional interactive)
3885 "Cause following command, if it kills, to add to previous kill.
3886 If the next command kills forward from point, the kill is
3887 appended to the previous killed text. If the command kills
3888 backward, the kill is prepended. Kill commands that act on the
3889 region, such as `kill-region', are regarded as killing forward if
3890 point is after mark, and killing backward if point is before
3891 mark.
3893 If the next command is not a kill command, `append-next-kill' has
3894 no effect.
3896 The argument is used for internal purposes; do not supply one."
3897 (interactive "p")
3898 ;; We don't use (interactive-p), since that breaks kbd macros.
3899 (if interactive
3900 (progn
3901 (setq this-command 'kill-region)
3902 (message "If the next command is a kill, it will append"))
3903 (setq last-command 'kill-region)))
3905 ;; Yanking.
3907 (defcustom yank-handled-properties
3908 '((font-lock-face . yank-handle-font-lock-face-property)
3909 (category . yank-handle-category-property))
3910 "List of special text property handling conditions for yanking.
3911 Each element should have the form (PROP . FUN), where PROP is a
3912 property symbol and FUN is a function. When the `yank' command
3913 inserts text into the buffer, it scans the inserted text for
3914 stretches of text that have `eq' values of the text property
3915 PROP; for each such stretch of text, FUN is called with three
3916 arguments: the property's value in that text, and the start and
3917 end positions of the text.
3919 This is done prior to removing the properties specified by
3920 `yank-excluded-properties'."
3921 :group 'killing
3922 :type '(repeat (cons (symbol :tag "property symbol")
3923 function))
3924 :version "24.3")
3926 ;; This is actually used in subr.el but defcustom does not work there.
3927 (defcustom yank-excluded-properties
3928 '(category field follow-link fontified font-lock-face help-echo
3929 intangible invisible keymap local-map mouse-face read-only
3930 yank-handler)
3931 "Text properties to discard when yanking.
3932 The value should be a list of text properties to discard or t,
3933 which means to discard all text properties.
3935 See also `yank-handled-properties'."
3936 :type '(choice (const :tag "All" t) (repeat symbol))
3937 :group 'killing
3938 :version "24.3")
3940 (defvar yank-window-start nil)
3941 (defvar yank-undo-function nil
3942 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
3943 Function is called with two parameters, START and END corresponding to
3944 the value of the mark and point; it is guaranteed that START <= END.
3945 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
3947 (defun yank-pop (&optional arg)
3948 "Replace just-yanked stretch of killed text with a different stretch.
3949 This command is allowed only immediately after a `yank' or a `yank-pop'.
3950 At such a time, the region contains a stretch of reinserted
3951 previously-killed text. `yank-pop' deletes that text and inserts in its
3952 place a different stretch of killed text.
3954 With no argument, the previous kill is inserted.
3955 With argument N, insert the Nth previous kill.
3956 If N is negative, this is a more recent kill.
3958 The sequence of kills wraps around, so that after the oldest one
3959 comes the newest one.
3961 When this command inserts killed text into the buffer, it honors
3962 `yank-excluded-properties' and `yank-handler' as described in the
3963 doc string for `insert-for-yank-1', which see."
3964 (interactive "*p")
3965 (if (not (eq last-command 'yank))
3966 (error "Previous command was not a yank"))
3967 (setq this-command 'yank)
3968 (unless arg (setq arg 1))
3969 (let ((inhibit-read-only t)
3970 (before (< (point) (mark t))))
3971 (if before
3972 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
3973 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
3974 (setq yank-undo-function nil)
3975 (set-marker (mark-marker) (point) (current-buffer))
3976 (insert-for-yank (current-kill arg))
3977 ;; Set the window start back where it was in the yank command,
3978 ;; if possible.
3979 (set-window-start (selected-window) yank-window-start t)
3980 (if before
3981 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3982 ;; It is cleaner to avoid activation, even though the command
3983 ;; loop would deactivate the mark because we inserted text.
3984 (goto-char (prog1 (mark t)
3985 (set-marker (mark-marker) (point) (current-buffer))))))
3986 nil)
3988 (defun yank (&optional arg)
3989 "Reinsert (\"paste\") the last stretch of killed text.
3990 More precisely, reinsert the most recent kill, which is the
3991 stretch of killed text most recently killed OR yanked. Put point
3992 at the end, and set mark at the beginning without activating it.
3993 With just \\[universal-argument] as argument, put point at beginning, and mark at end.
3994 With argument N, reinsert the Nth most recent kill.
3996 When this command inserts text into the buffer, it honors the
3997 `yank-handled-properties' and `yank-excluded-properties'
3998 variables, and the `yank-handler' text property. See
3999 `insert-for-yank-1' for details.
4001 See also the command `yank-pop' (\\[yank-pop])."
4002 (interactive "*P")
4003 (setq yank-window-start (window-start))
4004 ;; If we don't get all the way thru, make last-command indicate that
4005 ;; for the following command.
4006 (setq this-command t)
4007 (push-mark (point))
4008 (insert-for-yank (current-kill (cond
4009 ((listp arg) 0)
4010 ((eq arg '-) -2)
4011 (t (1- arg)))))
4012 (if (consp arg)
4013 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
4014 ;; It is cleaner to avoid activation, even though the command
4015 ;; loop would deactivate the mark because we inserted text.
4016 (goto-char (prog1 (mark t)
4017 (set-marker (mark-marker) (point) (current-buffer)))))
4018 ;; If we do get all the way thru, make this-command indicate that.
4019 (if (eq this-command t)
4020 (setq this-command 'yank))
4021 nil)
4023 (defun rotate-yank-pointer (arg)
4024 "Rotate the yanking point in the kill ring.
4025 With ARG, rotate that many kills forward (or backward, if negative)."
4026 (interactive "p")
4027 (current-kill arg))
4029 ;; Some kill commands.
4031 ;; Internal subroutine of delete-char
4032 (defun kill-forward-chars (arg)
4033 (if (listp arg) (setq arg (car arg)))
4034 (if (eq arg '-) (setq arg -1))
4035 (kill-region (point) (+ (point) arg)))
4037 ;; Internal subroutine of backward-delete-char
4038 (defun kill-backward-chars (arg)
4039 (if (listp arg) (setq arg (car arg)))
4040 (if (eq arg '-) (setq arg -1))
4041 (kill-region (point) (- (point) arg)))
4043 (defcustom backward-delete-char-untabify-method 'untabify
4044 "The method for untabifying when deleting backward.
4045 Can be `untabify' -- turn a tab to many spaces, then delete one space;
4046 `hungry' -- delete all whitespace, both tabs and spaces;
4047 `all' -- delete all whitespace, including tabs, spaces and newlines;
4048 nil -- just delete one character."
4049 :type '(choice (const untabify) (const hungry) (const all) (const nil))
4050 :version "20.3"
4051 :group 'killing)
4053 (defun backward-delete-char-untabify (arg &optional killp)
4054 "Delete characters backward, changing tabs into spaces.
4055 The exact behavior depends on `backward-delete-char-untabify-method'.
4056 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
4057 Interactively, ARG is the prefix arg (default 1)
4058 and KILLP is t if a prefix arg was specified."
4059 (interactive "*p\nP")
4060 (when (eq backward-delete-char-untabify-method 'untabify)
4061 (let ((count arg))
4062 (save-excursion
4063 (while (and (> count 0) (not (bobp)))
4064 (if (= (preceding-char) ?\t)
4065 (let ((col (current-column)))
4066 (forward-char -1)
4067 (setq col (- col (current-column)))
4068 (insert-char ?\s col)
4069 (delete-char 1)))
4070 (forward-char -1)
4071 (setq count (1- count))))))
4072 (let* ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
4073 ((eq backward-delete-char-untabify-method 'all)
4074 " \t\n\r")))
4075 (n (if skip
4076 (let* ((oldpt (point))
4077 (wh (- oldpt (save-excursion
4078 (skip-chars-backward skip)
4079 (constrain-to-field nil oldpt)))))
4080 (+ arg (if (zerop wh) 0 (1- wh))))
4081 arg)))
4082 ;; Avoid warning about delete-backward-char
4083 (with-no-warnings (delete-backward-char n killp))))
4085 (defun zap-to-char (arg char)
4086 "Kill up to and including ARGth occurrence of CHAR.
4087 Case is ignored if `case-fold-search' is non-nil in the current buffer.
4088 Goes backward if ARG is negative; error if CHAR not found."
4089 (interactive (list (prefix-numeric-value current-prefix-arg)
4090 (read-char "Zap to char: " t)))
4091 ;; Avoid "obsolete" warnings for translation-table-for-input.
4092 (with-no-warnings
4093 (if (char-table-p translation-table-for-input)
4094 (setq char (or (aref translation-table-for-input char) char))))
4095 (kill-region (point) (progn
4096 (search-forward (char-to-string char) nil nil arg)
4097 (point))))
4099 ;; kill-line and its subroutines.
4101 (defcustom kill-whole-line nil
4102 "If non-nil, `kill-line' with no arg at start of line kills the whole line."
4103 :type 'boolean
4104 :group 'killing)
4106 (defun kill-line (&optional arg)
4107 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
4108 With prefix argument ARG, kill that many lines from point.
4109 Negative arguments kill lines backward.
4110 With zero argument, kills the text before point on the current line.
4112 When calling from a program, nil means \"no arg\",
4113 a number counts as a prefix arg.
4115 To kill a whole line, when point is not at the beginning, type \
4116 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
4118 If `show-trailing-whitespace' is non-nil, this command will just
4119 kill the rest of the current line, even if there are only
4120 nonblanks there.
4122 If option `kill-whole-line' is non-nil, then this command kills the whole line
4123 including its terminating newline, when used at the beginning of a line
4124 with no argument. As a consequence, you can always kill a whole line
4125 by typing \\[move-beginning-of-line] \\[kill-line].
4127 If you want to append the killed line to the last killed text,
4128 use \\[append-next-kill] before \\[kill-line].
4130 If the buffer is read-only, Emacs will beep and refrain from deleting
4131 the line, but put the line in the kill ring anyway. This means that
4132 you can use this command to copy text from a read-only buffer.
4133 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4134 even beep.)"
4135 (interactive "P")
4136 (kill-region (point)
4137 ;; It is better to move point to the other end of the kill
4138 ;; before killing. That way, in a read-only buffer, point
4139 ;; moves across the text that is copied to the kill ring.
4140 ;; The choice has no effect on undo now that undo records
4141 ;; the value of point from before the command was run.
4142 (progn
4143 (if arg
4144 (forward-visible-line (prefix-numeric-value arg))
4145 (if (eobp)
4146 (signal 'end-of-buffer nil))
4147 (let ((end
4148 (save-excursion
4149 (end-of-visible-line) (point))))
4150 (if (or (save-excursion
4151 ;; If trailing whitespace is visible,
4152 ;; don't treat it as nothing.
4153 (unless show-trailing-whitespace
4154 (skip-chars-forward " \t" end))
4155 (= (point) end))
4156 (and kill-whole-line (bolp)))
4157 (forward-visible-line 1)
4158 (goto-char end))))
4159 (point))))
4161 (defun kill-whole-line (&optional arg)
4162 "Kill current line.
4163 With prefix ARG, kill that many lines starting from the current line.
4164 If ARG is negative, kill backward. Also kill the preceding newline.
4165 \(This is meant to make \\[repeat] work well with negative arguments.)
4166 If ARG is zero, kill current line but exclude the trailing newline."
4167 (interactive "p")
4168 (or arg (setq arg 1))
4169 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
4170 (signal 'end-of-buffer nil))
4171 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
4172 (signal 'beginning-of-buffer nil))
4173 (unless (eq last-command 'kill-region)
4174 (kill-new "")
4175 (setq last-command 'kill-region))
4176 (cond ((zerop arg)
4177 ;; We need to kill in two steps, because the previous command
4178 ;; could have been a kill command, in which case the text
4179 ;; before point needs to be prepended to the current kill
4180 ;; ring entry and the text after point appended. Also, we
4181 ;; need to use save-excursion to avoid copying the same text
4182 ;; twice to the kill ring in read-only buffers.
4183 (save-excursion
4184 (kill-region (point) (progn (forward-visible-line 0) (point))))
4185 (kill-region (point) (progn (end-of-visible-line) (point))))
4186 ((< arg 0)
4187 (save-excursion
4188 (kill-region (point) (progn (end-of-visible-line) (point))))
4189 (kill-region (point)
4190 (progn (forward-visible-line (1+ arg))
4191 (unless (bobp) (backward-char))
4192 (point))))
4194 (save-excursion
4195 (kill-region (point) (progn (forward-visible-line 0) (point))))
4196 (kill-region (point)
4197 (progn (forward-visible-line arg) (point))))))
4199 (defun forward-visible-line (arg)
4200 "Move forward by ARG lines, ignoring currently invisible newlines only.
4201 If ARG is negative, move backward -ARG lines.
4202 If ARG is zero, move to the beginning of the current line."
4203 (condition-case nil
4204 (if (> arg 0)
4205 (progn
4206 (while (> arg 0)
4207 (or (zerop (forward-line 1))
4208 (signal 'end-of-buffer nil))
4209 ;; If the newline we just skipped is invisible,
4210 ;; don't count it.
4211 (let ((prop
4212 (get-char-property (1- (point)) 'invisible)))
4213 (if (if (eq buffer-invisibility-spec t)
4214 prop
4215 (or (memq prop buffer-invisibility-spec)
4216 (assq prop buffer-invisibility-spec)))
4217 (setq arg (1+ arg))))
4218 (setq arg (1- arg)))
4219 ;; If invisible text follows, and it is a number of complete lines,
4220 ;; skip it.
4221 (let ((opoint (point)))
4222 (while (and (not (eobp))
4223 (let ((prop
4224 (get-char-property (point) 'invisible)))
4225 (if (eq buffer-invisibility-spec t)
4226 prop
4227 (or (memq prop buffer-invisibility-spec)
4228 (assq prop buffer-invisibility-spec)))))
4229 (goto-char
4230 (if (get-text-property (point) 'invisible)
4231 (or (next-single-property-change (point) 'invisible)
4232 (point-max))
4233 (next-overlay-change (point)))))
4234 (unless (bolp)
4235 (goto-char opoint))))
4236 (let ((first t))
4237 (while (or first (<= arg 0))
4238 (if first
4239 (beginning-of-line)
4240 (or (zerop (forward-line -1))
4241 (signal 'beginning-of-buffer nil)))
4242 ;; If the newline we just moved to is invisible,
4243 ;; don't count it.
4244 (unless (bobp)
4245 (let ((prop
4246 (get-char-property (1- (point)) 'invisible)))
4247 (unless (if (eq buffer-invisibility-spec t)
4248 prop
4249 (or (memq prop buffer-invisibility-spec)
4250 (assq prop buffer-invisibility-spec)))
4251 (setq arg (1+ arg)))))
4252 (setq first nil))
4253 ;; If invisible text follows, and it is a number of complete lines,
4254 ;; skip it.
4255 (let ((opoint (point)))
4256 (while (and (not (bobp))
4257 (let ((prop
4258 (get-char-property (1- (point)) 'invisible)))
4259 (if (eq buffer-invisibility-spec t)
4260 prop
4261 (or (memq prop buffer-invisibility-spec)
4262 (assq prop buffer-invisibility-spec)))))
4263 (goto-char
4264 (if (get-text-property (1- (point)) 'invisible)
4265 (or (previous-single-property-change (point) 'invisible)
4266 (point-min))
4267 (previous-overlay-change (point)))))
4268 (unless (bolp)
4269 (goto-char opoint)))))
4270 ((beginning-of-buffer end-of-buffer)
4271 nil)))
4273 (defun end-of-visible-line ()
4274 "Move to end of current visible line."
4275 (end-of-line)
4276 ;; If the following character is currently invisible,
4277 ;; skip all characters with that same `invisible' property value,
4278 ;; then find the next newline.
4279 (while (and (not (eobp))
4280 (save-excursion
4281 (skip-chars-forward "^\n")
4282 (let ((prop
4283 (get-char-property (point) 'invisible)))
4284 (if (eq buffer-invisibility-spec t)
4285 prop
4286 (or (memq prop buffer-invisibility-spec)
4287 (assq prop buffer-invisibility-spec))))))
4288 (skip-chars-forward "^\n")
4289 (if (get-text-property (point) 'invisible)
4290 (goto-char (or (next-single-property-change (point) 'invisible)
4291 (point-max)))
4292 (goto-char (next-overlay-change (point))))
4293 (end-of-line)))
4295 (defun insert-buffer (buffer)
4296 "Insert after point the contents of BUFFER.
4297 Puts mark after the inserted text.
4298 BUFFER may be a buffer or a buffer name.
4300 This function is meant for the user to run interactively.
4301 Don't call it from programs: use `insert-buffer-substring' instead!"
4302 (interactive
4303 (list
4304 (progn
4305 (barf-if-buffer-read-only)
4306 (read-buffer "Insert buffer: "
4307 (if (eq (selected-window) (next-window))
4308 (other-buffer (current-buffer))
4309 (window-buffer (next-window)))
4310 t))))
4311 (push-mark
4312 (save-excursion
4313 (insert-buffer-substring (get-buffer buffer))
4314 (point)))
4315 nil)
4316 (put 'insert-buffer 'interactive-only 'insert-buffer-substring)
4318 (defun append-to-buffer (buffer start end)
4319 "Append to specified buffer the text of the region.
4320 It is inserted into that buffer before its point.
4322 When calling from a program, give three arguments:
4323 BUFFER (or buffer name), START and END.
4324 START and END specify the portion of the current buffer to be copied."
4325 (interactive
4326 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
4327 (region-beginning) (region-end)))
4328 (let* ((oldbuf (current-buffer))
4329 (append-to (get-buffer-create buffer))
4330 (windows (get-buffer-window-list append-to t t))
4331 point)
4332 (save-excursion
4333 (with-current-buffer append-to
4334 (setq point (point))
4335 (barf-if-buffer-read-only)
4336 (insert-buffer-substring oldbuf start end)
4337 (dolist (window windows)
4338 (when (= (window-point window) point)
4339 (set-window-point window (point))))))))
4341 (defun prepend-to-buffer (buffer start end)
4342 "Prepend to specified buffer the text of the region.
4343 It is inserted into that buffer after its point.
4345 When calling from a program, give three arguments:
4346 BUFFER (or buffer name), START and END.
4347 START and END specify the portion of the current buffer to be copied."
4348 (interactive "BPrepend to buffer: \nr")
4349 (let ((oldbuf (current-buffer)))
4350 (with-current-buffer (get-buffer-create buffer)
4351 (barf-if-buffer-read-only)
4352 (save-excursion
4353 (insert-buffer-substring oldbuf start end)))))
4355 (defun copy-to-buffer (buffer start end)
4356 "Copy to specified buffer the text of the region.
4357 It is inserted into that buffer, replacing existing text there.
4359 When calling from a program, give three arguments:
4360 BUFFER (or buffer name), START and END.
4361 START and END specify the portion of the current buffer to be copied."
4362 (interactive "BCopy to buffer: \nr")
4363 (let ((oldbuf (current-buffer)))
4364 (with-current-buffer (get-buffer-create buffer)
4365 (barf-if-buffer-read-only)
4366 (erase-buffer)
4367 (save-excursion
4368 (insert-buffer-substring oldbuf start end)))))
4370 (define-error 'mark-inactive (purecopy "The mark is not active now"))
4372 (defvar activate-mark-hook nil
4373 "Hook run when the mark becomes active.
4374 It is also run at the end of a command, if the mark is active and
4375 it is possible that the region may have changed.")
4377 (defvar deactivate-mark-hook nil
4378 "Hook run when the mark becomes inactive.")
4380 (defun mark (&optional force)
4381 "Return this buffer's mark value as integer, or nil if never set.
4383 In Transient Mark mode, this function signals an error if
4384 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
4385 or the argument FORCE is non-nil, it disregards whether the mark
4386 is active, and returns an integer or nil in the usual way.
4388 If you are using this in an editing command, you are most likely making
4389 a mistake; see the documentation of `set-mark'."
4390 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
4391 (marker-position (mark-marker))
4392 (signal 'mark-inactive nil)))
4394 ;; Behind display-selections-p.
4395 (declare-function x-selection-owner-p "xselect.c"
4396 (&optional selection terminal))
4397 (declare-function x-selection-exists-p "xselect.c"
4398 (&optional selection terminal))
4400 (defun deactivate-mark (&optional force)
4401 "Deactivate the mark.
4402 If Transient Mark mode is disabled, this function normally does
4403 nothing; but if FORCE is non-nil, it deactivates the mark anyway.
4405 Deactivating the mark sets `mark-active' to nil, updates the
4406 primary selection according to `select-active-regions', and runs
4407 `deactivate-mark-hook'.
4409 If Transient Mark mode was temporarily enabled, reset the value
4410 of the variable `transient-mark-mode'; if this causes Transient
4411 Mark mode to be disabled, don't change `mark-active' to nil or
4412 run `deactivate-mark-hook'."
4413 (when (or transient-mark-mode force)
4414 (when (and (if (eq select-active-regions 'only)
4415 (eq (car-safe transient-mark-mode) 'only)
4416 select-active-regions)
4417 (region-active-p)
4418 (display-selections-p))
4419 ;; The var `saved-region-selection', if non-nil, is the text in
4420 ;; the region prior to the last command modifying the buffer.
4421 ;; Set the selection to that, or to the current region.
4422 (cond (saved-region-selection
4423 (x-set-selection 'PRIMARY saved-region-selection)
4424 (setq saved-region-selection nil))
4425 ;; If another program has acquired the selection, region
4426 ;; deactivation should not clobber it (Bug#11772).
4427 ((and (/= (region-beginning) (region-end))
4428 (or (x-selection-owner-p 'PRIMARY)
4429 (null (x-selection-exists-p 'PRIMARY))))
4430 (x-set-selection 'PRIMARY
4431 (funcall region-extract-function nil)))))
4432 (when mark-active (force-mode-line-update)) ;Refresh toolbar (bug#16382).
4433 (cond
4434 ((eq (car-safe transient-mark-mode) 'only)
4435 (setq transient-mark-mode (cdr transient-mark-mode)))
4436 ((eq transient-mark-mode 'lambda)
4437 (setq transient-mark-mode nil)))
4438 (setq mark-active nil)
4439 (run-hooks 'deactivate-mark-hook)
4440 (redisplay--update-region-highlight (selected-window))))
4442 (defun activate-mark (&optional no-tmm)
4443 "Activate the mark.
4444 If NO-TMM is non-nil, leave `transient-mark-mode' alone."
4445 (when (mark t)
4446 (unless (region-active-p)
4447 (force-mode-line-update) ;Refresh toolbar (bug#16382).
4448 (setq mark-active t)
4449 (unless (or transient-mark-mode no-tmm)
4450 (setq transient-mark-mode 'lambda))
4451 (run-hooks 'activate-mark-hook))))
4453 (defun set-mark (pos)
4454 "Set this buffer's mark to POS. Don't use this function!
4455 That is to say, don't use this function unless you want
4456 the user to see that the mark has moved, and you want the previous
4457 mark position to be lost.
4459 Normally, when a new mark is set, the old one should go on the stack.
4460 This is why most applications should use `push-mark', not `set-mark'.
4462 Novice Emacs Lisp programmers often try to use the mark for the wrong
4463 purposes. The mark saves a location for the user's convenience.
4464 Most editing commands should not alter the mark.
4465 To remember a location for internal use in the Lisp program,
4466 store it in a Lisp variable. Example:
4468 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
4469 (if pos
4470 (progn
4471 (set-marker (mark-marker) pos (current-buffer))
4472 (activate-mark 'no-tmm))
4473 ;; Normally we never clear mark-active except in Transient Mark mode.
4474 ;; But when we actually clear out the mark value too, we must
4475 ;; clear mark-active in any mode.
4476 (deactivate-mark t)
4477 ;; `deactivate-mark' sometimes leaves mark-active non-nil, but
4478 ;; it should never be nil if the mark is nil.
4479 (setq mark-active nil)
4480 (set-marker (mark-marker) nil)))
4482 (defcustom use-empty-active-region nil
4483 "Whether \"region-aware\" commands should act on empty regions.
4484 If nil, region-aware commands treat empty regions as inactive.
4485 If non-nil, region-aware commands treat the region as active as
4486 long as the mark is active, even if the region is empty.
4488 Region-aware commands are those that act on the region if it is
4489 active and Transient Mark mode is enabled, and on the text near
4490 point otherwise."
4491 :type 'boolean
4492 :version "23.1"
4493 :group 'editing-basics)
4495 (defun use-region-p ()
4496 "Return t if the region is active and it is appropriate to act on it.
4497 This is used by commands that act specially on the region under
4498 Transient Mark mode.
4500 The return value is t if Transient Mark mode is enabled and the
4501 mark is active; furthermore, if `use-empty-active-region' is nil,
4502 the region must not be empty. Otherwise, the return value is nil.
4504 For some commands, it may be appropriate to ignore the value of
4505 `use-empty-active-region'; in that case, use `region-active-p'."
4506 (and (region-active-p)
4507 (or use-empty-active-region (> (region-end) (region-beginning)))))
4509 (defun region-active-p ()
4510 "Return t if Transient Mark mode is enabled and the mark is active.
4512 Some commands act specially on the region when Transient Mark
4513 mode is enabled. Usually, such commands should use
4514 `use-region-p' instead of this function, because `use-region-p'
4515 also checks the value of `use-empty-active-region'."
4516 (and transient-mark-mode mark-active
4517 ;; FIXME: Somehow we sometimes end up with mark-active non-nil but
4518 ;; without the mark being set (e.g. bug#17324). We really should fix
4519 ;; that problem, but in the mean time, let's make sure we don't say the
4520 ;; region is active when there's no mark.
4521 (mark)))
4524 (defvar redisplay-unhighlight-region-function
4525 (lambda (rol) (when (overlayp rol) (delete-overlay rol))))
4527 (defvar redisplay-highlight-region-function
4528 (lambda (start end window rol)
4529 (if (not (overlayp rol))
4530 (let ((nrol (make-overlay start end)))
4531 (funcall redisplay-unhighlight-region-function rol)
4532 (overlay-put nrol 'window window)
4533 (overlay-put nrol 'face 'region)
4534 ;; Normal priority so that a large region doesn't hide all the
4535 ;; overlays within it, but high secondary priority so that if it
4536 ;; ends/starts in the middle of a small overlay, that small overlay
4537 ;; won't hide the region's boundaries.
4538 (overlay-put nrol 'priority '(nil . 100))
4539 nrol)
4540 (unless (and (eq (overlay-buffer rol) (current-buffer))
4541 (eq (overlay-start rol) start)
4542 (eq (overlay-end rol) end))
4543 (move-overlay rol start end (current-buffer)))
4544 rol)))
4546 (defun redisplay--update-region-highlight (window)
4547 (with-current-buffer (window-buffer window)
4548 (let ((rol (window-parameter window 'internal-region-overlay)))
4549 (if (not (region-active-p))
4550 (funcall redisplay-unhighlight-region-function rol)
4551 (let* ((pt (window-point window))
4552 (mark (mark))
4553 (start (min pt mark))
4554 (end (max pt mark))
4555 (new
4556 (funcall redisplay-highlight-region-function
4557 start end window rol)))
4558 (unless (equal new rol)
4559 (set-window-parameter window 'internal-region-overlay
4560 new)))))))
4562 (defun redisplay--update-region-highlights (windows)
4563 (with-demoted-errors "redisplay--update-region-highlights: %S"
4564 (if (null windows)
4565 (redisplay--update-region-highlight (selected-window))
4566 (unless (listp windows) (setq windows (window-list-1 nil nil t)))
4567 (if highlight-nonselected-windows
4568 (mapc #'redisplay--update-region-highlight windows)
4569 (let ((msw (and (window-minibuffer-p) (minibuffer-selected-window))))
4570 (dolist (w windows)
4571 (if (or (eq w (selected-window)) (eq w msw))
4572 (redisplay--update-region-highlight w)
4573 (funcall redisplay-unhighlight-region-function
4574 (window-parameter w 'internal-region-overlay)))))))))
4576 (add-function :before pre-redisplay-function
4577 #'redisplay--update-region-highlights)
4580 (defvar-local mark-ring nil
4581 "The list of former marks of the current buffer, most recent first.")
4582 (put 'mark-ring 'permanent-local t)
4584 (defcustom mark-ring-max 16
4585 "Maximum size of mark ring. Start discarding off end if gets this big."
4586 :type 'integer
4587 :group 'editing-basics)
4589 (defvar global-mark-ring nil
4590 "The list of saved global marks, most recent first.")
4592 (defcustom global-mark-ring-max 16
4593 "Maximum size of global mark ring. \
4594 Start discarding off end if gets this big."
4595 :type 'integer
4596 :group 'editing-basics)
4598 (defun pop-to-mark-command ()
4599 "Jump to mark, and pop a new position for mark off the ring.
4600 \(Does not affect global mark ring)."
4601 (interactive)
4602 (if (null (mark t))
4603 (error "No mark set in this buffer")
4604 (if (= (point) (mark t))
4605 (message "Mark popped"))
4606 (goto-char (mark t))
4607 (pop-mark)))
4609 (defun push-mark-command (arg &optional nomsg)
4610 "Set mark at where point is.
4611 If no prefix ARG and mark is already set there, just activate it.
4612 Display `Mark set' unless the optional second arg NOMSG is non-nil."
4613 (interactive "P")
4614 (let ((mark (mark t)))
4615 (if (or arg (null mark) (/= mark (point)))
4616 (push-mark nil nomsg t)
4617 (activate-mark 'no-tmm)
4618 (unless nomsg
4619 (message "Mark activated")))))
4621 (defcustom set-mark-command-repeat-pop nil
4622 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
4623 That means that C-u \\[set-mark-command] \\[set-mark-command]
4624 will pop the mark twice, and
4625 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
4626 will pop the mark three times.
4628 A value of nil means \\[set-mark-command]'s behavior does not change
4629 after C-u \\[set-mark-command]."
4630 :type 'boolean
4631 :group 'editing-basics)
4633 (defun set-mark-command (arg)
4634 "Set the mark where point is, or jump to the mark.
4635 Setting the mark also alters the region, which is the text
4636 between point and mark; this is the closest equivalent in
4637 Emacs to what some editors call the \"selection\".
4639 With no prefix argument, set the mark at point, and push the
4640 old mark position on local mark ring. Also push the old mark on
4641 global mark ring, if the previous mark was set in another buffer.
4643 When Transient Mark Mode is off, immediately repeating this
4644 command activates `transient-mark-mode' temporarily.
4646 With prefix argument (e.g., \\[universal-argument] \\[set-mark-command]), \
4647 jump to the mark, and set the mark from
4648 position popped off the local mark ring (this does not affect the global
4649 mark ring). Use \\[pop-global-mark] to jump to a mark popped off the global
4650 mark ring (see `pop-global-mark').
4652 If `set-mark-command-repeat-pop' is non-nil, repeating
4653 the \\[set-mark-command] command with no prefix argument pops the next position
4654 off the local (or global) mark ring and jumps there.
4656 With \\[universal-argument] \\[universal-argument] as prefix
4657 argument, unconditionally set mark where point is, even if
4658 `set-mark-command-repeat-pop' is non-nil.
4660 Novice Emacs Lisp programmers often try to use the mark for the wrong
4661 purposes. See the documentation of `set-mark' for more information."
4662 (interactive "P")
4663 (cond ((eq transient-mark-mode 'lambda)
4664 (setq transient-mark-mode nil))
4665 ((eq (car-safe transient-mark-mode) 'only)
4666 (deactivate-mark)))
4667 (cond
4668 ((and (consp arg) (> (prefix-numeric-value arg) 4))
4669 (push-mark-command nil))
4670 ((not (eq this-command 'set-mark-command))
4671 (if arg
4672 (pop-to-mark-command)
4673 (push-mark-command t)))
4674 ((and set-mark-command-repeat-pop
4675 (eq last-command 'pop-to-mark-command))
4676 (setq this-command 'pop-to-mark-command)
4677 (pop-to-mark-command))
4678 ((and set-mark-command-repeat-pop
4679 (eq last-command 'pop-global-mark)
4680 (not arg))
4681 (setq this-command 'pop-global-mark)
4682 (pop-global-mark))
4683 (arg
4684 (setq this-command 'pop-to-mark-command)
4685 (pop-to-mark-command))
4686 ((eq last-command 'set-mark-command)
4687 (if (region-active-p)
4688 (progn
4689 (deactivate-mark)
4690 (message "Mark deactivated"))
4691 (activate-mark)
4692 (message "Mark activated")))
4694 (push-mark-command nil))))
4696 (defun push-mark (&optional location nomsg activate)
4697 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
4698 If the last global mark pushed was not in the current buffer,
4699 also push LOCATION on the global mark ring.
4700 Display `Mark set' unless the optional second arg NOMSG is non-nil.
4702 Novice Emacs Lisp programmers often try to use the mark for the wrong
4703 purposes. See the documentation of `set-mark' for more information.
4705 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
4706 (unless (null (mark t))
4707 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
4708 (when (> (length mark-ring) mark-ring-max)
4709 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
4710 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
4711 (set-marker (mark-marker) (or location (point)) (current-buffer))
4712 ;; Now push the mark on the global mark ring.
4713 (if (and global-mark-ring
4714 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
4715 ;; The last global mark pushed was in this same buffer.
4716 ;; Don't push another one.
4718 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
4719 (when (> (length global-mark-ring) global-mark-ring-max)
4720 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
4721 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
4722 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
4723 (message "Mark set"))
4724 (if (or activate (not transient-mark-mode))
4725 (set-mark (mark t)))
4726 nil)
4728 (defun pop-mark ()
4729 "Pop off mark ring into the buffer's actual mark.
4730 Does not set point. Does nothing if mark ring is empty."
4731 (when mark-ring
4732 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
4733 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
4734 (move-marker (car mark-ring) nil)
4735 (if (null (mark t)) (ding))
4736 (setq mark-ring (cdr mark-ring)))
4737 (deactivate-mark))
4739 (define-obsolete-function-alias
4740 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
4741 (defun exchange-point-and-mark (&optional arg)
4742 "Put the mark where point is now, and point where the mark is now.
4743 This command works even when the mark is not active,
4744 and it reactivates the mark.
4746 If Transient Mark mode is on, a prefix ARG deactivates the mark
4747 if it is active, and otherwise avoids reactivating it. If
4748 Transient Mark mode is off, a prefix ARG enables Transient Mark
4749 mode temporarily."
4750 (interactive "P")
4751 (let ((omark (mark t))
4752 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
4753 (if (null omark)
4754 (error "No mark set in this buffer"))
4755 (set-mark (point))
4756 (goto-char omark)
4757 (cond (temp-highlight
4758 (setq transient-mark-mode (cons 'only transient-mark-mode)))
4759 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
4760 (not (or arg (region-active-p))))
4761 (deactivate-mark))
4762 (t (activate-mark)))
4763 nil))
4765 (defcustom shift-select-mode t
4766 "When non-nil, shifted motion keys activate the mark momentarily.
4768 While the mark is activated in this way, any shift-translated point
4769 motion key extends the region, and if Transient Mark mode was off, it
4770 is temporarily turned on. Furthermore, the mark will be deactivated
4771 by any subsequent point motion key that was not shift-translated, or
4772 by any action that normally deactivates the mark in Transient Mark mode.
4774 See `this-command-keys-shift-translated' for the meaning of
4775 shift-translation."
4776 :type 'boolean
4777 :group 'editing-basics)
4779 (defun handle-shift-selection ()
4780 "Activate/deactivate mark depending on invocation thru shift translation.
4781 This function is called by `call-interactively' when a command
4782 with a `^' character in its `interactive' spec is invoked, before
4783 running the command itself.
4785 If `shift-select-mode' is enabled and the command was invoked
4786 through shift translation, set the mark and activate the region
4787 temporarily, unless it was already set in this way. See
4788 `this-command-keys-shift-translated' for the meaning of shift
4789 translation.
4791 Otherwise, if the region has been activated temporarily,
4792 deactivate it, and restore the variable `transient-mark-mode' to
4793 its earlier value."
4794 (cond ((and shift-select-mode this-command-keys-shift-translated)
4795 (unless (and mark-active
4796 (eq (car-safe transient-mark-mode) 'only))
4797 (setq transient-mark-mode
4798 (cons 'only
4799 (unless (eq transient-mark-mode 'lambda)
4800 transient-mark-mode)))
4801 (push-mark nil nil t)))
4802 ((eq (car-safe transient-mark-mode) 'only)
4803 (setq transient-mark-mode (cdr transient-mark-mode))
4804 (deactivate-mark))))
4806 (define-minor-mode transient-mark-mode
4807 "Toggle Transient Mark mode.
4808 With a prefix argument ARG, enable Transient Mark mode if ARG is
4809 positive, and disable it otherwise. If called from Lisp, enable
4810 Transient Mark mode if ARG is omitted or nil.
4812 Transient Mark mode is a global minor mode. When enabled, the
4813 region is highlighted whenever the mark is active. The mark is
4814 \"deactivated\" by changing the buffer, and after certain other
4815 operations that set the mark but whose main purpose is something
4816 else--for example, incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
4818 You can also deactivate the mark by typing \\[keyboard-quit] or
4819 \\[keyboard-escape-quit].
4821 Many commands change their behavior when Transient Mark mode is
4822 in effect and the mark is active, by acting on the region instead
4823 of their usual default part of the buffer's text. Examples of
4824 such commands include \\[comment-dwim], \\[flush-lines], \\[keep-lines],
4825 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
4826 To see the documentation of commands which are sensitive to the
4827 Transient Mark mode, invoke \\[apropos-documentation] and type \"transient\"
4828 or \"mark.*active\" at the prompt."
4829 :global t
4830 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
4831 :variable transient-mark-mode)
4833 (defvar widen-automatically t
4834 "Non-nil means it is ok for commands to call `widen' when they want to.
4835 Some commands will do this in order to go to positions outside
4836 the current accessible part of the buffer.
4838 If `widen-automatically' is nil, these commands will do something else
4839 as a fallback, and won't change the buffer bounds.")
4841 (defvar non-essential nil
4842 "Whether the currently executing code is performing an essential task.
4843 This variable should be non-nil only when running code which should not
4844 disturb the user. E.g. it can be used to prevent Tramp from prompting the
4845 user for a password when we are simply scanning a set of files in the
4846 background or displaying possible completions before the user even asked
4847 for it.")
4849 (defun pop-global-mark ()
4850 "Pop off global mark ring and jump to the top location."
4851 (interactive)
4852 ;; Pop entries which refer to non-existent buffers.
4853 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
4854 (setq global-mark-ring (cdr global-mark-ring)))
4855 (or global-mark-ring
4856 (error "No global mark set"))
4857 (let* ((marker (car global-mark-ring))
4858 (buffer (marker-buffer marker))
4859 (position (marker-position marker)))
4860 (setq global-mark-ring (nconc (cdr global-mark-ring)
4861 (list (car global-mark-ring))))
4862 (set-buffer buffer)
4863 (or (and (>= position (point-min))
4864 (<= position (point-max)))
4865 (if widen-automatically
4866 (widen)
4867 (error "Global mark position is outside accessible part of buffer")))
4868 (goto-char position)
4869 (switch-to-buffer buffer)))
4871 (defcustom next-line-add-newlines nil
4872 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
4873 :type 'boolean
4874 :version "21.1"
4875 :group 'editing-basics)
4877 (defun next-line (&optional arg try-vscroll)
4878 "Move cursor vertically down ARG lines.
4879 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4880 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
4881 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
4882 function will not vscroll.
4884 ARG defaults to 1.
4886 If there is no character in the target line exactly under the current column,
4887 the cursor is positioned after the character in that line which spans this
4888 column, or at the end of the line if it is not long enough.
4889 If there is no line in the buffer after this one, behavior depends on the
4890 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
4891 to create a line, and moves the cursor to that line. Otherwise it moves the
4892 cursor to the end of the buffer.
4894 If the variable `line-move-visual' is non-nil, this command moves
4895 by display lines. Otherwise, it moves by buffer lines, without
4896 taking variable-width characters or continued lines into account.
4898 The command \\[set-goal-column] can be used to create
4899 a semipermanent goal column for this command.
4900 Then instead of trying to move exactly vertically (or as close as possible),
4901 this command moves to the specified goal column (or as close as possible).
4902 The goal column is stored in the variable `goal-column', which is nil
4903 when there is no goal column. Note that setting `goal-column'
4904 overrides `line-move-visual' and causes this command to move by buffer
4905 lines rather than by display lines.
4907 If you are thinking of using this in a Lisp program, consider
4908 using `forward-line' instead. It is usually easier to use
4909 and more reliable (no dependence on goal column, etc.)."
4910 (interactive "^p\np")
4911 (or arg (setq arg 1))
4912 (if (and next-line-add-newlines (= arg 1))
4913 (if (save-excursion (end-of-line) (eobp))
4914 ;; When adding a newline, don't expand an abbrev.
4915 (let ((abbrev-mode nil))
4916 (end-of-line)
4917 (insert (if use-hard-newlines hard-newline "\n")))
4918 (line-move arg nil nil try-vscroll))
4919 (if (called-interactively-p 'interactive)
4920 (condition-case err
4921 (line-move arg nil nil try-vscroll)
4922 ((beginning-of-buffer end-of-buffer)
4923 (signal (car err) (cdr err))))
4924 (line-move arg nil nil try-vscroll)))
4925 nil)
4926 (put 'next-line 'interactive-only 'forward-line)
4928 (defun previous-line (&optional arg try-vscroll)
4929 "Move cursor vertically up ARG lines.
4930 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4931 Non-interactively, use TRY-VSCROLL to control whether to vscroll tall
4932 lines: if either `auto-window-vscroll' or TRY-VSCROLL is nil, this
4933 function will not vscroll.
4935 ARG defaults to 1.
4937 If there is no character in the target line exactly over the current column,
4938 the cursor is positioned after the character in that line which spans this
4939 column, or at the end of the line if it is not long enough.
4941 If the variable `line-move-visual' is non-nil, this command moves
4942 by display lines. Otherwise, it moves by buffer lines, without
4943 taking variable-width characters or continued lines into account.
4945 The command \\[set-goal-column] can be used to create
4946 a semipermanent goal column for this command.
4947 Then instead of trying to move exactly vertically (or as close as possible),
4948 this command moves to the specified goal column (or as close as possible).
4949 The goal column is stored in the variable `goal-column', which is nil
4950 when there is no goal column. Note that setting `goal-column'
4951 overrides `line-move-visual' and causes this command to move by buffer
4952 lines rather than by display lines.
4954 If you are thinking of using this in a Lisp program, consider using
4955 `forward-line' with a negative argument instead. It is usually easier
4956 to use and more reliable (no dependence on goal column, etc.)."
4957 (interactive "^p\np")
4958 (or arg (setq arg 1))
4959 (if (called-interactively-p 'interactive)
4960 (condition-case err
4961 (line-move (- arg) nil nil try-vscroll)
4962 ((beginning-of-buffer end-of-buffer)
4963 (signal (car err) (cdr err))))
4964 (line-move (- arg) nil nil try-vscroll))
4965 nil)
4966 (put 'previous-line 'interactive-only
4967 "use `forward-line' with negative argument instead.")
4969 (defcustom track-eol nil
4970 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
4971 This means moving to the end of each line moved onto.
4972 The beginning of a blank line does not count as the end of a line.
4973 This has no effect when the variable `line-move-visual' is non-nil."
4974 :type 'boolean
4975 :group 'editing-basics)
4977 (defcustom goal-column nil
4978 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil.
4979 A non-nil setting overrides the variable `line-move-visual', which see."
4980 :type '(choice integer
4981 (const :tag "None" nil))
4982 :group 'editing-basics)
4983 (make-variable-buffer-local 'goal-column)
4985 (defvar temporary-goal-column 0
4986 "Current goal column for vertical motion.
4987 It is the column where point was at the start of the current run
4988 of vertical motion commands.
4990 When moving by visual lines via the function `line-move-visual', it is a cons
4991 cell (COL . HSCROLL), where COL is the x-position, in pixels,
4992 divided by the default column width, and HSCROLL is the number of
4993 columns by which window is scrolled from left margin.
4995 When the `track-eol' feature is doing its job, the value is
4996 `most-positive-fixnum'.")
4998 (defcustom line-move-ignore-invisible t
4999 "Non-nil means commands that move by lines ignore invisible newlines.
5000 When this option is non-nil, \\[next-line], \\[previous-line], \\[move-end-of-line], and \\[move-beginning-of-line] behave
5001 as if newlines that are invisible didn't exist, and count
5002 only visible newlines. Thus, moving across across 2 newlines
5003 one of which is invisible will be counted as a one-line move.
5004 Also, a non-nil value causes invisible text to be ignored when
5005 counting columns for the purposes of keeping point in the same
5006 column by \\[next-line] and \\[previous-line].
5008 Outline mode sets this."
5009 :type 'boolean
5010 :group 'editing-basics)
5012 (defcustom line-move-visual t
5013 "When non-nil, `line-move' moves point by visual lines.
5014 This movement is based on where the cursor is displayed on the
5015 screen, instead of relying on buffer contents alone. It takes
5016 into account variable-width characters and line continuation.
5017 If nil, `line-move' moves point by logical lines.
5018 A non-nil setting of `goal-column' overrides the value of this variable
5019 and forces movement by logical lines.
5020 A window that is horizontally scrolled also forces movement by logical
5021 lines."
5022 :type 'boolean
5023 :group 'editing-basics
5024 :version "23.1")
5026 ;; Only used if display-graphic-p.
5027 (declare-function font-info "font.c" (name &optional frame))
5029 (defun default-font-height ()
5030 "Return the height in pixels of the current buffer's default face font."
5031 (let ((default-font (face-font 'default)))
5032 (cond
5033 ((and (display-multi-font-p)
5034 ;; Avoid calling font-info if the frame's default font was
5035 ;; not changed since the frame was created. That's because
5036 ;; font-info is expensive for some fonts, see bug #14838.
5037 (not (string= (frame-parameter nil 'font) default-font)))
5038 (aref (font-info default-font) 3))
5039 (t (frame-char-height)))))
5041 (defun default-line-height ()
5042 "Return the pixel height of current buffer's default-face text line.
5044 The value includes `line-spacing', if any, defined for the buffer
5045 or the frame."
5046 (let ((dfh (default-font-height))
5047 (lsp (if (display-graphic-p)
5048 (or line-spacing
5049 (default-value 'line-spacing)
5050 (frame-parameter nil 'line-spacing)
5052 0)))
5053 (if (floatp lsp)
5054 (setq lsp (truncate (* (frame-char-height) lsp))))
5055 (+ dfh lsp)))
5057 (defun window-screen-lines ()
5058 "Return the number of screen lines in the text area of the selected window.
5060 This is different from `window-text-height' in that this function counts
5061 lines in units of the height of the font used by the default face displayed
5062 in the window, not in units of the frame's default font, and also accounts
5063 for `line-spacing', if any, defined for the window's buffer or frame.
5065 The value is a floating-point number."
5066 (let ((edges (window-inside-pixel-edges))
5067 (dlh (default-line-height)))
5068 (/ (float (- (nth 3 edges) (nth 1 edges))) dlh)))
5070 ;; Returns non-nil if partial move was done.
5071 (defun line-move-partial (arg noerror to-end)
5072 (if (< arg 0)
5073 ;; Move backward (up).
5074 ;; If already vscrolled, reduce vscroll
5075 (let ((vs (window-vscroll nil t))
5076 (dlh (default-line-height)))
5077 (when (> vs dlh)
5078 (set-window-vscroll nil (- vs dlh) t)))
5080 ;; Move forward (down).
5081 (let* ((lh (window-line-height -1))
5082 (rowh (car lh))
5083 (vpos (nth 1 lh))
5084 (ypos (nth 2 lh))
5085 (rbot (nth 3 lh))
5086 (this-lh (window-line-height))
5087 (this-height (car this-lh))
5088 (this-ypos (nth 2 this-lh))
5089 (dlh (default-line-height))
5090 (wslines (window-screen-lines))
5091 (edges (window-inside-pixel-edges))
5092 (winh (- (nth 3 edges) (nth 1 edges) 1))
5093 py vs last-line)
5094 (if (> (mod wslines 1.0) 0.0)
5095 (setq wslines (round (+ wslines 0.5))))
5096 (when (or (null lh)
5097 (>= rbot dlh)
5098 (<= ypos (- dlh))
5099 (null this-lh)
5100 (<= this-ypos (- dlh)))
5101 (unless lh
5102 (let ((wend (pos-visible-in-window-p t nil t)))
5103 (setq rbot (nth 3 wend)
5104 rowh (nth 4 wend)
5105 vpos (nth 5 wend))))
5106 (unless this-lh
5107 (let ((wstart (pos-visible-in-window-p nil nil t)))
5108 (setq this-ypos (nth 2 wstart)
5109 this-height (nth 4 wstart))))
5110 (setq py
5111 (or (nth 1 this-lh)
5112 (let ((ppos (posn-at-point))
5113 col-row)
5114 (setq col-row (posn-actual-col-row ppos))
5115 (if col-row
5116 (- (cdr col-row) (window-vscroll))
5117 (cdr (posn-col-row ppos))))))
5118 ;; VPOS > 0 means the last line is only partially visible.
5119 ;; But if the part that is visible is at least as tall as the
5120 ;; default font, that means the line is actually fully
5121 ;; readable, and something like line-spacing is hidden. So in
5122 ;; that case we accept the last line in the window as still
5123 ;; visible, and consider the margin as starting one line
5124 ;; later.
5125 (if (and vpos (> vpos 0))
5126 (if (and rowh
5127 (>= rowh (default-font-height))
5128 (< rowh dlh))
5129 (setq last-line (min (- wslines scroll-margin) vpos))
5130 (setq last-line (min (- wslines scroll-margin 1) (1- vpos)))))
5131 (cond
5132 ;; If last line of window is fully visible, and vscrolling
5133 ;; more would make this line invisible, move forward.
5134 ((and (or (< (setq vs (window-vscroll nil t)) dlh)
5135 (null this-height)
5136 (<= this-height dlh))
5137 (or (null rbot) (= rbot 0)))
5138 nil)
5139 ;; If cursor is not in the bottom scroll margin, and the
5140 ;; current line is is not too tall, move forward.
5141 ((and (or (null this-height) (<= this-height winh))
5142 vpos
5143 (> vpos 0)
5144 (< py last-line))
5145 nil)
5146 ;; When already vscrolled, we vscroll some more if we can,
5147 ;; or clear vscroll and move forward at end of tall image.
5148 ((> vs 0)
5149 (when (or (and rbot (> rbot 0))
5150 (and this-height (> this-height dlh)))
5151 (set-window-vscroll nil (+ vs dlh) t)))
5152 ;; If cursor just entered the bottom scroll margin, move forward,
5153 ;; but also optionally vscroll one line so redisplay won't recenter.
5154 ((and vpos
5155 (> vpos 0)
5156 (= py last-line))
5157 ;; Don't vscroll if the partially-visible line at window
5158 ;; bottom is not too tall (a.k.a. "just one more text
5159 ;; line"): in that case, we do want redisplay to behave
5160 ;; normally, i.e. recenter or whatever.
5162 ;; Note: ROWH + RBOT from the value returned by
5163 ;; pos-visible-in-window-p give the total height of the
5164 ;; partially-visible glyph row at the end of the window. As
5165 ;; we are dealing with floats, we disregard sub-pixel
5166 ;; discrepancies between that and DLH.
5167 (if (and rowh rbot (>= (- (+ rowh rbot) winh) 1))
5168 (set-window-vscroll nil dlh t))
5169 (line-move-1 arg noerror to-end)
5171 ;; If there are lines above the last line, scroll-up one line.
5172 ((and vpos (> vpos 0))
5173 (scroll-up 1)
5175 ;; Finally, start vscroll.
5177 (set-window-vscroll nil dlh t)))))))
5180 ;; This is like line-move-1 except that it also performs
5181 ;; vertical scrolling of tall images if appropriate.
5182 ;; That is not really a clean thing to do, since it mixes
5183 ;; scrolling with cursor motion. But so far we don't have
5184 ;; a cleaner solution to the problem of making C-n do something
5185 ;; useful given a tall image.
5186 (defun line-move (arg &optional noerror to-end try-vscroll)
5187 "Move forward ARG lines.
5188 If NOERROR, don't signal an error if we can't move ARG lines.
5189 TO-END is unused.
5190 TRY-VSCROLL controls whether to vscroll tall lines: if either
5191 `auto-window-vscroll' or TRY-VSCROLL is nil, this function will
5192 not vscroll."
5193 (if noninteractive
5194 (forward-line arg)
5195 (unless (and auto-window-vscroll try-vscroll
5196 ;; Only vscroll for single line moves
5197 (= (abs arg) 1)
5198 ;; Under scroll-conservatively, the display engine
5199 ;; does this better.
5200 (zerop scroll-conservatively)
5201 ;; But don't vscroll in a keyboard macro.
5202 (not defining-kbd-macro)
5203 (not executing-kbd-macro)
5204 (line-move-partial arg noerror to-end))
5205 (set-window-vscroll nil 0 t)
5206 (if (and line-move-visual
5207 ;; Display-based column are incompatible with goal-column.
5208 (not goal-column)
5209 ;; When the text in the window is scrolled to the left,
5210 ;; display-based motion doesn't make sense (because each
5211 ;; logical line occupies exactly one screen line).
5212 (not (> (window-hscroll) 0))
5213 ;; Likewise when the text _was_ scrolled to the left
5214 ;; when the current run of vertical motion commands
5215 ;; started.
5216 (not (and (memq last-command
5217 `(next-line previous-line ,this-command))
5218 auto-hscroll-mode
5219 (numberp temporary-goal-column)
5220 (>= temporary-goal-column
5221 (- (window-width) hscroll-margin)))))
5222 (prog1 (line-move-visual arg noerror)
5223 ;; If we moved into a tall line, set vscroll to make
5224 ;; scrolling through tall images more smooth.
5225 (let ((lh (line-pixel-height))
5226 (edges (window-inside-pixel-edges))
5227 (dlh (default-line-height))
5228 winh)
5229 (setq winh (- (nth 3 edges) (nth 1 edges) 1))
5230 (if (and (< arg 0)
5231 (< (point) (window-start))
5232 (> lh winh))
5233 (set-window-vscroll
5235 (- lh dlh) t))))
5236 (line-move-1 arg noerror to-end)))))
5238 ;; Display-based alternative to line-move-1.
5239 ;; Arg says how many lines to move. The value is t if we can move the
5240 ;; specified number of lines.
5241 (defun line-move-visual (arg &optional noerror)
5242 "Move ARG lines forward.
5243 If NOERROR, don't signal an error if we can't move that many lines."
5244 (let ((opoint (point))
5245 (hscroll (window-hscroll))
5246 target-hscroll)
5247 ;; Check if the previous command was a line-motion command, or if
5248 ;; we were called from some other command.
5249 (if (and (consp temporary-goal-column)
5250 (memq last-command `(next-line previous-line ,this-command)))
5251 ;; If so, there's no need to reset `temporary-goal-column',
5252 ;; but we may need to hscroll.
5253 (if (or (/= (cdr temporary-goal-column) hscroll)
5254 (> (cdr temporary-goal-column) 0))
5255 (setq target-hscroll (cdr temporary-goal-column)))
5256 ;; Otherwise, we should reset `temporary-goal-column'.
5257 (let ((posn (posn-at-point)))
5258 (cond
5259 ;; Handle the `overflow-newline-into-fringe' case:
5260 ((eq (nth 1 posn) 'right-fringe)
5261 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
5262 ((car (posn-x-y posn))
5263 (setq temporary-goal-column
5264 (cons (/ (float (car (posn-x-y posn)))
5265 (frame-char-width)) hscroll))))))
5266 (if target-hscroll
5267 (set-window-hscroll (selected-window) target-hscroll))
5268 ;; vertical-motion can move more than it was asked to if it moves
5269 ;; across display strings with newlines. We don't want to ring
5270 ;; the bell and announce beginning/end of buffer in that case.
5271 (or (and (or (and (>= arg 0)
5272 (>= (vertical-motion
5273 (cons (or goal-column
5274 (if (consp temporary-goal-column)
5275 (car temporary-goal-column)
5276 temporary-goal-column))
5277 arg))
5278 arg))
5279 (and (< arg 0)
5280 (<= (vertical-motion
5281 (cons (or goal-column
5282 (if (consp temporary-goal-column)
5283 (car temporary-goal-column)
5284 temporary-goal-column))
5285 arg))
5286 arg)))
5287 (or (>= arg 0)
5288 (/= (point) opoint)
5289 ;; If the goal column lies on a display string,
5290 ;; `vertical-motion' advances the cursor to the end
5291 ;; of the string. For arg < 0, this can cause the
5292 ;; cursor to get stuck. (Bug#3020).
5293 (= (vertical-motion arg) arg)))
5294 (unless noerror
5295 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
5296 nil)))))
5298 ;; This is the guts of next-line and previous-line.
5299 ;; Arg says how many lines to move.
5300 ;; The value is t if we can move the specified number of lines.
5301 (defun line-move-1 (arg &optional noerror _to-end)
5302 ;; Don't run any point-motion hooks, and disregard intangibility,
5303 ;; for intermediate positions.
5304 (let ((inhibit-point-motion-hooks t)
5305 (opoint (point))
5306 (orig-arg arg))
5307 (if (consp temporary-goal-column)
5308 (setq temporary-goal-column (+ (car temporary-goal-column)
5309 (cdr temporary-goal-column))))
5310 (unwind-protect
5311 (progn
5312 (if (not (memq last-command '(next-line previous-line)))
5313 (setq temporary-goal-column
5314 (if (and track-eol (eolp)
5315 ;; Don't count beg of empty line as end of line
5316 ;; unless we just did explicit end-of-line.
5317 (or (not (bolp)) (eq last-command 'move-end-of-line)))
5318 most-positive-fixnum
5319 (current-column))))
5321 (if (not (or (integerp selective-display)
5322 line-move-ignore-invisible))
5323 ;; Use just newline characters.
5324 ;; Set ARG to 0 if we move as many lines as requested.
5325 (or (if (> arg 0)
5326 (progn (if (> arg 1) (forward-line (1- arg)))
5327 ;; This way of moving forward ARG lines
5328 ;; verifies that we have a newline after the last one.
5329 ;; It doesn't get confused by intangible text.
5330 (end-of-line)
5331 (if (zerop (forward-line 1))
5332 (setq arg 0)))
5333 (and (zerop (forward-line arg))
5334 (bolp)
5335 (setq arg 0)))
5336 (unless noerror
5337 (signal (if (< arg 0)
5338 'beginning-of-buffer
5339 'end-of-buffer)
5340 nil)))
5341 ;; Move by arg lines, but ignore invisible ones.
5342 (let (done)
5343 (while (and (> arg 0) (not done))
5344 ;; If the following character is currently invisible,
5345 ;; skip all characters with that same `invisible' property value.
5346 (while (and (not (eobp)) (invisible-p (point)))
5347 (goto-char (next-char-property-change (point))))
5348 ;; Move a line.
5349 ;; We don't use `end-of-line', since we want to escape
5350 ;; from field boundaries occurring exactly at point.
5351 (goto-char (constrain-to-field
5352 (let ((inhibit-field-text-motion t))
5353 (line-end-position))
5354 (point) t t
5355 'inhibit-line-move-field-capture))
5356 ;; If there's no invisibility here, move over the newline.
5357 (cond
5358 ((eobp)
5359 (if (not noerror)
5360 (signal 'end-of-buffer nil)
5361 (setq done t)))
5362 ((and (> arg 1) ;; Use vertical-motion for last move
5363 (not (integerp selective-display))
5364 (not (invisible-p (point))))
5365 ;; We avoid vertical-motion when possible
5366 ;; because that has to fontify.
5367 (forward-line 1))
5368 ;; Otherwise move a more sophisticated way.
5369 ((zerop (vertical-motion 1))
5370 (if (not noerror)
5371 (signal 'end-of-buffer nil)
5372 (setq done t))))
5373 (unless done
5374 (setq arg (1- arg))))
5375 ;; The logic of this is the same as the loop above,
5376 ;; it just goes in the other direction.
5377 (while (and (< arg 0) (not done))
5378 ;; For completely consistency with the forward-motion
5379 ;; case, we should call beginning-of-line here.
5380 ;; However, if point is inside a field and on a
5381 ;; continued line, the call to (vertical-motion -1)
5382 ;; below won't move us back far enough; then we return
5383 ;; to the same column in line-move-finish, and point
5384 ;; gets stuck -- cyd
5385 (forward-line 0)
5386 (cond
5387 ((bobp)
5388 (if (not noerror)
5389 (signal 'beginning-of-buffer nil)
5390 (setq done t)))
5391 ((and (< arg -1) ;; Use vertical-motion for last move
5392 (not (integerp selective-display))
5393 (not (invisible-p (1- (point)))))
5394 (forward-line -1))
5395 ((zerop (vertical-motion -1))
5396 (if (not noerror)
5397 (signal 'beginning-of-buffer nil)
5398 (setq done t))))
5399 (unless done
5400 (setq arg (1+ arg))
5401 (while (and ;; Don't move over previous invis lines
5402 ;; if our target is the middle of this line.
5403 (or (zerop (or goal-column temporary-goal-column))
5404 (< arg 0))
5405 (not (bobp)) (invisible-p (1- (point))))
5406 (goto-char (previous-char-property-change (point))))))))
5407 ;; This is the value the function returns.
5408 (= arg 0))
5410 (cond ((> arg 0)
5411 ;; If we did not move down as far as desired, at least go
5412 ;; to end of line. Be sure to call point-entered and
5413 ;; point-left-hooks.
5414 (let* ((npoint (prog1 (line-end-position)
5415 (goto-char opoint)))
5416 (inhibit-point-motion-hooks nil))
5417 (goto-char npoint)))
5418 ((< arg 0)
5419 ;; If we did not move up as far as desired,
5420 ;; at least go to beginning of line.
5421 (let* ((npoint (prog1 (line-beginning-position)
5422 (goto-char opoint)))
5423 (inhibit-point-motion-hooks nil))
5424 (goto-char npoint)))
5426 (line-move-finish (or goal-column temporary-goal-column)
5427 opoint (> orig-arg 0)))))))
5429 (defun line-move-finish (column opoint forward)
5430 (let ((repeat t))
5431 (while repeat
5432 ;; Set REPEAT to t to repeat the whole thing.
5433 (setq repeat nil)
5435 (let (new
5436 (old (point))
5437 (line-beg (line-beginning-position))
5438 (line-end
5439 ;; Compute the end of the line
5440 ;; ignoring effectively invisible newlines.
5441 (save-excursion
5442 ;; Like end-of-line but ignores fields.
5443 (skip-chars-forward "^\n")
5444 (while (and (not (eobp)) (invisible-p (point)))
5445 (goto-char (next-char-property-change (point)))
5446 (skip-chars-forward "^\n"))
5447 (point))))
5449 ;; Move to the desired column.
5450 (line-move-to-column (truncate column))
5452 ;; Corner case: suppose we start out in a field boundary in
5453 ;; the middle of a continued line. When we get to
5454 ;; line-move-finish, point is at the start of a new *screen*
5455 ;; line but the same text line; then line-move-to-column would
5456 ;; move us backwards. Test using C-n with point on the "x" in
5457 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
5458 (and forward
5459 (< (point) old)
5460 (goto-char old))
5462 (setq new (point))
5464 ;; Process intangibility within a line.
5465 ;; With inhibit-point-motion-hooks bound to nil, a call to
5466 ;; goto-char moves point past intangible text.
5468 ;; However, inhibit-point-motion-hooks controls both the
5469 ;; intangibility and the point-entered/point-left hooks. The
5470 ;; following hack avoids calling the point-* hooks
5471 ;; unnecessarily. Note that we move *forward* past intangible
5472 ;; text when the initial and final points are the same.
5473 (goto-char new)
5474 (let ((inhibit-point-motion-hooks nil))
5475 (goto-char new)
5477 ;; If intangibility moves us to a different (later) place
5478 ;; in the same line, use that as the destination.
5479 (if (<= (point) line-end)
5480 (setq new (point))
5481 ;; If that position is "too late",
5482 ;; try the previous allowable position.
5483 ;; See if it is ok.
5484 (backward-char)
5485 (if (if forward
5486 ;; If going forward, don't accept the previous
5487 ;; allowable position if it is before the target line.
5488 (< line-beg (point))
5489 ;; If going backward, don't accept the previous
5490 ;; allowable position if it is still after the target line.
5491 (<= (point) line-end))
5492 (setq new (point))
5493 ;; As a last resort, use the end of the line.
5494 (setq new line-end))))
5496 ;; Now move to the updated destination, processing fields
5497 ;; as well as intangibility.
5498 (goto-char opoint)
5499 (let ((inhibit-point-motion-hooks nil))
5500 (goto-char
5501 ;; Ignore field boundaries if the initial and final
5502 ;; positions have the same `field' property, even if the
5503 ;; fields are non-contiguous. This seems to be "nicer"
5504 ;; behavior in many situations.
5505 (if (eq (get-char-property new 'field)
5506 (get-char-property opoint 'field))
5508 (constrain-to-field new opoint t t
5509 'inhibit-line-move-field-capture))))
5511 ;; If all this moved us to a different line,
5512 ;; retry everything within that new line.
5513 (when (or (< (point) line-beg) (> (point) line-end))
5514 ;; Repeat the intangibility and field processing.
5515 (setq repeat t))))))
5517 (defun line-move-to-column (col)
5518 "Try to find column COL, considering invisibility.
5519 This function works only in certain cases,
5520 because what we really need is for `move-to-column'
5521 and `current-column' to be able to ignore invisible text."
5522 (if (zerop col)
5523 (beginning-of-line)
5524 (move-to-column col))
5526 (when (and line-move-ignore-invisible
5527 (not (bolp)) (invisible-p (1- (point))))
5528 (let ((normal-location (point))
5529 (normal-column (current-column)))
5530 ;; If the following character is currently invisible,
5531 ;; skip all characters with that same `invisible' property value.
5532 (while (and (not (eobp))
5533 (invisible-p (point)))
5534 (goto-char (next-char-property-change (point))))
5535 ;; Have we advanced to a larger column position?
5536 (if (> (current-column) normal-column)
5537 ;; We have made some progress towards the desired column.
5538 ;; See if we can make any further progress.
5539 (line-move-to-column (+ (current-column) (- col normal-column)))
5540 ;; Otherwise, go to the place we originally found
5541 ;; and move back over invisible text.
5542 ;; that will get us to the same place on the screen
5543 ;; but with a more reasonable buffer position.
5544 (goto-char normal-location)
5545 (let ((line-beg (line-beginning-position)))
5546 (while (and (not (bolp)) (invisible-p (1- (point))))
5547 (goto-char (previous-char-property-change (point) line-beg))))))))
5549 (defun move-end-of-line (arg)
5550 "Move point to end of current line as displayed.
5551 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5552 If point reaches the beginning or end of buffer, it stops there.
5554 To ignore the effects of the `intangible' text or overlay
5555 property, bind `inhibit-point-motion-hooks' to t.
5556 If there is an image in the current line, this function
5557 disregards newlines that are part of the text on which the image
5558 rests."
5559 (interactive "^p")
5560 (or arg (setq arg 1))
5561 (let (done)
5562 (while (not done)
5563 (let ((newpos
5564 (save-excursion
5565 (let ((goal-column 0)
5566 (line-move-visual nil))
5567 (and (line-move arg t)
5568 ;; With bidi reordering, we may not be at bol,
5569 ;; so make sure we are.
5570 (skip-chars-backward "^\n")
5571 (not (bobp))
5572 (progn
5573 (while (and (not (bobp)) (invisible-p (1- (point))))
5574 (goto-char (previous-single-char-property-change
5575 (point) 'invisible)))
5576 (backward-char 1)))
5577 (point)))))
5578 (goto-char newpos)
5579 (if (and (> (point) newpos)
5580 (eq (preceding-char) ?\n))
5581 (backward-char 1)
5582 (if (and (> (point) newpos) (not (eobp))
5583 (not (eq (following-char) ?\n)))
5584 ;; If we skipped something intangible and now we're not
5585 ;; really at eol, keep going.
5586 (setq arg 1)
5587 (setq done t)))))))
5589 (defun move-beginning-of-line (arg)
5590 "Move point to beginning of current line as displayed.
5591 \(If there's an image in the line, this disregards newlines
5592 which are part of the text that the image rests on.)
5594 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5595 If point reaches the beginning or end of buffer, it stops there.
5596 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5597 (interactive "^p")
5598 (or arg (setq arg 1))
5600 (let ((orig (point))
5601 first-vis first-vis-field-value)
5603 ;; Move by lines, if ARG is not 1 (the default).
5604 (if (/= arg 1)
5605 (let ((line-move-visual nil))
5606 (line-move (1- arg) t)))
5608 ;; Move to beginning-of-line, ignoring fields and invisible text.
5609 (skip-chars-backward "^\n")
5610 (while (and (not (bobp)) (invisible-p (1- (point))))
5611 (goto-char (previous-char-property-change (point)))
5612 (skip-chars-backward "^\n"))
5614 ;; Now find first visible char in the line.
5615 (while (and (< (point) orig) (invisible-p (point)))
5616 (goto-char (next-char-property-change (point) orig)))
5617 (setq first-vis (point))
5619 ;; See if fields would stop us from reaching FIRST-VIS.
5620 (setq first-vis-field-value
5621 (constrain-to-field first-vis orig (/= arg 1) t nil))
5623 (goto-char (if (/= first-vis-field-value first-vis)
5624 ;; If yes, obey them.
5625 first-vis-field-value
5626 ;; Otherwise, move to START with attention to fields.
5627 ;; (It is possible that fields never matter in this case.)
5628 (constrain-to-field (point) orig
5629 (/= arg 1) t nil)))))
5632 ;; Many people have said they rarely use this feature, and often type
5633 ;; it by accident. Maybe it shouldn't even be on a key.
5634 (put 'set-goal-column 'disabled t)
5636 (defun set-goal-column (arg)
5637 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
5638 Those commands will move to this position in the line moved to
5639 rather than trying to keep the same horizontal position.
5640 With a non-nil argument ARG, clears out the goal column
5641 so that \\[next-line] and \\[previous-line] resume vertical motion.
5642 The goal column is stored in the variable `goal-column'."
5643 (interactive "P")
5644 (if arg
5645 (progn
5646 (setq goal-column nil)
5647 (message "No goal column"))
5648 (setq goal-column (current-column))
5649 ;; The older method below can be erroneous if `set-goal-column' is bound
5650 ;; to a sequence containing %
5651 ;;(message (substitute-command-keys
5652 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
5653 ;;goal-column)
5654 (message "%s"
5655 (concat
5656 (format "Goal column %d " goal-column)
5657 (substitute-command-keys
5658 "(use \\[set-goal-column] with an arg to unset it)")))
5661 nil)
5663 ;;; Editing based on visual lines, as opposed to logical lines.
5665 (defun end-of-visual-line (&optional n)
5666 "Move point to end of current visual line.
5667 With argument N not nil or 1, move forward N - 1 visual lines first.
5668 If point reaches the beginning or end of buffer, it stops there.
5669 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5670 (interactive "^p")
5671 (or n (setq n 1))
5672 (if (/= n 1)
5673 (let ((line-move-visual t))
5674 (line-move (1- n) t)))
5675 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
5676 ;; constrain to field boundaries, so we don't either.
5677 (vertical-motion (cons (window-width) 0)))
5679 (defun beginning-of-visual-line (&optional n)
5680 "Move point to beginning of current visual line.
5681 With argument N not nil or 1, move forward N - 1 visual lines first.
5682 If point reaches the beginning or end of buffer, it stops there.
5683 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
5684 (interactive "^p")
5685 (or n (setq n 1))
5686 (let ((opoint (point)))
5687 (if (/= n 1)
5688 (let ((line-move-visual t))
5689 (line-move (1- n) t)))
5690 (vertical-motion 0)
5691 ;; Constrain to field boundaries, like `move-beginning-of-line'.
5692 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
5694 (defun kill-visual-line (&optional arg)
5695 "Kill the rest of the visual line.
5696 With prefix argument ARG, kill that many visual lines from point.
5697 If ARG is negative, kill visual lines backward.
5698 If ARG is zero, kill the text before point on the current visual
5699 line.
5701 If you want to append the killed line to the last killed text,
5702 use \\[append-next-kill] before \\[kill-line].
5704 If the buffer is read-only, Emacs will beep and refrain from deleting
5705 the line, but put the line in the kill ring anyway. This means that
5706 you can use this command to copy text from a read-only buffer.
5707 \(If the variable `kill-read-only-ok' is non-nil, then this won't
5708 even beep.)"
5709 (interactive "P")
5710 ;; Like in `kill-line', it's better to move point to the other end
5711 ;; of the kill before killing.
5712 (let ((opoint (point))
5713 (kill-whole-line (and kill-whole-line (bolp))))
5714 (if arg
5715 (vertical-motion (prefix-numeric-value arg))
5716 (end-of-visual-line 1)
5717 (if (= (point) opoint)
5718 (vertical-motion 1)
5719 ;; Skip any trailing whitespace at the end of the visual line.
5720 ;; We used to do this only if `show-trailing-whitespace' is
5721 ;; nil, but that's wrong; the correct thing would be to check
5722 ;; whether the trailing whitespace is highlighted. But, it's
5723 ;; OK to just do this unconditionally.
5724 (skip-chars-forward " \t")))
5725 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
5726 (1+ (point))
5727 (point)))))
5729 (defun next-logical-line (&optional arg try-vscroll)
5730 "Move cursor vertically down ARG lines.
5731 This is identical to `next-line', except that it always moves
5732 by logical lines instead of visual lines, ignoring the value of
5733 the variable `line-move-visual'."
5734 (interactive "^p\np")
5735 (let ((line-move-visual nil))
5736 (with-no-warnings
5737 (next-line arg try-vscroll))))
5739 (defun previous-logical-line (&optional arg try-vscroll)
5740 "Move cursor vertically up ARG lines.
5741 This is identical to `previous-line', except that it always moves
5742 by logical lines instead of visual lines, ignoring the value of
5743 the variable `line-move-visual'."
5744 (interactive "^p\np")
5745 (let ((line-move-visual nil))
5746 (with-no-warnings
5747 (previous-line arg try-vscroll))))
5749 (defgroup visual-line nil
5750 "Editing based on visual lines."
5751 :group 'convenience
5752 :version "23.1")
5754 (defvar visual-line-mode-map
5755 (let ((map (make-sparse-keymap)))
5756 (define-key map [remap kill-line] 'kill-visual-line)
5757 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
5758 (define-key map [remap move-end-of-line] 'end-of-visual-line)
5759 ;; These keybindings interfere with xterm function keys. Are
5760 ;; there any other suitable bindings?
5761 ;; (define-key map "\M-[" 'previous-logical-line)
5762 ;; (define-key map "\M-]" 'next-logical-line)
5763 map))
5765 (defcustom visual-line-fringe-indicators '(nil nil)
5766 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
5767 The value should be a list of the form (LEFT RIGHT), where LEFT
5768 and RIGHT are symbols representing the bitmaps to display, to
5769 indicate wrapped lines, in the left and right fringes respectively.
5770 See also `fringe-indicator-alist'.
5771 The default is not to display fringe indicators for wrapped lines.
5772 This variable does not affect fringe indicators displayed for
5773 other purposes."
5774 :type '(list (choice (const :tag "Hide left indicator" nil)
5775 (const :tag "Left curly arrow" left-curly-arrow)
5776 (symbol :tag "Other bitmap"))
5777 (choice (const :tag "Hide right indicator" nil)
5778 (const :tag "Right curly arrow" right-curly-arrow)
5779 (symbol :tag "Other bitmap")))
5780 :set (lambda (symbol value)
5781 (dolist (buf (buffer-list))
5782 (with-current-buffer buf
5783 (when (and (boundp 'visual-line-mode)
5784 (symbol-value 'visual-line-mode))
5785 (setq fringe-indicator-alist
5786 (cons (cons 'continuation value)
5787 (assq-delete-all
5788 'continuation
5789 (copy-tree fringe-indicator-alist)))))))
5790 (set-default symbol value)))
5792 (defvar visual-line--saved-state nil)
5794 (define-minor-mode visual-line-mode
5795 "Toggle visual line based editing (Visual Line mode).
5796 With a prefix argument ARG, enable Visual Line mode if ARG is
5797 positive, and disable it otherwise. If called from Lisp, enable
5798 the mode if ARG is omitted or nil.
5800 When Visual Line mode is enabled, `word-wrap' is turned on in
5801 this buffer, and simple editing commands are redefined to act on
5802 visual lines, not logical lines. See Info node `Visual Line
5803 Mode' for details."
5804 :keymap visual-line-mode-map
5805 :group 'visual-line
5806 :lighter " Wrap"
5807 (if visual-line-mode
5808 (progn
5809 (set (make-local-variable 'visual-line--saved-state) nil)
5810 ;; Save the local values of some variables, to be restored if
5811 ;; visual-line-mode is turned off.
5812 (dolist (var '(line-move-visual truncate-lines
5813 truncate-partial-width-windows
5814 word-wrap fringe-indicator-alist))
5815 (if (local-variable-p var)
5816 (push (cons var (symbol-value var))
5817 visual-line--saved-state)))
5818 (set (make-local-variable 'line-move-visual) t)
5819 (set (make-local-variable 'truncate-partial-width-windows) nil)
5820 (setq truncate-lines nil
5821 word-wrap t
5822 fringe-indicator-alist
5823 (cons (cons 'continuation visual-line-fringe-indicators)
5824 fringe-indicator-alist)))
5825 (kill-local-variable 'line-move-visual)
5826 (kill-local-variable 'word-wrap)
5827 (kill-local-variable 'truncate-lines)
5828 (kill-local-variable 'truncate-partial-width-windows)
5829 (kill-local-variable 'fringe-indicator-alist)
5830 (dolist (saved visual-line--saved-state)
5831 (set (make-local-variable (car saved)) (cdr saved)))
5832 (kill-local-variable 'visual-line--saved-state)))
5834 (defun turn-on-visual-line-mode ()
5835 (visual-line-mode 1))
5837 (define-globalized-minor-mode global-visual-line-mode
5838 visual-line-mode turn-on-visual-line-mode)
5841 (defun transpose-chars (arg)
5842 "Interchange characters around point, moving forward one character.
5843 With prefix arg ARG, effect is to take character before point
5844 and drag it forward past ARG other characters (backward if ARG negative).
5845 If no argument and at end of line, the previous two chars are exchanged."
5846 (interactive "*P")
5847 (and (null arg) (eolp) (forward-char -1))
5848 (transpose-subr 'forward-char (prefix-numeric-value arg)))
5850 (defun transpose-words (arg)
5851 "Interchange words around point, leaving point at end of them.
5852 With prefix arg ARG, effect is to take word before or around point
5853 and drag it forward past ARG other words (backward if ARG negative).
5854 If ARG is zero, the words around or after point and around or after mark
5855 are interchanged."
5856 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
5857 (interactive "*p")
5858 (transpose-subr 'forward-word arg))
5860 (defun transpose-sexps (arg)
5861 "Like \\[transpose-words] but applies to sexps.
5862 Does not work on a sexp that point is in the middle of
5863 if it is a list or string."
5864 (interactive "*p")
5865 (transpose-subr
5866 (lambda (arg)
5867 ;; Here we should try to simulate the behavior of
5868 ;; (cons (progn (forward-sexp x) (point))
5869 ;; (progn (forward-sexp (- x)) (point)))
5870 ;; Except that we don't want to rely on the second forward-sexp
5871 ;; putting us back to where we want to be, since forward-sexp-function
5872 ;; might do funny things like infix-precedence.
5873 (if (if (> arg 0)
5874 (looking-at "\\sw\\|\\s_")
5875 (and (not (bobp))
5876 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
5877 ;; Jumping over a symbol. We might be inside it, mind you.
5878 (progn (funcall (if (> arg 0)
5879 'skip-syntax-backward 'skip-syntax-forward)
5880 "w_")
5881 (cons (save-excursion (forward-sexp arg) (point)) (point)))
5882 ;; Otherwise, we're between sexps. Take a step back before jumping
5883 ;; to make sure we'll obey the same precedence no matter which direction
5884 ;; we're going.
5885 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
5886 (cons (save-excursion (forward-sexp arg) (point))
5887 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
5888 (not (zerop (funcall (if (> arg 0)
5889 'skip-syntax-forward
5890 'skip-syntax-backward)
5891 ".")))))
5892 (point)))))
5893 arg 'special))
5895 (defun transpose-lines (arg)
5896 "Exchange current line and previous line, leaving point after both.
5897 With argument ARG, takes previous line and moves it past ARG lines.
5898 With argument 0, interchanges line point is in with line mark is in."
5899 (interactive "*p")
5900 (transpose-subr (function
5901 (lambda (arg)
5902 (if (> arg 0)
5903 (progn
5904 ;; Move forward over ARG lines,
5905 ;; but create newlines if necessary.
5906 (setq arg (forward-line arg))
5907 (if (/= (preceding-char) ?\n)
5908 (setq arg (1+ arg)))
5909 (if (> arg 0)
5910 (newline arg)))
5911 (forward-line arg))))
5912 arg))
5914 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
5915 ;; which seems inconsistent with the ARG /= 0 case.
5916 ;; FIXME document SPECIAL.
5917 (defun transpose-subr (mover arg &optional special)
5918 "Subroutine to do the work of transposing objects.
5919 Works for lines, sentences, paragraphs, etc. MOVER is a function that
5920 moves forward by units of the given object (e.g. forward-sentence,
5921 forward-paragraph). If ARG is zero, exchanges the current object
5922 with the one containing mark. If ARG is an integer, moves the
5923 current object past ARG following (if ARG is positive) or
5924 preceding (if ARG is negative) objects, leaving point after the
5925 current object."
5926 (let ((aux (if special mover
5927 (lambda (x)
5928 (cons (progn (funcall mover x) (point))
5929 (progn (funcall mover (- x)) (point))))))
5930 pos1 pos2)
5931 (cond
5932 ((= arg 0)
5933 (save-excursion
5934 (setq pos1 (funcall aux 1))
5935 (goto-char (or (mark) (error "No mark set in this buffer")))
5936 (setq pos2 (funcall aux 1))
5937 (transpose-subr-1 pos1 pos2))
5938 (exchange-point-and-mark))
5939 ((> arg 0)
5940 (setq pos1 (funcall aux -1))
5941 (setq pos2 (funcall aux arg))
5942 (transpose-subr-1 pos1 pos2)
5943 (goto-char (car pos2)))
5945 (setq pos1 (funcall aux -1))
5946 (goto-char (car pos1))
5947 (setq pos2 (funcall aux arg))
5948 (transpose-subr-1 pos1 pos2)))))
5950 (defun transpose-subr-1 (pos1 pos2)
5951 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
5952 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
5953 (when (> (car pos1) (car pos2))
5954 (let ((swap pos1))
5955 (setq pos1 pos2 pos2 swap)))
5956 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
5957 (atomic-change-group
5958 ;; This sequence of insertions attempts to preserve marker
5959 ;; positions at the start and end of the transposed objects.
5960 (let* ((word (buffer-substring (car pos2) (cdr pos2)))
5961 (len1 (- (cdr pos1) (car pos1)))
5962 (len2 (length word))
5963 (boundary (make-marker)))
5964 (set-marker boundary (car pos2))
5965 (goto-char (cdr pos1))
5966 (insert-before-markers word)
5967 (setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
5968 (goto-char boundary)
5969 (insert word)
5970 (goto-char (+ boundary len1))
5971 (delete-region (point) (+ (point) len2))
5972 (set-marker boundary nil))))
5974 (defun backward-word (&optional arg)
5975 "Move backward until encountering the beginning of a word.
5976 With argument ARG, do this that many times.
5977 If ARG is omitted or nil, move point backward one word."
5978 (interactive "^p")
5979 (forward-word (- (or arg 1))))
5981 (defun mark-word (&optional arg allow-extend)
5982 "Set mark ARG words away from point.
5983 The place mark goes is the same place \\[forward-word] would
5984 move to with the same argument.
5985 Interactively, if this command is repeated
5986 or (in Transient Mark mode) if the mark is active,
5987 it marks the next ARG words after the ones already marked."
5988 (interactive "P\np")
5989 (cond ((and allow-extend
5990 (or (and (eq last-command this-command) (mark t))
5991 (region-active-p)))
5992 (setq arg (if arg (prefix-numeric-value arg)
5993 (if (< (mark) (point)) -1 1)))
5994 (set-mark
5995 (save-excursion
5996 (goto-char (mark))
5997 (forward-word arg)
5998 (point))))
6000 (push-mark
6001 (save-excursion
6002 (forward-word (prefix-numeric-value arg))
6003 (point))
6004 nil t))))
6006 (defun kill-word (arg)
6007 "Kill characters forward until encountering the end of a word.
6008 With argument ARG, do this that many times."
6009 (interactive "p")
6010 (kill-region (point) (progn (forward-word arg) (point))))
6012 (defun backward-kill-word (arg)
6013 "Kill characters backward until encountering the beginning of a word.
6014 With argument ARG, do this that many times."
6015 (interactive "p")
6016 (kill-word (- arg)))
6018 (defun current-word (&optional strict really-word)
6019 "Return the symbol or word that point is on (or a nearby one) as a string.
6020 The return value includes no text properties.
6021 If optional arg STRICT is non-nil, return nil unless point is within
6022 or adjacent to a symbol or word. In all cases the value can be nil
6023 if there is no word nearby.
6024 The function, belying its name, normally finds a symbol.
6025 If optional arg REALLY-WORD is non-nil, it finds just a word."
6026 (save-excursion
6027 (let* ((oldpoint (point)) (start (point)) (end (point))
6028 (syntaxes (if really-word "w" "w_"))
6029 (not-syntaxes (concat "^" syntaxes)))
6030 (skip-syntax-backward syntaxes) (setq start (point))
6031 (goto-char oldpoint)
6032 (skip-syntax-forward syntaxes) (setq end (point))
6033 (when (and (eq start oldpoint) (eq end oldpoint)
6034 ;; Point is neither within nor adjacent to a word.
6035 (not strict))
6036 ;; Look for preceding word in same line.
6037 (skip-syntax-backward not-syntaxes (line-beginning-position))
6038 (if (bolp)
6039 ;; No preceding word in same line.
6040 ;; Look for following word in same line.
6041 (progn
6042 (skip-syntax-forward not-syntaxes (line-end-position))
6043 (setq start (point))
6044 (skip-syntax-forward syntaxes)
6045 (setq end (point)))
6046 (setq end (point))
6047 (skip-syntax-backward syntaxes)
6048 (setq start (point))))
6049 ;; If we found something nonempty, return it as a string.
6050 (unless (= start end)
6051 (buffer-substring-no-properties start end)))))
6053 (defcustom fill-prefix nil
6054 "String for filling to insert at front of new line, or nil for none."
6055 :type '(choice (const :tag "None" nil)
6056 string)
6057 :group 'fill)
6058 (make-variable-buffer-local 'fill-prefix)
6059 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
6061 (defcustom auto-fill-inhibit-regexp nil
6062 "Regexp to match lines which should not be auto-filled."
6063 :type '(choice (const :tag "None" nil)
6064 regexp)
6065 :group 'fill)
6067 (defun do-auto-fill ()
6068 "The default value for `normal-auto-fill-function'.
6069 This is the default auto-fill function, some major modes use a different one.
6070 Returns t if it really did any work."
6071 (let (fc justify give-up
6072 (fill-prefix fill-prefix))
6073 (if (or (not (setq justify (current-justification)))
6074 (null (setq fc (current-fill-column)))
6075 (and (eq justify 'left)
6076 (<= (current-column) fc))
6077 (and auto-fill-inhibit-regexp
6078 (save-excursion (beginning-of-line)
6079 (looking-at auto-fill-inhibit-regexp))))
6080 nil ;; Auto-filling not required
6081 (if (memq justify '(full center right))
6082 (save-excursion (unjustify-current-line)))
6084 ;; Choose a fill-prefix automatically.
6085 (when (and adaptive-fill-mode
6086 (or (null fill-prefix) (string= fill-prefix "")))
6087 (let ((prefix
6088 (fill-context-prefix
6089 (save-excursion (fill-forward-paragraph -1) (point))
6090 (save-excursion (fill-forward-paragraph 1) (point)))))
6091 (and prefix (not (equal prefix ""))
6092 ;; Use auto-indentation rather than a guessed empty prefix.
6093 (not (and fill-indent-according-to-mode
6094 (string-match "\\`[ \t]*\\'" prefix)))
6095 (setq fill-prefix prefix))))
6097 (while (and (not give-up) (> (current-column) fc))
6098 ;; Determine where to split the line.
6099 (let* (after-prefix
6100 (fill-point
6101 (save-excursion
6102 (beginning-of-line)
6103 (setq after-prefix (point))
6104 (and fill-prefix
6105 (looking-at (regexp-quote fill-prefix))
6106 (setq after-prefix (match-end 0)))
6107 (move-to-column (1+ fc))
6108 (fill-move-to-break-point after-prefix)
6109 (point))))
6111 ;; See whether the place we found is any good.
6112 (if (save-excursion
6113 (goto-char fill-point)
6114 (or (bolp)
6115 ;; There is no use breaking at end of line.
6116 (save-excursion (skip-chars-forward " ") (eolp))
6117 ;; It is futile to split at the end of the prefix
6118 ;; since we would just insert the prefix again.
6119 (and after-prefix (<= (point) after-prefix))
6120 ;; Don't split right after a comment starter
6121 ;; since we would just make another comment starter.
6122 (and comment-start-skip
6123 (let ((limit (point)))
6124 (beginning-of-line)
6125 (and (re-search-forward comment-start-skip
6126 limit t)
6127 (eq (point) limit))))))
6128 ;; No good place to break => stop trying.
6129 (setq give-up t)
6130 ;; Ok, we have a useful place to break the line. Do it.
6131 (let ((prev-column (current-column)))
6132 ;; If point is at the fill-point, do not `save-excursion'.
6133 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
6134 ;; point will end up before it rather than after it.
6135 (if (save-excursion
6136 (skip-chars-backward " \t")
6137 (= (point) fill-point))
6138 (default-indent-new-line t)
6139 (save-excursion
6140 (goto-char fill-point)
6141 (default-indent-new-line t)))
6142 ;; Now do justification, if required
6143 (if (not (eq justify 'left))
6144 (save-excursion
6145 (end-of-line 0)
6146 (justify-current-line justify nil t)))
6147 ;; If making the new line didn't reduce the hpos of
6148 ;; the end of the line, then give up now;
6149 ;; trying again will not help.
6150 (if (>= (current-column) prev-column)
6151 (setq give-up t))))))
6152 ;; Justify last line.
6153 (justify-current-line justify t t)
6154 t)))
6156 (defvar comment-line-break-function 'comment-indent-new-line
6157 "Mode-specific function which line breaks and continues a comment.
6158 This function is called during auto-filling when a comment syntax
6159 is defined.
6160 The function should take a single optional argument, which is a flag
6161 indicating whether it should use soft newlines.")
6163 (defun default-indent-new-line (&optional soft)
6164 "Break line at point and indent.
6165 If a comment syntax is defined, call `comment-indent-new-line'.
6167 The inserted newline is marked hard if variable `use-hard-newlines' is true,
6168 unless optional argument SOFT is non-nil."
6169 (interactive)
6170 (if comment-start
6171 (funcall comment-line-break-function soft)
6172 ;; Insert the newline before removing empty space so that markers
6173 ;; get preserved better.
6174 (if soft (insert-and-inherit ?\n) (newline 1))
6175 (save-excursion (forward-char -1) (delete-horizontal-space))
6176 (delete-horizontal-space)
6178 (if (and fill-prefix (not adaptive-fill-mode))
6179 ;; Blindly trust a non-adaptive fill-prefix.
6180 (progn
6181 (indent-to-left-margin)
6182 (insert-before-markers-and-inherit fill-prefix))
6184 (cond
6185 ;; If there's an adaptive prefix, use it unless we're inside
6186 ;; a comment and the prefix is not a comment starter.
6187 (fill-prefix
6188 (indent-to-left-margin)
6189 (insert-and-inherit fill-prefix))
6190 ;; If we're not inside a comment, just try to indent.
6191 (t (indent-according-to-mode))))))
6193 (defvar normal-auto-fill-function 'do-auto-fill
6194 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
6195 Some major modes set this.")
6197 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
6198 ;; `functions' and `hooks' are usually unsafe to set, but setting
6199 ;; auto-fill-function to nil in a file-local setting is safe and
6200 ;; can be useful to prevent auto-filling.
6201 (put 'auto-fill-function 'safe-local-variable 'null)
6203 (define-minor-mode auto-fill-mode
6204 "Toggle automatic line breaking (Auto Fill mode).
6205 With a prefix argument ARG, enable Auto Fill mode if ARG is
6206 positive, and disable it otherwise. If called from Lisp, enable
6207 the mode if ARG is omitted or nil.
6209 When Auto Fill mode is enabled, inserting a space at a column
6210 beyond `current-fill-column' automatically breaks the line at a
6211 previous space.
6213 When `auto-fill-mode' is on, the `auto-fill-function' variable is
6214 non-`nil'.
6216 The value of `normal-auto-fill-function' specifies the function to use
6217 for `auto-fill-function' when turning Auto Fill mode on."
6218 :variable (auto-fill-function
6219 . (lambda (v) (setq auto-fill-function
6220 (if v normal-auto-fill-function)))))
6222 ;; This holds a document string used to document auto-fill-mode.
6223 (defun auto-fill-function ()
6224 "Automatically break line at a previous space, in insertion of text."
6225 nil)
6227 (defun turn-on-auto-fill ()
6228 "Unconditionally turn on Auto Fill mode."
6229 (auto-fill-mode 1))
6231 (defun turn-off-auto-fill ()
6232 "Unconditionally turn off Auto Fill mode."
6233 (auto-fill-mode -1))
6235 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
6237 (defun set-fill-column (arg)
6238 "Set `fill-column' to specified argument.
6239 Use \\[universal-argument] followed by a number to specify a column.
6240 Just \\[universal-argument] as argument means to use the current column."
6241 (interactive
6242 (list (or current-prefix-arg
6243 ;; We used to use current-column silently, but C-x f is too easily
6244 ;; typed as a typo for C-x C-f, so we turned it into an error and
6245 ;; now an interactive prompt.
6246 (read-number "Set fill-column to: " (current-column)))))
6247 (if (consp arg)
6248 (setq arg (current-column)))
6249 (if (not (integerp arg))
6250 ;; Disallow missing argument; it's probably a typo for C-x C-f.
6251 (error "set-fill-column requires an explicit argument")
6252 (message "Fill column set to %d (was %d)" arg fill-column)
6253 (setq fill-column arg)))
6255 (defun set-selective-display (arg)
6256 "Set `selective-display' to ARG; clear it if no arg.
6257 When the value of `selective-display' is a number > 0,
6258 lines whose indentation is >= that value are not displayed.
6259 The variable `selective-display' has a separate value for each buffer."
6260 (interactive "P")
6261 (if (eq selective-display t)
6262 (error "selective-display already in use for marked lines"))
6263 (let ((current-vpos
6264 (save-restriction
6265 (narrow-to-region (point-min) (point))
6266 (goto-char (window-start))
6267 (vertical-motion (window-height)))))
6268 (setq selective-display
6269 (and arg (prefix-numeric-value arg)))
6270 (recenter current-vpos))
6271 (set-window-start (selected-window) (window-start))
6272 (princ "selective-display set to " t)
6273 (prin1 selective-display t)
6274 (princ "." t))
6276 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
6278 (defun toggle-truncate-lines (&optional arg)
6279 "Toggle truncating of long lines for the current buffer.
6280 When truncating is off, long lines are folded.
6281 With prefix argument ARG, truncate long lines if ARG is positive,
6282 otherwise fold them. Note that in side-by-side windows, this
6283 command has no effect if `truncate-partial-width-windows' is
6284 non-nil."
6285 (interactive "P")
6286 (setq truncate-lines
6287 (if (null arg)
6288 (not truncate-lines)
6289 (> (prefix-numeric-value arg) 0)))
6290 (force-mode-line-update)
6291 (unless truncate-lines
6292 (let ((buffer (current-buffer)))
6293 (walk-windows (lambda (window)
6294 (if (eq buffer (window-buffer window))
6295 (set-window-hscroll window 0)))
6296 nil t)))
6297 (message "Truncate long lines %s"
6298 (if truncate-lines "enabled" "disabled")))
6300 (defun toggle-word-wrap (&optional arg)
6301 "Toggle whether to use word-wrapping for continuation lines.
6302 With prefix argument ARG, wrap continuation lines at word boundaries
6303 if ARG is positive, otherwise wrap them at the right screen edge.
6304 This command toggles the value of `word-wrap'. It has no effect
6305 if long lines are truncated."
6306 (interactive "P")
6307 (setq word-wrap
6308 (if (null arg)
6309 (not word-wrap)
6310 (> (prefix-numeric-value arg) 0)))
6311 (force-mode-line-update)
6312 (message "Word wrapping %s"
6313 (if word-wrap "enabled" "disabled")))
6315 (defvar overwrite-mode-textual (purecopy " Ovwrt")
6316 "The string displayed in the mode line when in overwrite mode.")
6317 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
6318 "The string displayed in the mode line when in binary overwrite mode.")
6320 (define-minor-mode overwrite-mode
6321 "Toggle Overwrite mode.
6322 With a prefix argument ARG, enable Overwrite mode if ARG is
6323 positive, and disable it otherwise. If called from Lisp, enable
6324 the mode if ARG is omitted or nil.
6326 When Overwrite mode is enabled, printing characters typed in
6327 replace existing text on a one-for-one basis, rather than pushing
6328 it to the right. At the end of a line, such characters extend
6329 the line. Before a tab, such characters insert until the tab is
6330 filled in. \\[quoted-insert] still inserts characters in
6331 overwrite mode; this is supposed to make it easier to insert
6332 characters when necessary."
6333 :variable (overwrite-mode
6334 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-textual)))))
6336 (define-minor-mode binary-overwrite-mode
6337 "Toggle Binary Overwrite mode.
6338 With a prefix argument ARG, enable Binary Overwrite mode if ARG
6339 is positive, and disable it otherwise. If called from Lisp,
6340 enable the mode if ARG is omitted or nil.
6342 When Binary Overwrite mode is enabled, printing characters typed
6343 in replace existing text. Newlines are not treated specially, so
6344 typing at the end of a line joins the line to the next, with the
6345 typed character between them. Typing before a tab character
6346 simply replaces the tab with the character typed.
6347 \\[quoted-insert] replaces the text at the cursor, just as
6348 ordinary typing characters do.
6350 Note that Binary Overwrite mode is not its own minor mode; it is
6351 a specialization of overwrite mode, entered by setting the
6352 `overwrite-mode' variable to `overwrite-mode-binary'."
6353 :variable (overwrite-mode
6354 . (lambda (v) (setq overwrite-mode (if v 'overwrite-mode-binary)))))
6356 (define-minor-mode line-number-mode
6357 "Toggle line number display in the mode line (Line Number mode).
6358 With a prefix argument ARG, enable Line Number mode if ARG is
6359 positive, and disable it otherwise. If called from Lisp, enable
6360 the mode if ARG is omitted or nil.
6362 Line numbers do not appear for very large buffers and buffers
6363 with very long lines; see variables `line-number-display-limit'
6364 and `line-number-display-limit-width'."
6365 :init-value t :global t :group 'mode-line)
6367 (define-minor-mode column-number-mode
6368 "Toggle column number display in the mode line (Column Number mode).
6369 With a prefix argument ARG, enable Column Number mode if ARG is
6370 positive, and disable it otherwise.
6372 If called from Lisp, enable the mode if ARG is omitted or nil."
6373 :global t :group 'mode-line)
6375 (define-minor-mode size-indication-mode
6376 "Toggle buffer size display in the mode line (Size Indication mode).
6377 With a prefix argument ARG, enable Size Indication mode if ARG is
6378 positive, and disable it otherwise.
6380 If called from Lisp, enable the mode if ARG is omitted or nil."
6381 :global t :group 'mode-line)
6383 (define-minor-mode auto-save-mode
6384 "Toggle auto-saving in the current buffer (Auto Save mode).
6385 With a prefix argument ARG, enable Auto Save mode if ARG is
6386 positive, and disable it otherwise.
6388 If called from Lisp, enable the mode if ARG is omitted or nil."
6389 :variable ((and buffer-auto-save-file-name
6390 ;; If auto-save is off because buffer has shrunk,
6391 ;; then toggling should turn it on.
6392 (>= buffer-saved-size 0))
6393 . (lambda (val)
6394 (setq buffer-auto-save-file-name
6395 (cond
6396 ((null val) nil)
6397 ((and buffer-file-name auto-save-visited-file-name
6398 (not buffer-read-only))
6399 buffer-file-name)
6400 (t (make-auto-save-file-name))))))
6401 ;; If -1 was stored here, to temporarily turn off saving,
6402 ;; turn it back on.
6403 (and (< buffer-saved-size 0)
6404 (setq buffer-saved-size 0)))
6406 (defgroup paren-blinking nil
6407 "Blinking matching of parens and expressions."
6408 :prefix "blink-matching-"
6409 :group 'paren-matching)
6411 (defcustom blink-matching-paren t
6412 "Non-nil means show matching open-paren when close-paren is inserted.
6413 If t, highlight the paren. If `jump', move cursor to its position."
6414 :type '(choice
6415 (const :tag "Disable" nil)
6416 (const :tag "Highlight" t)
6417 (const :tag "Move cursor" jump))
6418 :group 'paren-blinking)
6420 (defcustom blink-matching-paren-on-screen t
6421 "Non-nil means show matching open-paren when it is on screen.
6422 If nil, don't show it (but the open-paren can still be shown
6423 when it is off screen).
6425 This variable has no effect if `blink-matching-paren' is nil.
6426 \(In that case, the open-paren is never shown.)
6427 It is also ignored if `show-paren-mode' is enabled."
6428 :type 'boolean
6429 :group 'paren-blinking)
6431 (defcustom blink-matching-paren-distance (* 100 1024)
6432 "If non-nil, maximum distance to search backwards for matching open-paren.
6433 If nil, search stops at the beginning of the accessible portion of the buffer."
6434 :version "23.2" ; 25->100k
6435 :type '(choice (const nil) integer)
6436 :group 'paren-blinking)
6438 (defcustom blink-matching-delay 1
6439 "Time in seconds to delay after showing a matching paren."
6440 :type 'number
6441 :group 'paren-blinking)
6443 (defcustom blink-matching-paren-dont-ignore-comments nil
6444 "If nil, `blink-matching-paren' ignores comments.
6445 More precisely, when looking for the matching parenthesis,
6446 it skips the contents of comments that end before point."
6447 :type 'boolean
6448 :group 'paren-blinking)
6450 (defun blink-matching-check-mismatch (start end)
6451 "Return whether or not START...END are matching parens.
6452 END is the current point and START is the blink position.
6453 START might be nil if no matching starter was found.
6454 Returns non-nil if we find there is a mismatch."
6455 (let* ((end-syntax (syntax-after (1- end)))
6456 (matching-paren (and (consp end-syntax)
6457 (eq (syntax-class end-syntax) 5)
6458 (cdr end-syntax))))
6459 ;; For self-matched chars like " and $, we can't know when they're
6460 ;; mismatched or unmatched, so we can only do it for parens.
6461 (when matching-paren
6462 (not (and start
6464 (eq (char-after start) matching-paren)
6465 ;; The cdr might hold a new paren-class info rather than
6466 ;; a matching-char info, in which case the two CDRs
6467 ;; should match.
6468 (eq matching-paren (cdr-safe (syntax-after start)))))))))
6470 (defvar blink-matching-check-function #'blink-matching-check-mismatch
6471 "Function to check parentheses mismatches.
6472 The function takes two arguments (START and END) where START is the
6473 position just before the opening token and END is the position right after.
6474 START can be nil, if it was not found.
6475 The function should return non-nil if the two tokens do not match.")
6477 (defvar blink-matching--overlay
6478 (let ((ol (make-overlay (point) (point) nil t)))
6479 (overlay-put ol 'face 'show-paren-match)
6480 (delete-overlay ol)
6482 "Overlay used to highlight the matching paren.")
6484 (defun blink-matching-open ()
6485 "Momentarily highlight the beginning of the sexp before point."
6486 (interactive)
6487 (when (and (not (bobp))
6488 blink-matching-paren)
6489 (let* ((oldpos (point))
6490 (message-log-max nil) ; Don't log messages about paren matching.
6491 (blinkpos
6492 (save-excursion
6493 (save-restriction
6494 (if blink-matching-paren-distance
6495 (narrow-to-region
6496 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
6497 (- (point) blink-matching-paren-distance))
6498 oldpos))
6499 (let ((parse-sexp-ignore-comments
6500 (and parse-sexp-ignore-comments
6501 (not blink-matching-paren-dont-ignore-comments))))
6502 (condition-case ()
6503 (progn
6504 (forward-sexp -1)
6505 ;; backward-sexp skips backward over prefix chars,
6506 ;; so move back to the matching paren.
6507 (while (and (< (point) (1- oldpos))
6508 (let ((code (syntax-after (point))))
6509 (or (eq (syntax-class code) 6)
6510 (eq (logand 1048576 (car code))
6511 1048576))))
6512 (forward-char 1))
6513 (point))
6514 (error nil))))))
6515 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
6516 (cond
6517 (mismatch
6518 (if blinkpos
6519 (if (minibufferp)
6520 (minibuffer-message "Mismatched parentheses")
6521 (message "Mismatched parentheses"))
6522 (if (minibufferp)
6523 (minibuffer-message "No matching parenthesis found")
6524 (message "No matching parenthesis found"))))
6525 ((not blinkpos) nil)
6526 ((pos-visible-in-window-p blinkpos)
6527 ;; Matching open within window, temporarily move to or highlight
6528 ;; char after blinkpos but only if `blink-matching-paren-on-screen'
6529 ;; is non-nil.
6530 (and blink-matching-paren-on-screen
6531 (not show-paren-mode)
6532 (if (eq blink-matching-paren 'jump)
6533 (save-excursion
6534 (goto-char blinkpos)
6535 (sit-for blink-matching-delay))
6536 (unwind-protect
6537 (progn
6538 (move-overlay blink-matching--overlay blinkpos (1+ blinkpos)
6539 (current-buffer))
6540 (sit-for blink-matching-delay))
6541 (delete-overlay blink-matching--overlay)))))
6543 (save-excursion
6544 (goto-char blinkpos)
6545 (let ((open-paren-line-string
6546 ;; Show what precedes the open in its line, if anything.
6547 (cond
6548 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
6549 (buffer-substring (line-beginning-position)
6550 (1+ blinkpos)))
6551 ;; Show what follows the open in its line, if anything.
6552 ((save-excursion
6553 (forward-char 1)
6554 (skip-chars-forward " \t")
6555 (not (eolp)))
6556 (buffer-substring blinkpos
6557 (line-end-position)))
6558 ;; Otherwise show the previous nonblank line,
6559 ;; if there is one.
6560 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
6561 (concat
6562 (buffer-substring (progn
6563 (skip-chars-backward "\n \t")
6564 (line-beginning-position))
6565 (progn (end-of-line)
6566 (skip-chars-backward " \t")
6567 (point)))
6568 ;; Replace the newline and other whitespace with `...'.
6569 "..."
6570 (buffer-substring blinkpos (1+ blinkpos))))
6571 ;; There is nothing to show except the char itself.
6572 (t (buffer-substring blinkpos (1+ blinkpos))))))
6573 (message "Matches %s"
6574 (substring-no-properties open-paren-line-string)))))))))
6576 (defvar blink-paren-function 'blink-matching-open
6577 "Function called, if non-nil, whenever a close parenthesis is inserted.
6578 More precisely, a char with closeparen syntax is self-inserted.")
6580 (defun blink-paren-post-self-insert-function ()
6581 (when (and (eq (char-before) last-command-event) ; Sanity check.
6582 (memq (char-syntax last-command-event) '(?\) ?\$))
6583 blink-paren-function
6584 (not executing-kbd-macro)
6585 (not noninteractive)
6586 ;; Verify an even number of quoting characters precede the close.
6587 (= 1 (logand 1 (- (point)
6588 (save-excursion
6589 (forward-char -1)
6590 (skip-syntax-backward "/\\")
6591 (point))))))
6592 (funcall blink-paren-function)))
6594 (put 'blink-paren-post-self-insert-function 'priority 100)
6596 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
6597 ;; Most likely, this hook is nil, so this arg doesn't matter,
6598 ;; but I use it as a reminder that this function usually
6599 ;; likes to be run after others since it does
6600 ;; `sit-for'. That's also the reason it get a `priority' prop
6601 ;; of 100.
6602 'append)
6604 ;; This executes C-g typed while Emacs is waiting for a command.
6605 ;; Quitting out of a program does not go through here;
6606 ;; that happens in the QUIT macro at the C code level.
6607 (defun keyboard-quit ()
6608 "Signal a `quit' condition.
6609 During execution of Lisp code, this character causes a quit directly.
6610 At top-level, as an editor command, this simply beeps."
6611 (interactive)
6612 ;; Avoid adding the region to the window selection.
6613 (setq saved-region-selection nil)
6614 (let (select-active-regions)
6615 (deactivate-mark))
6616 (if (fboundp 'kmacro-keyboard-quit)
6617 (kmacro-keyboard-quit))
6618 ;; Force the next redisplay cycle to remove the "Def" indicator from
6619 ;; all the mode lines.
6620 (if defining-kbd-macro
6621 (force-mode-line-update t))
6622 (setq defining-kbd-macro nil)
6623 (let ((debug-on-quit nil))
6624 (signal 'quit nil)))
6626 (defvar buffer-quit-function nil
6627 "Function to call to \"quit\" the current buffer, or nil if none.
6628 \\[keyboard-escape-quit] calls this function when its more local actions
6629 \(such as canceling a prefix argument, minibuffer or region) do not apply.")
6631 (defun keyboard-escape-quit ()
6632 "Exit the current \"mode\" (in a generalized sense of the word).
6633 This command can exit an interactive command such as `query-replace',
6634 can clear out a prefix argument or a region,
6635 can get out of the minibuffer or other recursive edit,
6636 cancel the use of the current buffer (for special-purpose buffers),
6637 or go back to just one window (by deleting all but the selected window)."
6638 (interactive)
6639 (cond ((eq last-command 'mode-exited) nil)
6640 ((region-active-p)
6641 (deactivate-mark))
6642 ((> (minibuffer-depth) 0)
6643 (abort-recursive-edit))
6644 (current-prefix-arg
6645 nil)
6646 ((> (recursion-depth) 0)
6647 (exit-recursive-edit))
6648 (buffer-quit-function
6649 (funcall buffer-quit-function))
6650 ((not (one-window-p t))
6651 (delete-other-windows))
6652 ((string-match "^ \\*" (buffer-name (current-buffer)))
6653 (bury-buffer))))
6655 (defun play-sound-file (file &optional volume device)
6656 "Play sound stored in FILE.
6657 VOLUME and DEVICE correspond to the keywords of the sound
6658 specification for `play-sound'."
6659 (interactive "fPlay sound file: ")
6660 (let ((sound (list :file file)))
6661 (if volume
6662 (plist-put sound :volume volume))
6663 (if device
6664 (plist-put sound :device device))
6665 (push 'sound sound)
6666 (play-sound sound)))
6669 (defcustom read-mail-command 'rmail
6670 "Your preference for a mail reading package.
6671 This is used by some keybindings which support reading mail.
6672 See also `mail-user-agent' concerning sending mail."
6673 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
6674 (function-item :tag "Gnus" :format "%t\n" gnus)
6675 (function-item :tag "Emacs interface to MH"
6676 :format "%t\n" mh-rmail)
6677 (function :tag "Other"))
6678 :version "21.1"
6679 :group 'mail)
6681 (defcustom mail-user-agent 'message-user-agent
6682 "Your preference for a mail composition package.
6683 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
6684 outgoing email message. This variable lets you specify which
6685 mail-sending package you prefer.
6687 Valid values include:
6689 `message-user-agent' -- use the Message package.
6690 See Info node `(message)'.
6691 `sendmail-user-agent' -- use the Mail package.
6692 See Info node `(emacs)Sending Mail'.
6693 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
6694 See Info node `(mh-e)'.
6695 `gnus-user-agent' -- like `message-user-agent', but with Gnus
6696 paraphernalia if Gnus is running, particularly
6697 the Gcc: header for archiving.
6699 Additional valid symbols may be available; check with the author of
6700 your package for details. The function should return non-nil if it
6701 succeeds.
6703 See also `read-mail-command' concerning reading mail."
6704 :type '(radio (function-item :tag "Message package"
6705 :format "%t\n"
6706 message-user-agent)
6707 (function-item :tag "Mail package"
6708 :format "%t\n"
6709 sendmail-user-agent)
6710 (function-item :tag "Emacs interface to MH"
6711 :format "%t\n"
6712 mh-e-user-agent)
6713 (function-item :tag "Message with full Gnus features"
6714 :format "%t\n"
6715 gnus-user-agent)
6716 (function :tag "Other"))
6717 :version "23.2" ; sendmail->message
6718 :group 'mail)
6720 (defcustom compose-mail-user-agent-warnings t
6721 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
6722 If the value of `mail-user-agent' is the default, and the user
6723 appears to have customizations applying to the old default,
6724 `compose-mail' issues a warning."
6725 :type 'boolean
6726 :version "23.2"
6727 :group 'mail)
6729 (defun rfc822-goto-eoh ()
6730 "If the buffer starts with a mail header, move point to the header's end.
6731 Otherwise, moves to `point-min'.
6732 The end of the header is the start of the next line, if there is one,
6733 else the end of the last line. This function obeys RFC822."
6734 (goto-char (point-min))
6735 (when (re-search-forward
6736 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
6737 (goto-char (match-beginning 0))))
6739 ;; Used by Rmail (e.g., rmail-forward).
6740 (defvar mail-encode-mml nil
6741 "If non-nil, mail-user-agent's `sendfunc' command should mml-encode
6742 the outgoing message before sending it.")
6744 (defun compose-mail (&optional to subject other-headers continue
6745 switch-function yank-action send-actions
6746 return-action)
6747 "Start composing a mail message to send.
6748 This uses the user's chosen mail composition package
6749 as selected with the variable `mail-user-agent'.
6750 The optional arguments TO and SUBJECT specify recipients
6751 and the initial Subject field, respectively.
6753 OTHER-HEADERS is an alist specifying additional
6754 header fields. Elements look like (HEADER . VALUE) where both
6755 HEADER and VALUE are strings.
6757 CONTINUE, if non-nil, says to continue editing a message already
6758 being composed. Interactively, CONTINUE is the prefix argument.
6760 SWITCH-FUNCTION, if non-nil, is a function to use to
6761 switch to and display the buffer used for mail composition.
6763 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
6764 to insert the raw text of the message being replied to.
6765 It has the form (FUNCTION . ARGS). The user agent will apply
6766 FUNCTION to ARGS, to insert the raw text of the original message.
6767 \(The user agent will also run `mail-citation-hook', *after* the
6768 original text has been inserted in this way.)
6770 SEND-ACTIONS is a list of actions to call when the message is sent.
6771 Each action has the form (FUNCTION . ARGS).
6773 RETURN-ACTION, if non-nil, is an action for returning to the
6774 caller. It has the form (FUNCTION . ARGS). The function is
6775 called after the mail has been sent or put aside, and the mail
6776 buffer buried."
6777 (interactive
6778 (list nil nil nil current-prefix-arg))
6780 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
6781 ;; from sendmail-user-agent to message-user-agent. Some users may
6782 ;; encounter incompatibilities. This hack tries to detect problems
6783 ;; and warn about them.
6784 (and compose-mail-user-agent-warnings
6785 (eq mail-user-agent 'message-user-agent)
6786 (let (warn-vars)
6787 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
6788 mail-yank-hooks mail-archive-file-name
6789 mail-default-reply-to mail-mailing-lists
6790 mail-self-blind))
6791 (and (boundp var)
6792 (symbol-value var)
6793 (push var warn-vars)))
6794 (when warn-vars
6795 (display-warning 'mail
6796 (format "\
6797 The default mail mode is now Message mode.
6798 You have the following Mail mode variable%s customized:
6799 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
6800 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
6801 (if (> (length warn-vars) 1) "s" "")
6802 (mapconcat 'symbol-name
6803 warn-vars " "))))))
6805 (let ((function (get mail-user-agent 'composefunc)))
6806 (funcall function to subject other-headers continue switch-function
6807 yank-action send-actions return-action)))
6809 (defun compose-mail-other-window (&optional to subject other-headers continue
6810 yank-action send-actions
6811 return-action)
6812 "Like \\[compose-mail], but edit the outgoing message in another window."
6813 (interactive (list nil nil nil current-prefix-arg))
6814 (compose-mail to subject other-headers continue
6815 'switch-to-buffer-other-window yank-action send-actions
6816 return-action))
6818 (defun compose-mail-other-frame (&optional to subject other-headers continue
6819 yank-action send-actions
6820 return-action)
6821 "Like \\[compose-mail], but edit the outgoing message in another frame."
6822 (interactive (list nil nil nil current-prefix-arg))
6823 (compose-mail to subject other-headers continue
6824 'switch-to-buffer-other-frame yank-action send-actions
6825 return-action))
6828 (defvar set-variable-value-history nil
6829 "History of values entered with `set-variable'.
6831 Maximum length of the history list is determined by the value
6832 of `history-length', which see.")
6834 (defun set-variable (variable value &optional make-local)
6835 "Set VARIABLE to VALUE. VALUE is a Lisp object.
6836 VARIABLE should be a user option variable name, a Lisp variable
6837 meant to be customized by users. You should enter VALUE in Lisp syntax,
6838 so if you want VALUE to be a string, you must surround it with doublequotes.
6839 VALUE is used literally, not evaluated.
6841 If VARIABLE has a `variable-interactive' property, that is used as if
6842 it were the arg to `interactive' (which see) to interactively read VALUE.
6844 If VARIABLE has been defined with `defcustom', then the type information
6845 in the definition is used to check that VALUE is valid.
6847 With a prefix argument, set VARIABLE to VALUE buffer-locally."
6848 (interactive
6849 (let* ((default-var (variable-at-point))
6850 (var (if (custom-variable-p default-var)
6851 (read-variable (format "Set variable (default %s): " default-var)
6852 default-var)
6853 (read-variable "Set variable: ")))
6854 (minibuffer-help-form '(describe-variable var))
6855 (prop (get var 'variable-interactive))
6856 (obsolete (car (get var 'byte-obsolete-variable)))
6857 (prompt (format "Set %s %s to value: " var
6858 (cond ((local-variable-p var)
6859 "(buffer-local)")
6860 ((or current-prefix-arg
6861 (local-variable-if-set-p var))
6862 "buffer-locally")
6863 (t "globally"))))
6864 (val (progn
6865 (when obsolete
6866 (message (concat "`%S' is obsolete; "
6867 (if (symbolp obsolete) "use `%S' instead" "%s"))
6868 var obsolete)
6869 (sit-for 3))
6870 (if prop
6871 ;; Use VAR's `variable-interactive' property
6872 ;; as an interactive spec for prompting.
6873 (call-interactively `(lambda (arg)
6874 (interactive ,prop)
6875 arg))
6876 (read-from-minibuffer prompt nil
6877 read-expression-map t
6878 'set-variable-value-history
6879 (format "%S" (symbol-value var)))))))
6880 (list var val current-prefix-arg)))
6882 (and (custom-variable-p variable)
6883 (not (get variable 'custom-type))
6884 (custom-load-symbol variable))
6885 (let ((type (get variable 'custom-type)))
6886 (when type
6887 ;; Match with custom type.
6888 (require 'cus-edit)
6889 (setq type (widget-convert type))
6890 (unless (widget-apply type :match value)
6891 (error "Value `%S' does not match type %S of %S"
6892 value (car type) variable))))
6894 (if make-local
6895 (make-local-variable variable))
6897 (set variable value)
6899 ;; Force a thorough redisplay for the case that the variable
6900 ;; has an effect on the display, like `tab-width' has.
6901 (force-mode-line-update))
6903 ;; Define the major mode for lists of completions.
6905 (defvar completion-list-mode-map
6906 (let ((map (make-sparse-keymap)))
6907 (define-key map [mouse-2] 'choose-completion)
6908 (define-key map [follow-link] 'mouse-face)
6909 (define-key map [down-mouse-2] nil)
6910 (define-key map "\C-m" 'choose-completion)
6911 (define-key map "\e\e\e" 'delete-completion-window)
6912 (define-key map [left] 'previous-completion)
6913 (define-key map [right] 'next-completion)
6914 (define-key map "q" 'quit-window)
6915 (define-key map "z" 'kill-this-buffer)
6916 map)
6917 "Local map for completion list buffers.")
6919 ;; Completion mode is suitable only for specially formatted data.
6920 (put 'completion-list-mode 'mode-class 'special)
6922 (defvar completion-reference-buffer nil
6923 "Record the buffer that was current when the completion list was requested.
6924 This is a local variable in the completion list buffer.
6925 Initial value is nil to avoid some compiler warnings.")
6927 (defvar completion-no-auto-exit nil
6928 "Non-nil means `choose-completion-string' should never exit the minibuffer.
6929 This also applies to other functions such as `choose-completion'.")
6931 (defvar completion-base-position nil
6932 "Position of the base of the text corresponding to the shown completions.
6933 This variable is used in the *Completions* buffers.
6934 Its value is a list of the form (START END) where START is the place
6935 where the completion should be inserted and END (if non-nil) is the end
6936 of the text to replace. If END is nil, point is used instead.")
6938 (defvar completion-list-insert-choice-function #'completion--replace
6939 "Function to use to insert the text chosen in *Completions*.
6940 Called with three arguments (BEG END TEXT), it should replace the text
6941 between BEG and END with TEXT. Expected to be set buffer-locally
6942 in the *Completions* buffer.")
6944 (defvar completion-base-size nil
6945 "Number of chars before point not involved in completion.
6946 This is a local variable in the completion list buffer.
6947 It refers to the chars in the minibuffer if completing in the
6948 minibuffer, or in `completion-reference-buffer' otherwise.
6949 Only characters in the field at point are included.
6951 If nil, Emacs determines which part of the tail end of the
6952 buffer's text is involved in completion by comparing the text
6953 directly.")
6954 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
6956 (defun delete-completion-window ()
6957 "Delete the completion list window.
6958 Go to the window from which completion was requested."
6959 (interactive)
6960 (let ((buf completion-reference-buffer))
6961 (if (one-window-p t)
6962 (if (window-dedicated-p) (delete-frame))
6963 (delete-window (selected-window))
6964 (if (get-buffer-window buf)
6965 (select-window (get-buffer-window buf))))))
6967 (defun previous-completion (n)
6968 "Move to the previous item in the completion list."
6969 (interactive "p")
6970 (next-completion (- n)))
6972 (defun next-completion (n)
6973 "Move to the next item in the completion list.
6974 With prefix argument N, move N items (negative N means move backward)."
6975 (interactive "p")
6976 (let ((beg (point-min)) (end (point-max)))
6977 (while (and (> n 0) (not (eobp)))
6978 ;; If in a completion, move to the end of it.
6979 (when (get-text-property (point) 'mouse-face)
6980 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
6981 ;; Move to start of next one.
6982 (unless (get-text-property (point) 'mouse-face)
6983 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
6984 (setq n (1- n)))
6985 (while (and (< n 0) (not (bobp)))
6986 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
6987 ;; If in a completion, move to the start of it.
6988 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
6989 (goto-char (previous-single-property-change
6990 (point) 'mouse-face nil beg)))
6991 ;; Move to end of the previous completion.
6992 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
6993 (goto-char (previous-single-property-change
6994 (point) 'mouse-face nil beg)))
6995 ;; Move to the start of that one.
6996 (goto-char (previous-single-property-change
6997 (point) 'mouse-face nil beg))
6998 (setq n (1+ n))))))
7000 (defun choose-completion (&optional event)
7001 "Choose the completion at point.
7002 If EVENT, use EVENT's position to determine the starting position."
7003 (interactive (list last-nonmenu-event))
7004 ;; In case this is run via the mouse, give temporary modes such as
7005 ;; isearch a chance to turn off.
7006 (run-hooks 'mouse-leave-buffer-hook)
7007 (with-current-buffer (window-buffer (posn-window (event-start event)))
7008 (let ((buffer completion-reference-buffer)
7009 (base-size completion-base-size)
7010 (base-position completion-base-position)
7011 (insert-function completion-list-insert-choice-function)
7012 (choice
7013 (save-excursion
7014 (goto-char (posn-point (event-start event)))
7015 (let (beg end)
7016 (cond
7017 ((and (not (eobp)) (get-text-property (point) 'mouse-face))
7018 (setq end (point) beg (1+ (point))))
7019 ((and (not (bobp))
7020 (get-text-property (1- (point)) 'mouse-face))
7021 (setq end (1- (point)) beg (point)))
7022 (t (error "No completion here")))
7023 (setq beg (previous-single-property-change beg 'mouse-face))
7024 (setq end (or (next-single-property-change end 'mouse-face)
7025 (point-max)))
7026 (buffer-substring-no-properties beg end)))))
7028 (unless (buffer-live-p buffer)
7029 (error "Destination buffer is dead"))
7030 (quit-window nil (posn-window (event-start event)))
7032 (with-current-buffer buffer
7033 (choose-completion-string
7034 choice buffer
7035 (or base-position
7036 (when base-size
7037 ;; Someone's using old completion code that doesn't know
7038 ;; about base-position yet.
7039 (list (+ base-size (field-beginning))))
7040 ;; If all else fails, just guess.
7041 (list (choose-completion-guess-base-position choice)))
7042 insert-function)))))
7044 ;; Delete the longest partial match for STRING
7045 ;; that can be found before POINT.
7046 (defun choose-completion-guess-base-position (string)
7047 (save-excursion
7048 (let ((opoint (point))
7049 len)
7050 ;; Try moving back by the length of the string.
7051 (goto-char (max (- (point) (length string))
7052 (minibuffer-prompt-end)))
7053 ;; See how far back we were actually able to move. That is the
7054 ;; upper bound on how much we can match and delete.
7055 (setq len (- opoint (point)))
7056 (if completion-ignore-case
7057 (setq string (downcase string)))
7058 (while (and (> len 0)
7059 (let ((tail (buffer-substring (point) opoint)))
7060 (if completion-ignore-case
7061 (setq tail (downcase tail)))
7062 (not (string= tail (substring string 0 len)))))
7063 (setq len (1- len))
7064 (forward-char 1))
7065 (point))))
7067 (defun choose-completion-delete-max-match (string)
7068 (declare (obsolete choose-completion-guess-base-position "23.2"))
7069 (delete-region (choose-completion-guess-base-position string) (point)))
7071 (defvar choose-completion-string-functions nil
7072 "Functions that may override the normal insertion of a completion choice.
7073 These functions are called in order with three arguments:
7074 CHOICE - the string to insert in the buffer,
7075 BUFFER - the buffer in which the choice should be inserted,
7076 BASE-POSITION - where to insert the completion.
7078 If a function in the list returns non-nil, that function is supposed
7079 to have inserted the CHOICE in the BUFFER, and possibly exited
7080 the minibuffer; no further functions will be called.
7082 If all functions in the list return nil, that means to use
7083 the default method of inserting the completion in BUFFER.")
7085 (defun choose-completion-string (choice &optional
7086 buffer base-position insert-function)
7087 "Switch to BUFFER and insert the completion choice CHOICE.
7088 BASE-POSITION says where to insert the completion.
7089 INSERT-FUNCTION says how to insert the completion and falls
7090 back on `completion-list-insert-choice-function' when nil."
7092 ;; If BUFFER is the minibuffer, exit the minibuffer
7093 ;; unless it is reading a file name and CHOICE is a directory,
7094 ;; or completion-no-auto-exit is non-nil.
7096 ;; Some older code may call us passing `base-size' instead of
7097 ;; `base-position'. It's difficult to make any use of `base-size',
7098 ;; so we just ignore it.
7099 (unless (consp base-position)
7100 (message "Obsolete `base-size' passed to choose-completion-string")
7101 (setq base-position nil))
7103 (let* ((buffer (or buffer completion-reference-buffer))
7104 (mini-p (minibufferp buffer)))
7105 ;; If BUFFER is a minibuffer, barf unless it's the currently
7106 ;; active minibuffer.
7107 (if (and mini-p
7108 (not (and (active-minibuffer-window)
7109 (equal buffer
7110 (window-buffer (active-minibuffer-window))))))
7111 (error "Minibuffer is not active for completion")
7112 ;; Set buffer so buffer-local choose-completion-string-functions works.
7113 (set-buffer buffer)
7114 (unless (run-hook-with-args-until-success
7115 'choose-completion-string-functions
7116 ;; The fourth arg used to be `mini-p' but was useless
7117 ;; (since minibufferp can be used on the `buffer' arg)
7118 ;; and indeed unused. The last used to be `base-size', so we
7119 ;; keep it to try and avoid breaking old code.
7120 choice buffer base-position nil)
7121 ;; This remove-text-properties should be unnecessary since `choice'
7122 ;; comes from buffer-substring-no-properties.
7123 ;;(remove-text-properties 0 (length choice) '(mouse-face nil) choice)
7124 ;; Insert the completion into the buffer where it was requested.
7125 (funcall (or insert-function completion-list-insert-choice-function)
7126 (or (car base-position) (point))
7127 (or (cadr base-position) (point))
7128 choice)
7129 ;; Update point in the window that BUFFER is showing in.
7130 (let ((window (get-buffer-window buffer t)))
7131 (set-window-point window (point)))
7132 ;; If completing for the minibuffer, exit it with this choice.
7133 (and (not completion-no-auto-exit)
7134 (minibufferp buffer)
7135 minibuffer-completion-table
7136 ;; If this is reading a file name, and the file name chosen
7137 ;; is a directory, don't exit the minibuffer.
7138 (let* ((result (buffer-substring (field-beginning) (point)))
7139 (bounds
7140 (completion-boundaries result minibuffer-completion-table
7141 minibuffer-completion-predicate
7142 "")))
7143 (if (eq (car bounds) (length result))
7144 ;; The completion chosen leads to a new set of completions
7145 ;; (e.g. it's a directory): don't exit the minibuffer yet.
7146 (let ((mini (active-minibuffer-window)))
7147 (select-window mini)
7148 (when minibuffer-auto-raise
7149 (raise-frame (window-frame mini))))
7150 (exit-minibuffer))))))))
7152 (define-derived-mode completion-list-mode nil "Completion List"
7153 "Major mode for buffers showing lists of possible completions.
7154 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
7155 to select the completion near point.
7156 Or click to select one with the mouse.
7158 \\{completion-list-mode-map}"
7159 (set (make-local-variable 'completion-base-size) nil))
7161 (defun completion-list-mode-finish ()
7162 "Finish setup of the completions buffer.
7163 Called from `temp-buffer-show-hook'."
7164 (when (eq major-mode 'completion-list-mode)
7165 (setq buffer-read-only t)))
7167 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
7170 ;; Variables and faces used in `completion-setup-function'.
7172 (defcustom completion-show-help t
7173 "Non-nil means show help message in *Completions* buffer."
7174 :type 'boolean
7175 :version "22.1"
7176 :group 'completion)
7178 ;; This function goes in completion-setup-hook, so that it is called
7179 ;; after the text of the completion list buffer is written.
7180 (defun completion-setup-function ()
7181 (let* ((mainbuf (current-buffer))
7182 (base-dir
7183 ;; FIXME: This is a bad hack. We try to set the default-directory
7184 ;; in the *Completions* buffer so that the relative file names
7185 ;; displayed there can be treated as valid file names, independently
7186 ;; from the completion context. But this suffers from many problems:
7187 ;; - It's not clear when the completions are file names. With some
7188 ;; completion tables (e.g. bzr revision specs), the listed
7189 ;; completions can mix file names and other things.
7190 ;; - It doesn't pay attention to possible quoting.
7191 ;; - With fancy completion styles, the code below will not always
7192 ;; find the right base directory.
7193 (if minibuffer-completing-file-name
7194 (file-name-as-directory
7195 (expand-file-name
7196 (buffer-substring (minibuffer-prompt-end)
7197 (- (point) (or completion-base-size 0))))))))
7198 (with-current-buffer standard-output
7199 (let ((base-size completion-base-size) ;Read before killing localvars.
7200 (base-position completion-base-position)
7201 (insert-fun completion-list-insert-choice-function))
7202 (completion-list-mode)
7203 (set (make-local-variable 'completion-base-size) base-size)
7204 (set (make-local-variable 'completion-base-position) base-position)
7205 (set (make-local-variable 'completion-list-insert-choice-function)
7206 insert-fun))
7207 (set (make-local-variable 'completion-reference-buffer) mainbuf)
7208 (if base-dir (setq default-directory base-dir))
7209 ;; Maybe insert help string.
7210 (when completion-show-help
7211 (goto-char (point-min))
7212 (if (display-mouse-p)
7213 (insert (substitute-command-keys
7214 "Click on a completion to select it.\n")))
7215 (insert (substitute-command-keys
7216 "In this buffer, type \\[choose-completion] to \
7217 select the completion near point.\n\n"))))))
7219 (add-hook 'completion-setup-hook 'completion-setup-function)
7221 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
7222 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
7224 (defun switch-to-completions ()
7225 "Select the completion list window."
7226 (interactive)
7227 (let ((window (or (get-buffer-window "*Completions*" 0)
7228 ;; Make sure we have a completions window.
7229 (progn (minibuffer-completion-help)
7230 (get-buffer-window "*Completions*" 0)))))
7231 (when window
7232 (select-window window)
7233 ;; In the new buffer, go to the first completion.
7234 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
7235 (when (bobp)
7236 (next-completion 1)))))
7238 ;;; Support keyboard commands to turn on various modifiers.
7240 ;; These functions -- which are not commands -- each add one modifier
7241 ;; to the following event.
7243 (defun event-apply-alt-modifier (_ignore-prompt)
7244 "\\<function-key-map>Add the Alt modifier to the following event.
7245 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
7246 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
7247 (defun event-apply-super-modifier (_ignore-prompt)
7248 "\\<function-key-map>Add the Super modifier to the following event.
7249 For example, type \\[event-apply-super-modifier] & to enter Super-&."
7250 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
7251 (defun event-apply-hyper-modifier (_ignore-prompt)
7252 "\\<function-key-map>Add the Hyper modifier to the following event.
7253 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
7254 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
7255 (defun event-apply-shift-modifier (_ignore-prompt)
7256 "\\<function-key-map>Add the Shift modifier to the following event.
7257 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
7258 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
7259 (defun event-apply-control-modifier (_ignore-prompt)
7260 "\\<function-key-map>Add the Ctrl modifier to the following event.
7261 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
7262 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
7263 (defun event-apply-meta-modifier (_ignore-prompt)
7264 "\\<function-key-map>Add the Meta modifier to the following event.
7265 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
7266 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
7268 (defun event-apply-modifier (event symbol lshiftby prefix)
7269 "Apply a modifier flag to event EVENT.
7270 SYMBOL is the name of this modifier, as a symbol.
7271 LSHIFTBY is the numeric value of this modifier, in keyboard events.
7272 PREFIX is the string that represents this modifier in an event type symbol."
7273 (if (numberp event)
7274 (cond ((eq symbol 'control)
7275 (if (and (<= (downcase event) ?z)
7276 (>= (downcase event) ?a))
7277 (- (downcase event) ?a -1)
7278 (if (and (<= (downcase event) ?Z)
7279 (>= (downcase event) ?A))
7280 (- (downcase event) ?A -1)
7281 (logior (lsh 1 lshiftby) event))))
7282 ((eq symbol 'shift)
7283 (if (and (<= (downcase event) ?z)
7284 (>= (downcase event) ?a))
7285 (upcase event)
7286 (logior (lsh 1 lshiftby) event)))
7288 (logior (lsh 1 lshiftby) event)))
7289 (if (memq symbol (event-modifiers event))
7290 event
7291 (let ((event-type (if (symbolp event) event (car event))))
7292 (setq event-type (intern (concat prefix (symbol-name event-type))))
7293 (if (symbolp event)
7294 event-type
7295 (cons event-type (cdr event)))))))
7297 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
7298 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
7299 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
7300 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
7301 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
7302 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
7304 ;;;; Keypad support.
7306 ;; Make the keypad keys act like ordinary typing keys. If people add
7307 ;; bindings for the function key symbols, then those bindings will
7308 ;; override these, so this shouldn't interfere with any existing
7309 ;; bindings.
7311 ;; Also tell read-char how to handle these keys.
7312 (mapc
7313 (lambda (keypad-normal)
7314 (let ((keypad (nth 0 keypad-normal))
7315 (normal (nth 1 keypad-normal)))
7316 (put keypad 'ascii-character normal)
7317 (define-key function-key-map (vector keypad) (vector normal))))
7318 ;; See also kp-keys bound in bindings.el.
7319 '((kp-space ?\s)
7320 (kp-tab ?\t)
7321 (kp-enter ?\r)
7322 (kp-separator ?,)
7323 (kp-equal ?=)
7324 ;; Do the same for various keys that are represented as symbols under
7325 ;; GUIs but naturally correspond to characters.
7326 (backspace 127)
7327 (delete 127)
7328 (tab ?\t)
7329 (linefeed ?\n)
7330 (clear ?\C-l)
7331 (return ?\C-m)
7332 (escape ?\e)
7335 ;;;;
7336 ;;;; forking a twin copy of a buffer.
7337 ;;;;
7339 (defvar clone-buffer-hook nil
7340 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
7342 (defvar clone-indirect-buffer-hook nil
7343 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
7345 (defun clone-process (process &optional newname)
7346 "Create a twin copy of PROCESS.
7347 If NEWNAME is nil, it defaults to PROCESS' name;
7348 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
7349 If PROCESS is associated with a buffer, the new process will be associated
7350 with the current buffer instead.
7351 Returns nil if PROCESS has already terminated."
7352 (setq newname (or newname (process-name process)))
7353 (if (string-match "<[0-9]+>\\'" newname)
7354 (setq newname (substring newname 0 (match-beginning 0))))
7355 (when (memq (process-status process) '(run stop open))
7356 (let* ((process-connection-type (process-tty-name process))
7357 (new-process
7358 (if (memq (process-status process) '(open))
7359 (let ((args (process-contact process t)))
7360 (setq args (plist-put args :name newname))
7361 (setq args (plist-put args :buffer
7362 (if (process-buffer process)
7363 (current-buffer))))
7364 (apply 'make-network-process args))
7365 (apply 'start-process newname
7366 (if (process-buffer process) (current-buffer))
7367 (process-command process)))))
7368 (set-process-query-on-exit-flag
7369 new-process (process-query-on-exit-flag process))
7370 (set-process-inherit-coding-system-flag
7371 new-process (process-inherit-coding-system-flag process))
7372 (set-process-filter new-process (process-filter process))
7373 (set-process-sentinel new-process (process-sentinel process))
7374 (set-process-plist new-process (copy-sequence (process-plist process)))
7375 new-process)))
7377 ;; things to maybe add (currently partly covered by `funcall mode'):
7378 ;; - syntax-table
7379 ;; - overlays
7380 (defun clone-buffer (&optional newname display-flag)
7381 "Create and return a twin copy of the current buffer.
7382 Unlike an indirect buffer, the new buffer can be edited
7383 independently of the old one (if it is not read-only).
7384 NEWNAME is the name of the new buffer. It may be modified by
7385 adding or incrementing <N> at the end as necessary to create a
7386 unique buffer name. If nil, it defaults to the name of the
7387 current buffer, with the proper suffix. If DISPLAY-FLAG is
7388 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
7389 clone a file-visiting buffer, or a buffer whose major mode symbol
7390 has a non-nil `no-clone' property, results in an error.
7392 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
7393 current buffer with appropriate suffix. However, if a prefix
7394 argument is given, then the command prompts for NEWNAME in the
7395 minibuffer.
7397 This runs the normal hook `clone-buffer-hook' in the new buffer
7398 after it has been set up properly in other respects."
7399 (interactive
7400 (progn
7401 (if buffer-file-name
7402 (error "Cannot clone a file-visiting buffer"))
7403 (if (get major-mode 'no-clone)
7404 (error "Cannot clone a buffer in %s mode" mode-name))
7405 (list (if current-prefix-arg
7406 (read-buffer "Name of new cloned buffer: " (current-buffer)))
7407 t)))
7408 (if buffer-file-name
7409 (error "Cannot clone a file-visiting buffer"))
7410 (if (get major-mode 'no-clone)
7411 (error "Cannot clone a buffer in %s mode" mode-name))
7412 (setq newname (or newname (buffer-name)))
7413 (if (string-match "<[0-9]+>\\'" newname)
7414 (setq newname (substring newname 0 (match-beginning 0))))
7415 (let ((buf (current-buffer))
7416 (ptmin (point-min))
7417 (ptmax (point-max))
7418 (pt (point))
7419 (mk (if mark-active (mark t)))
7420 (modified (buffer-modified-p))
7421 (mode major-mode)
7422 (lvars (buffer-local-variables))
7423 (process (get-buffer-process (current-buffer)))
7424 (new (generate-new-buffer (or newname (buffer-name)))))
7425 (save-restriction
7426 (widen)
7427 (with-current-buffer new
7428 (insert-buffer-substring buf)))
7429 (with-current-buffer new
7430 (narrow-to-region ptmin ptmax)
7431 (goto-char pt)
7432 (if mk (set-mark mk))
7433 (set-buffer-modified-p modified)
7435 ;; Clone the old buffer's process, if any.
7436 (when process (clone-process process))
7438 ;; Now set up the major mode.
7439 (funcall mode)
7441 ;; Set up other local variables.
7442 (mapc (lambda (v)
7443 (condition-case () ;in case var is read-only
7444 (if (symbolp v)
7445 (makunbound v)
7446 (set (make-local-variable (car v)) (cdr v)))
7447 (error nil)))
7448 lvars)
7450 ;; Run any hooks (typically set up by the major mode
7451 ;; for cloning to work properly).
7452 (run-hooks 'clone-buffer-hook))
7453 (if display-flag
7454 ;; Presumably the current buffer is shown in the selected frame, so
7455 ;; we want to display the clone elsewhere.
7456 (let ((same-window-regexps nil)
7457 (same-window-buffer-names))
7458 (pop-to-buffer new)))
7459 new))
7462 (defun clone-indirect-buffer (newname display-flag &optional norecord)
7463 "Create an indirect buffer that is a twin copy of the current buffer.
7465 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
7466 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
7467 or if not called with a prefix arg, NEWNAME defaults to the current
7468 buffer's name. The name is modified by adding a `<N>' suffix to it
7469 or by incrementing the N in an existing suffix. Trying to clone a
7470 buffer whose major mode symbol has a non-nil `no-clone-indirect'
7471 property results in an error.
7473 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7474 This is always done when called interactively.
7476 Optional third arg NORECORD non-nil means do not put this buffer at the
7477 front of the list of recently selected ones."
7478 (interactive
7479 (progn
7480 (if (get major-mode 'no-clone-indirect)
7481 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7482 (list (if current-prefix-arg
7483 (read-buffer "Name of indirect buffer: " (current-buffer)))
7484 t)))
7485 (if (get major-mode 'no-clone-indirect)
7486 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7487 (setq newname (or newname (buffer-name)))
7488 (if (string-match "<[0-9]+>\\'" newname)
7489 (setq newname (substring newname 0 (match-beginning 0))))
7490 (let* ((name (generate-new-buffer-name newname))
7491 (buffer (make-indirect-buffer (current-buffer) name t)))
7492 (with-current-buffer buffer
7493 (run-hooks 'clone-indirect-buffer-hook))
7494 (when display-flag
7495 (pop-to-buffer buffer norecord))
7496 buffer))
7499 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
7500 "Like `clone-indirect-buffer' but display in another window."
7501 (interactive
7502 (progn
7503 (if (get major-mode 'no-clone-indirect)
7504 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
7505 (list (if current-prefix-arg
7506 (read-buffer "Name of indirect buffer: " (current-buffer)))
7507 t)))
7508 (let ((pop-up-windows t))
7509 (clone-indirect-buffer newname display-flag norecord)))
7512 ;;; Handling of Backspace and Delete keys.
7514 (defcustom normal-erase-is-backspace 'maybe
7515 "Set the default behavior of the Delete and Backspace keys.
7517 If set to t, Delete key deletes forward and Backspace key deletes
7518 backward.
7520 If set to nil, both Delete and Backspace keys delete backward.
7522 If set to 'maybe (which is the default), Emacs automatically
7523 selects a behavior. On window systems, the behavior depends on
7524 the keyboard used. If the keyboard has both a Backspace key and
7525 a Delete key, and both are mapped to their usual meanings, the
7526 option's default value is set to t, so that Backspace can be used
7527 to delete backward, and Delete can be used to delete forward.
7529 If not running under a window system, customizing this option
7530 accomplishes a similar effect by mapping C-h, which is usually
7531 generated by the Backspace key, to DEL, and by mapping DEL to C-d
7532 via `keyboard-translate'. The former functionality of C-h is
7533 available on the F1 key. You should probably not use this
7534 setting if you don't have both Backspace, Delete and F1 keys.
7536 Setting this variable with setq doesn't take effect. Programmatically,
7537 call `normal-erase-is-backspace-mode' (which see) instead."
7538 :type '(choice (const :tag "Off" nil)
7539 (const :tag "Maybe" maybe)
7540 (other :tag "On" t))
7541 :group 'editing-basics
7542 :version "21.1"
7543 :set (lambda (symbol value)
7544 ;; The fboundp is because of a problem with :set when
7545 ;; dumping Emacs. It doesn't really matter.
7546 (if (fboundp 'normal-erase-is-backspace-mode)
7547 (normal-erase-is-backspace-mode (or value 0))
7548 (set-default symbol value))))
7550 (defun normal-erase-is-backspace-setup-frame (&optional frame)
7551 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
7552 (unless frame (setq frame (selected-frame)))
7553 (with-selected-frame frame
7554 (unless (terminal-parameter nil 'normal-erase-is-backspace)
7555 (normal-erase-is-backspace-mode
7556 (if (if (eq normal-erase-is-backspace 'maybe)
7557 (and (not noninteractive)
7558 (or (memq system-type '(ms-dos windows-nt))
7559 (memq window-system '(w32 ns))
7560 (and (memq window-system '(x))
7561 (fboundp 'x-backspace-delete-keys-p)
7562 (x-backspace-delete-keys-p))
7563 ;; If the terminal Emacs is running on has erase char
7564 ;; set to ^H, use the Backspace key for deleting
7565 ;; backward, and the Delete key for deleting forward.
7566 (and (null window-system)
7567 (eq tty-erase-char ?\^H))))
7568 normal-erase-is-backspace)
7569 1 0)))))
7571 (define-minor-mode normal-erase-is-backspace-mode
7572 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
7573 With a prefix argument ARG, enable this feature if ARG is
7574 positive, and disable it otherwise. If called from Lisp, enable
7575 the mode if ARG is omitted or nil.
7577 On window systems, when this mode is on, Delete is mapped to C-d
7578 and Backspace is mapped to DEL; when this mode is off, both
7579 Delete and Backspace are mapped to DEL. (The remapping goes via
7580 `local-function-key-map', so binding Delete or Backspace in the
7581 global or local keymap will override that.)
7583 In addition, on window systems, the bindings of C-Delete, M-Delete,
7584 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
7585 the global keymap in accordance with the functionality of Delete and
7586 Backspace. For example, if Delete is remapped to C-d, which deletes
7587 forward, C-Delete is bound to `kill-word', but if Delete is remapped
7588 to DEL, which deletes backward, C-Delete is bound to
7589 `backward-kill-word'.
7591 If not running on a window system, a similar effect is accomplished by
7592 remapping C-h (normally produced by the Backspace key) and DEL via
7593 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
7594 to C-d; if it's off, the keys are not remapped.
7596 When not running on a window system, and this mode is turned on, the
7597 former functionality of C-h is available on the F1 key. You should
7598 probably not turn on this mode on a text-only terminal if you don't
7599 have both Backspace, Delete and F1 keys.
7601 See also `normal-erase-is-backspace'."
7602 :variable ((eq (terminal-parameter nil 'normal-erase-is-backspace) 1)
7603 . (lambda (v)
7604 (setf (terminal-parameter nil 'normal-erase-is-backspace)
7605 (if v 1 0))))
7606 (let ((enabled (eq 1 (terminal-parameter
7607 nil 'normal-erase-is-backspace))))
7609 (cond ((or (memq window-system '(x w32 ns pc))
7610 (memq system-type '(ms-dos windows-nt)))
7611 (let ((bindings
7612 `(([M-delete] [M-backspace])
7613 ([C-M-delete] [C-M-backspace])
7614 ([?\e C-delete] [?\e C-backspace]))))
7616 (if enabled
7617 (progn
7618 (define-key local-function-key-map [delete] [deletechar])
7619 (define-key local-function-key-map [kp-delete] [deletechar])
7620 (define-key local-function-key-map [backspace] [?\C-?])
7621 (dolist (b bindings)
7622 ;; Not sure if input-decode-map is really right, but
7623 ;; keyboard-translate-table (used below) only works
7624 ;; for integer events, and key-translation-table is
7625 ;; global (like the global-map, used earlier).
7626 (define-key input-decode-map (car b) nil)
7627 (define-key input-decode-map (cadr b) nil)))
7628 (define-key local-function-key-map [delete] [?\C-?])
7629 (define-key local-function-key-map [kp-delete] [?\C-?])
7630 (define-key local-function-key-map [backspace] [?\C-?])
7631 (dolist (b bindings)
7632 (define-key input-decode-map (car b) (cadr b))
7633 (define-key input-decode-map (cadr b) (car b))))))
7635 (if enabled
7636 (progn
7637 (keyboard-translate ?\C-h ?\C-?)
7638 (keyboard-translate ?\C-? ?\C-d))
7639 (keyboard-translate ?\C-h ?\C-h)
7640 (keyboard-translate ?\C-? ?\C-?))))
7642 (if (called-interactively-p 'interactive)
7643 (message "Delete key deletes %s"
7644 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
7645 "forward" "backward")))))
7647 (defvar vis-mode-saved-buffer-invisibility-spec nil
7648 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
7650 (define-minor-mode read-only-mode
7651 "Change whether the current buffer is read-only.
7652 With prefix argument ARG, make the buffer read-only if ARG is
7653 positive, otherwise make it writable. If buffer is read-only
7654 and `view-read-only' is non-nil, enter view mode.
7656 Do not call this from a Lisp program unless you really intend to
7657 do the same thing as the \\[read-only-mode] command, including
7658 possibly enabling or disabling View mode. Also, note that this
7659 command works by setting the variable `buffer-read-only', which
7660 does not affect read-only regions caused by text properties. To
7661 ignore read-only status in a Lisp program (whether due to text
7662 properties or buffer state), bind `inhibit-read-only' temporarily
7663 to a non-nil value."
7664 :variable buffer-read-only
7665 (cond
7666 ((and (not buffer-read-only) view-mode)
7667 (View-exit-and-edit)
7668 (make-local-variable 'view-read-only)
7669 (setq view-read-only t)) ; Must leave view mode.
7670 ((and buffer-read-only view-read-only
7671 ;; If view-mode is already active, `view-mode-enter' is a nop.
7672 (not view-mode)
7673 (not (eq (get major-mode 'mode-class) 'special)))
7674 (view-mode-enter))))
7676 (define-minor-mode visible-mode
7677 "Toggle making all invisible text temporarily visible (Visible mode).
7678 With a prefix argument ARG, enable Visible mode if ARG is
7679 positive, and disable it otherwise. If called from Lisp, enable
7680 the mode if ARG is omitted or nil.
7682 This mode works by saving the value of `buffer-invisibility-spec'
7683 and setting it to nil."
7684 :lighter " Vis"
7685 :group 'editing-basics
7686 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
7687 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
7688 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
7689 (when visible-mode
7690 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
7691 buffer-invisibility-spec)
7692 (setq buffer-invisibility-spec nil)))
7694 (defvar messages-buffer-mode-map
7695 (let ((map (make-sparse-keymap)))
7696 (set-keymap-parent map special-mode-map)
7697 (define-key map "g" nil) ; nothing to revert
7698 map))
7700 (define-derived-mode messages-buffer-mode special-mode "Messages"
7701 "Major mode used in the \"*Messages*\" buffer.")
7703 (defun messages-buffer ()
7704 "Return the \"*Messages*\" buffer.
7705 If it does not exist, create and it switch it to `messages-buffer-mode'."
7706 (or (get-buffer "*Messages*")
7707 (with-current-buffer (get-buffer-create "*Messages*")
7708 (messages-buffer-mode)
7709 (current-buffer))))
7712 ;; Minibuffer prompt stuff.
7714 ;;(defun minibuffer-prompt-modification (start end)
7715 ;; (error "You cannot modify the prompt"))
7718 ;;(defun minibuffer-prompt-insertion (start end)
7719 ;; (let ((inhibit-modification-hooks t))
7720 ;; (delete-region start end)
7721 ;; ;; Discard undo information for the text insertion itself
7722 ;; ;; and for the text deletion.above.
7723 ;; (when (consp buffer-undo-list)
7724 ;; (setq buffer-undo-list (cddr buffer-undo-list)))
7725 ;; (message "You cannot modify the prompt")))
7728 ;;(setq minibuffer-prompt-properties
7729 ;; (list 'modification-hooks '(minibuffer-prompt-modification)
7730 ;; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
7733 ;;;; Problematic external packages.
7735 ;; rms says this should be done by specifying symbols that define
7736 ;; versions together with bad values. This is therefore not as
7737 ;; flexible as it could be. See the thread:
7738 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
7739 (defconst bad-packages-alist
7740 ;; Not sure exactly which semantic versions have problems.
7741 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
7742 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
7743 "The version of `semantic' loaded does not work in Emacs 22.
7744 It can cause constant high CPU load.
7745 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
7746 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
7747 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
7748 ;; provided the `CUA-mode' feature. Since this is no longer true,
7749 ;; we can warn the user if the `CUA-mode' feature is ever provided.
7750 (CUA-mode t nil
7751 "CUA-mode is now part of the standard GNU Emacs distribution,
7752 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
7754 You have loaded an older version of CUA-mode which does not work
7755 correctly with this version of Emacs. You should remove the old
7756 version and use the one distributed with Emacs."))
7757 "Alist of packages known to cause problems in this version of Emacs.
7758 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
7759 PACKAGE is either a regular expression to match file names, or a
7760 symbol (a feature name), like for `with-eval-after-load'.
7761 SYMBOL is either the name of a string variable, or `t'. Upon
7762 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
7763 warning using STRING as the message.")
7765 (defun bad-package-check (package)
7766 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
7767 (condition-case nil
7768 (let* ((list (assoc package bad-packages-alist))
7769 (symbol (nth 1 list)))
7770 (and list
7771 (boundp symbol)
7772 (or (eq symbol t)
7773 (and (stringp (setq symbol (eval symbol)))
7774 (string-match-p (nth 2 list) symbol)))
7775 (display-warning package (nth 3 list) :warning)))
7776 (error nil)))
7778 (dolist (elem bad-packages-alist)
7779 (let ((pkg (car elem)))
7780 (with-eval-after-load pkg
7781 (bad-package-check pkg))))
7784 ;;; Generic dispatcher commands
7786 ;; Macro `define-alternatives' is used to create generic commands.
7787 ;; Generic commands are these (like web, mail, news, encrypt, irc, etc.)
7788 ;; that can have different alternative implementations where choosing
7789 ;; among them is exclusively a matter of user preference.
7791 ;; (define-alternatives COMMAND) creates a new interactive command
7792 ;; M-x COMMAND and a customizable variable COMMAND-alternatives.
7793 ;; Typically, the user will not need to customize this variable; packages
7794 ;; wanting to add alternative implementations should use
7796 ;; ;;;###autoload (push '("My impl name" . my-impl-symbol) COMMAND-alternatives
7798 (defmacro define-alternatives (command &rest customizations)
7799 "Define the new command `COMMAND'.
7801 The argument `COMMAND' should be a symbol.
7803 Running `M-x COMMAND RET' for the first time prompts for which
7804 alternative to use and records the selected command as a custom
7805 variable.
7807 Running `C-u M-x COMMAND RET' prompts again for an alternative
7808 and overwrites the previous choice.
7810 The variable `COMMAND-alternatives' contains an alist with
7811 alternative implementations of COMMAND. `define-alternatives'
7812 does not have any effect until this variable is set.
7814 CUSTOMIZATIONS, if non-nil, should be composed of alternating
7815 `defcustom' keywords and values to add to the declaration of
7816 `COMMAND-alternatives' (typically :group and :version)."
7817 (let* ((command-name (symbol-name command))
7818 (varalt-name (concat command-name "-alternatives"))
7819 (varalt-sym (intern varalt-name))
7820 (varimp-sym (intern (concat command-name "--implementation"))))
7821 `(progn
7823 (defcustom ,varalt-sym nil
7824 ,(format "Alist of alternative implementations for the `%s' command.
7826 Each entry must be a pair (ALTNAME . ALTFUN), where:
7827 ALTNAME - The name shown at user to describe the alternative implementation.
7828 ALTFUN - The function called to implement this alternative."
7829 command-name)
7830 :type '(alist :key-type string :value-type function)
7831 ,@customizations)
7833 (put ',varalt-sym 'definition-name ',command)
7834 (defvar ,varimp-sym nil "Internal use only.")
7836 (defun ,command (&optional arg)
7837 ,(format "Run generic command `%s'.
7838 If used for the first time, or with interactive ARG, ask the user which
7839 implementation to use for `%s'. The variable `%s'
7840 contains the list of implementations currently supported for this command."
7841 command-name command-name varalt-name)
7842 (interactive "P")
7843 (when (or arg (null ,varimp-sym))
7844 (let ((val (completing-read
7845 ,(format "Select implementation for command `%s': "
7846 command-name)
7847 ,varalt-sym nil t)))
7848 (unless (string-equal val "")
7849 (when (null ,varimp-sym)
7850 (message
7851 "Use `C-u M-x %s RET' to select another implementation"
7852 ,command-name)
7853 (sit-for 3))
7854 (customize-save-variable ',varimp-sym
7855 (cdr (assoc-string val ,varalt-sym))))))
7856 (if ,varimp-sym
7857 (call-interactively ,varimp-sym)
7858 (message ,(format "No implementation selected for command `%s'"
7859 command-name)))))))
7862 ;; This is here because files in obsolete/ are not scanned for autoloads.
7864 (defvar iswitchb-mode nil "\
7865 Non-nil if Iswitchb mode is enabled.
7866 See the command `iswitchb-mode' for a description of this minor mode.
7867 Setting this variable directly does not take effect;
7868 either customize it (see the info node `Easy Customization')
7869 or call the function `iswitchb-mode'.")
7871 (custom-autoload 'iswitchb-mode "iswitchb" nil)
7873 (autoload 'iswitchb-mode "iswitchb" "\
7874 Toggle Iswitchb mode.
7875 With a prefix argument ARG, enable Iswitchb mode if ARG is
7876 positive, and disable it otherwise. If called from Lisp, enable
7877 the mode if ARG is omitted or nil.
7879 Iswitchb mode is a global minor mode that enables switching
7880 between buffers using substrings. See `iswitchb' for details.
7882 \(fn &optional ARG)" t nil)
7884 (make-obsolete 'iswitchb-mode
7885 "use `icomplete-mode' or `ido-mode' instead." "24.4")
7888 (provide 'simple)
7890 ;;; simple.el ends here