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