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