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