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