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