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