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