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