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