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