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