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