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