Merge from trunk
[bpt/emacs.git] / lisp / simple.el
CommitLineData
c88ab9ce
ER
1;;; simple.el --- basic editing commands for Emacs
2
73b0cd50 3;; Copyright (C) 1985-1987, 1993-2011 Free Software Foundation, Inc.
2076c87c 4
30764597
PJ
5;; Maintainer: FSF
6;; Keywords: internal
bd78fa1d 7;; Package: emacs
30764597 8
2076c87c
JB
9;; This file is part of GNU Emacs.
10
eb3fa2cf 11;; GNU Emacs is free software: you can redistribute it and/or modify
2076c87c 12;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
2076c87c
JB
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
eb3fa2cf 22;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
2076c87c 23
d9ecc911
ER
24;;; Commentary:
25
26;; A grab-bag of basic Emacs commands not specifically related to some
27;; major mode or to file-handling.
28
3a801d0c 29;;; Code:
2076c87c 30
30ee26a9
EZ
31;; This is for lexical-let in apply-partially.
32(eval-when-compile (require 'cl))
33
f31b1257
DN
34(declare-function widget-convert "wid-edit" (type &rest args))
35(declare-function shell-mode "shell" ())
d01a33cf 36
ca60ee11
JB
37(defvar compilation-current-error)
38
7fcce20f 39(defcustom idle-update-delay 0.5
1d2b0303 40 "Idle time delay before updating various things on the screen.
7fcce20f
RS
41Various Emacs features that update auxiliary information when point moves
42wait this many seconds after Emacs becomes idle before doing an update."
43 :type 'number
44 :group 'display
45 :version "22.1")
d01a33cf 46
69c1dd37 47(defgroup killing nil
c9f0110e 48 "Killing and yanking commands."
69c1dd37
RS
49 :group 'editing)
50
69c1dd37
RS
51(defgroup paren-matching nil
52 "Highlight (un)matching of parens and expressions."
69c1dd37
RS
53 :group 'matching)
54
7979163c
JL
55(defun get-next-valid-buffer (list &optional buffer visible-ok frame)
56 "Search LIST for a valid buffer to display in FRAME.
a74f9094
KL
57Return nil when all buffers in LIST are undesirable for display,
58otherwise return the first suitable buffer in LIST.
59
60Buffers not visible in windows are preferred to visible buffers,
61unless VISIBLE-OK is non-nil.
62If the optional argument FRAME is nil, it defaults to the selected frame.
7979163c 63If BUFFER is non-nil, ignore occurrences of that buffer in LIST."
a74f9094
KL
64 ;; This logic is more or less copied from other-buffer.
65 (setq frame (or frame (selected-frame)))
66 (let ((pred (frame-parameter frame 'buffer-predicate))
67 found buf)
68 (while (and (not found) list)
69 (setq buf (car list))
70 (if (and (not (eq buffer buf))
71 (buffer-live-p buf)
72 (or (null pred) (funcall pred buf))
73 (not (eq (aref (buffer-name buf) 0) ?\s))
74 (or visible-ok (null (get-buffer-window buf 'visible))))
75 (setq found buf)
76 (setq list (cdr list))))
77 (car list)))
78
7979163c 79(defun last-buffer (&optional buffer visible-ok frame)
4dc1abeb
MR
80 "Return the last buffer in FRAME's buffer list.
81If BUFFER is the last buffer, return the preceding buffer instead.
a74f9094
KL
82Buffers not visible in windows are preferred to visible buffers,
83unless optional argument VISIBLE-OK is non-nil.
4dc1abeb
MR
84Optional third argument FRAME nil or omitted means use the
85selected frame's buffer list.
86If no such buffer exists, return the buffer `*scratch*', creating
87it if necessary."
a74f9094 88 (setq frame (or frame (selected-frame)))
a18b8cb5
KL
89 (or (get-next-valid-buffer (nreverse (buffer-list frame))
90 buffer visible-ok frame)
4dc1abeb
MR
91 (get-buffer "*scratch*")
92 (let ((scratch (get-buffer-create "*scratch*")))
93 (set-buffer-major-mode scratch)
94 scratch)))
95
f54b0d85
RS
96(defun next-buffer ()
97 "Switch to the next buffer in cyclic order."
98 (interactive)
a18b8cb5 99 (let ((buffer (current-buffer)))
a74f9094 100 (switch-to-buffer (other-buffer buffer t))
a18b8cb5 101 (bury-buffer buffer)))
a74f9094
KL
102
103(defun previous-buffer ()
f54b0d85
RS
104 "Switch to the previous buffer in cyclic order."
105 (interactive)
a18b8cb5 106 (switch-to-buffer (last-buffer (current-buffer) t)))
a74f9094 107
ee9c5954 108\f
50f007fb 109;;; next-error support framework
bbf41690
RS
110
111(defgroup next-error nil
f33321ad 112 "`next-error' support framework."
bbf41690 113 :group 'compilation
bf247b6e 114 :version "22.1")
bbf41690
RS
115
116(defface next-error
117 '((t (:inherit region)))
118 "Face used to highlight next error locus."
119 :group 'next-error
bf247b6e 120 :version "22.1")
bbf41690 121
7408ee97 122(defcustom next-error-highlight 0.5
1d2b0303 123 "Highlighting of locations in selected source buffers.
676b1a74
CY
124If a number, highlight the locus in `next-error' face for the given time
125in seconds, or until the next command is executed.
126If t, highlight the locus until the next command is executed, or until
127some other locus replaces it.
bbf41690
RS
128If nil, don't highlight the locus in the source buffer.
129If `fringe-arrow', indicate the locus by the fringe arrow."
6d3c944b 130 :type '(choice (number :tag "Highlight for specified time")
c81b29e6 131 (const :tag "Semipermanent highlighting" t)
bbf41690 132 (const :tag "No highlighting" nil)
6d3c944b 133 (const :tag "Fringe arrow" fringe-arrow))
bbf41690 134 :group 'next-error
bf247b6e 135 :version "22.1")
bbf41690 136
7408ee97 137(defcustom next-error-highlight-no-select 0.5
1d2b0303 138 "Highlighting of locations in `next-error-no-select'.
f33321ad 139If number, highlight the locus in `next-error' face for given time in seconds.
6d3c944b 140If t, highlight the locus indefinitely until some other locus replaces it.
bbf41690
RS
141If nil, don't highlight the locus in the source buffer.
142If `fringe-arrow', indicate the locus by the fringe arrow."
6d3c944b 143 :type '(choice (number :tag "Highlight for specified time")
c81b29e6 144 (const :tag "Semipermanent highlighting" t)
bbf41690 145 (const :tag "No highlighting" nil)
6d3c944b 146 (const :tag "Fringe arrow" fringe-arrow))
bbf41690 147 :group 'next-error
bf247b6e 148 :version "22.1")
bbf41690 149
446b609e 150(defcustom next-error-recenter nil
1d2b0303 151 "Display the line in the visited source file recentered as specified.
28adf31c
TTN
152If non-nil, the value is passed directly to `recenter'."
153 :type '(choice (integer :tag "Line to recenter to")
154 (const :tag "Center of window" (4))
446b609e
TTN
155 (const :tag "No recentering" nil))
156 :group 'next-error
157 :version "23.1")
158
d634a3a2 159(defcustom next-error-hook nil
1d2b0303 160 "List of hook functions run by `next-error' after visiting source file."
d634a3a2
JL
161 :type 'hook
162 :group 'next-error)
163
814c3037
JL
164(defvar next-error-highlight-timer nil)
165
9c9b00d6 166(defvar next-error-overlay-arrow-position nil)
6bdad9ae 167(put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
9c9b00d6
JL
168(add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
169
50f007fb 170(defvar next-error-last-buffer nil
f33321ad 171 "The most recent `next-error' buffer.
50f007fb
KS
172A buffer becomes most recent when its compilation, grep, or
173similar mode is started, or when it is used with \\[next-error]
174or \\[compile-goto-error].")
175
176(defvar next-error-function nil
e462ab77
SM
177 "Function to use to find the next error in the current buffer.
178The function is called with 2 parameters:
179ARG is an integer specifying by how many errors to move.
180RESET is a boolean which, if non-nil, says to go back to the beginning
181of the errors before moving.
182Major modes providing compile-like functionality should set this variable
183to indicate to `next-error' that this is a candidate buffer and how
184to navigate in it.")
50f007fb
KS
185(make-variable-buffer-local 'next-error-function)
186
8cdba32b
RS
187(defvar next-error-move-function nil
188 "Function to use to move to an error locus.
189It takes two arguments, a buffer position in the error buffer
190and a buffer position in the error locus buffer.
191The buffer for the error locus should already be current.
192nil means use goto-char using the second argument position.")
193(make-variable-buffer-local 'next-error-move-function)
194
f1e2a033 195(defsubst next-error-buffer-p (buffer
e967cd11 196 &optional avoid-current
f1e2a033 197 extra-test-inclusive
5f9e0ca5 198 extra-test-exclusive)
f33321ad 199 "Test if BUFFER is a `next-error' capable buffer.
e967cd11
RS
200
201If AVOID-CURRENT is non-nil, treat the current buffer
202as an absolute last resort only.
203
204The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
205that normally would not qualify. If it returns t, the buffer
206in question is treated as usable.
207
7979163c 208The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
01ba9662 209that would normally be considered usable. If it returns nil,
e967cd11
RS
210that buffer is rejected."
211 (and (buffer-name buffer) ;First make sure it's live.
212 (not (and avoid-current (eq buffer (current-buffer))))
213 (with-current-buffer buffer
214 (if next-error-function ; This is the normal test.
215 ;; Optionally reject some buffers.
216 (if extra-test-exclusive
217 (funcall extra-test-exclusive)
218 t)
219 ;; Optionally accept some other buffers.
220 (and extra-test-inclusive
221 (funcall extra-test-inclusive))))))
222
223(defun next-error-find-buffer (&optional avoid-current
f1e2a033 224 extra-test-inclusive
5f9e0ca5 225 extra-test-exclusive)
f33321ad 226 "Return a `next-error' capable buffer.
7979163c 227
e967cd11
RS
228If AVOID-CURRENT is non-nil, treat the current buffer
229as an absolute last resort only.
230
01ba9662 231The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
e967cd11
RS
232that normally would not qualify. If it returns t, the buffer
233in question is treated as usable.
234
7979163c 235The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
e967cd11
RS
236that would normally be considered usable. If it returns nil,
237that buffer is rejected."
03e75c7e
JL
238 (or
239 ;; 1. If one window on the selected frame displays such buffer, return it.
240 (let ((window-buffers
241 (delete-dups
242 (delq nil (mapcar (lambda (w)
243 (if (next-error-buffer-p
e967cd11
RS
244 (window-buffer w)
245 avoid-current
f1e2a033 246 extra-test-inclusive extra-test-exclusive)
03e75c7e
JL
247 (window-buffer w)))
248 (window-list))))))
03e75c7e
JL
249 (if (eq (length window-buffers) 1)
250 (car window-buffers)))
e967cd11 251 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
03e75c7e 252 (if (and next-error-last-buffer
e967cd11 253 (next-error-buffer-p next-error-last-buffer avoid-current
f1e2a033 254 extra-test-inclusive extra-test-exclusive))
e967cd11
RS
255 next-error-last-buffer)
256 ;; 3. If the current buffer is acceptable, choose it.
257 (if (next-error-buffer-p (current-buffer) avoid-current
258 extra-test-inclusive extra-test-exclusive)
03e75c7e 259 (current-buffer))
e967cd11 260 ;; 4. Look for any acceptable buffer.
03e75c7e
JL
261 (let ((buffers (buffer-list)))
262 (while (and buffers
e967cd11
RS
263 (not (next-error-buffer-p
264 (car buffers) avoid-current
265 extra-test-inclusive extra-test-exclusive)))
03e75c7e 266 (setq buffers (cdr buffers)))
e967cd11
RS
267 (car buffers))
268 ;; 5. Use the current buffer as a last resort if it qualifies,
269 ;; even despite AVOID-CURRENT.
270 (and avoid-current
271 (next-error-buffer-p (current-buffer) nil
272 extra-test-inclusive extra-test-exclusive)
273 (progn
ee4dc5d9 274 (message "This is the only buffer with error message locations")
e967cd11
RS
275 (current-buffer)))
276 ;; 6. Give up.
ee4dc5d9 277 (error "No buffers contain error message locations")))
50f007fb 278
310abb0b 279(defun next-error (&optional arg reset)
f33321ad 280 "Visit next `next-error' message and corresponding source code.
50f007fb
KS
281
282If all the error messages parsed so far have been processed already,
283the message buffer is checked for new ones.
284
e462ab77 285A prefix ARG specifies how many error messages to move;
50f007fb
KS
286negative means move back to previous error messages.
287Just \\[universal-argument] as a prefix means reparse the error message buffer
288and start at the first error.
289
e249a6d8 290The RESET argument specifies that we should restart from the beginning.
50f007fb
KS
291
292\\[next-error] normally uses the most recently started
293compilation, grep, or occur buffer. It can also operate on any
294buffer with output from the \\[compile], \\[grep] commands, or,
295more generally, on any buffer in Compilation mode or with
296Compilation Minor mode enabled, or any buffer in which
03e75c7e
JL
297`next-error-function' is bound to an appropriate function.
298To specify use of a particular buffer for error messages, type
299\\[next-error] in that buffer when it is the only one displayed
300in the current frame.
50f007fb 301
d634a3a2
JL
302Once \\[next-error] has chosen the buffer for error messages, it
303runs `next-error-hook' with `run-hooks', and stays with that buffer
304until you use it in some other buffer which uses Compilation mode
305or Compilation Minor mode.
50f007fb
KS
306
307See variables `compilation-parse-errors-function' and
308\`compilation-error-regexp-alist' for customization ideas."
309 (interactive "P")
e462ab77 310 (if (consp arg) (setq reset t arg nil))
50f007fb
KS
311 (when (setq next-error-last-buffer (next-error-find-buffer))
312 ;; we know here that next-error-function is a valid symbol we can funcall
313 (with-current-buffer next-error-last-buffer
d634a3a2 314 (funcall next-error-function (prefix-numeric-value arg) reset)
446b609e
TTN
315 (when next-error-recenter
316 (recenter next-error-recenter))
d634a3a2 317 (run-hooks 'next-error-hook))))
50f007fb 318
56ab610b
RS
319(defun next-error-internal ()
320 "Visit the source code corresponding to the `next-error' message at point."
321 (setq next-error-last-buffer (current-buffer))
322 ;; we know here that next-error-function is a valid symbol we can funcall
323 (with-current-buffer next-error-last-buffer
324 (funcall next-error-function 0 nil)
446b609e
TTN
325 (when next-error-recenter
326 (recenter next-error-recenter))
56ab610b
RS
327 (run-hooks 'next-error-hook)))
328
50f007fb
KS
329(defalias 'goto-next-locus 'next-error)
330(defalias 'next-match 'next-error)
331
310abb0b 332(defun previous-error (&optional n)
f33321ad 333 "Visit previous `next-error' message and corresponding source code.
50f007fb
KS
334
335Prefix arg N says how many error messages to move backwards (or
336forwards, if negative).
337
338This operates on the output from the \\[compile] and \\[grep] commands."
339 (interactive "p")
310abb0b 340 (next-error (- (or n 1))))
50f007fb 341
310abb0b 342(defun first-error (&optional n)
50f007fb
KS
343 "Restart at the first error.
344Visit corresponding source code.
345With prefix arg N, visit the source code of the Nth error.
346This operates on the output from the \\[compile] command, for instance."
347 (interactive "p")
348 (next-error n t))
349
310abb0b 350(defun next-error-no-select (&optional n)
f33321ad 351 "Move point to the next error in the `next-error' buffer and highlight match.
50f007fb
KS
352Prefix arg N says how many error messages to move forwards (or
353backwards, if negative).
354Finds and highlights the source line like \\[next-error], but does not
355select the source buffer."
356 (interactive "p")
ee9c5954
JL
357 (let ((next-error-highlight next-error-highlight-no-select))
358 (next-error n))
50f007fb
KS
359 (pop-to-buffer next-error-last-buffer))
360
310abb0b 361(defun previous-error-no-select (&optional n)
f33321ad 362 "Move point to the previous error in the `next-error' buffer and highlight match.
50f007fb
KS
363Prefix arg N says how many error messages to move backwards (or
364forwards, if negative).
365Finds and highlights the source line like \\[previous-error], but does not
366select the source buffer."
367 (interactive "p")
310abb0b 368 (next-error-no-select (- (or n 1))))
50f007fb 369
85be9ec4 370;; Internal variable for `next-error-follow-mode-post-command-hook'.
282d6eae
EZ
371(defvar next-error-follow-last-line nil)
372
2a223f35 373(define-minor-mode next-error-follow-minor-mode
282d6eae 374 "Minor mode for compilation, occur and diff modes.
2a223f35
EZ
375When turned on, cursor motion in the compilation, grep, occur or diff
376buffer causes automatic display of the corresponding source code
377location."
ed8e0f0a 378 :group 'next-error :init-value nil :lighter " Fol"
8a98a6c2 379 (if (not next-error-follow-minor-mode)
282d6eae
EZ
380 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
381 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
e56dd5c6 382 (make-local-variable 'next-error-follow-last-line)))
282d6eae 383
85be9ec4
SM
384;; Used as a `post-command-hook' by `next-error-follow-mode'
385;; for the *Compilation* *grep* and *Occur* buffers.
282d6eae
EZ
386(defun next-error-follow-mode-post-command-hook ()
387 (unless (equal next-error-follow-last-line (line-number-at-pos))
388 (setq next-error-follow-last-line (line-number-at-pos))
389 (condition-case nil
390 (let ((compilation-context-lines nil))
391 (setq compilation-current-error (point))
392 (next-error-no-select 0))
393 (error t))))
394
ee9c5954 395\f
50f007fb
KS
396;;;
397
93be67de
KH
398(defun fundamental-mode ()
399 "Major mode not specialized for anything in particular.
400Other major modes are defined by comparison with this one."
401 (interactive)
e174f8db 402 (kill-all-local-variables)
56924d99 403 (run-mode-hooks 'fundamental-mode-hook))
eaae8106 404
d445b3f8
SM
405;; Special major modes to view specially formatted data rather than files.
406
407(defvar special-mode-map
408 (let ((map (make-sparse-keymap)))
409 (suppress-keymap map)
410 (define-key map "q" 'quit-window)
411 (define-key map " " 'scroll-up)
412 (define-key map "\C-?" 'scroll-down)
413 (define-key map "?" 'describe-mode)
abef340a 414 (define-key map "h" 'describe-mode)
d445b3f8
SM
415 (define-key map ">" 'end-of-buffer)
416 (define-key map "<" 'beginning-of-buffer)
417 (define-key map "g" 'revert-buffer)
abef340a 418 (define-key map "z" 'kill-this-buffer)
d445b3f8 419 map))
1d2b0303 420
d445b3f8
SM
421(put 'special-mode 'mode-class 'special)
422(define-derived-mode special-mode nil "Special"
423 "Parent major mode from which special major modes should inherit."
424 (setq buffer-read-only t))
425
10dcc561
SM
426;; Major mode meant to be the parent of programming modes.
427
b2a15250
SM
428(defvar prog-mode-map
429 (let ((map (make-sparse-keymap)))
430 (define-key map [?\C-\M-q] 'prog-indent-sexp)
431 map)
432 "Keymap used for programming modes.")
433
434(defun prog-indent-sexp ()
435 "Indent the expression after point."
436 (interactive)
437 (let ((start (point))
438 (end (save-excursion (forward-sexp 1) (point))))
439 (indent-region start end nil)))
440
10dcc561
SM
441(define-derived-mode prog-mode fundamental-mode "Prog"
442 "Major mode for editing programming language source code."
443 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
228482b2
EZ
444 (set (make-local-variable 'parse-sexp-ignore-comments) t)
445 ;; Any programming language is always written left to right.
446 (setq bidi-paragraph-direction 'left-to-right))
10dcc561 447
93be67de
KH
448;; Making and deleting lines.
449
28fab7b5
GM
450(defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
451 "Propertized string representing a hard newline character.")
4ea0018b 452
30bb9754 453(defun newline (&optional arg)
d133d835 454 "Insert a newline, and move to left margin of the new line if it's blank.
058d4999
DL
455If `use-hard-newlines' is non-nil, the newline is marked with the
456text-property `hard'.
76c64e24 457With ARG, insert that many newlines.
058d4999 458Call `auto-fill-function' if the current column number is greater
6688f85f 459than the value of `fill-column' and ARG is nil."
30bb9754 460 (interactive "*P")
4c4cbf11 461 (barf-if-buffer-read-only)
e5eddfd1
SM
462 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
463 ;; Set last-command-event to tell self-insert what to insert.
464 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
465 (beforepos (point))
466 (last-command-event ?\n)
467 ;; Don't auto-fill if we have a numeric argument.
468 (auto-fill-function (if arg nil auto-fill-function))
469 (postproc
470 ;; Do the rest in post-self-insert-hook, because we want to do it
471 ;; *before* other functions on that hook.
472 (lambda ()
473 ;; Mark the newline(s) `hard'.
474 (if use-hard-newlines
475 (set-hard-newline-properties
476 (- (point) (prefix-numeric-value arg)) (point)))
477 ;; If the newline leaves the previous line blank, and we
478 ;; have a left margin, delete that from the blank line.
479 (save-excursion
480 (goto-char beforepos)
481 (beginning-of-line)
482 (and (looking-at "[ \t]$")
483 (> (current-left-margin) 0)
484 (delete-region (point)
485 (line-end-position))))
486 ;; Indent the line after the newline, except in one case:
487 ;; when we added the newline at the beginning of a line which
488 ;; starts a page.
489 (or was-page-start
490 (move-to-left-margin nil t)))))
491 (unwind-protect
492 (progn
493 (add-hook 'post-self-insert-hook postproc)
494 (self-insert-command (prefix-numeric-value arg)))
495 ;; We first used let-binding to protect the hook, but that was naive
496 ;; since add-hook affects the symbol-default value of the variable,
497 ;; whereas the let-binding might only protect the buffer-local value.
498 (remove-hook 'post-self-insert-hook postproc)))
30bb9754
BG
499 nil)
500
55741b46
RS
501(defun set-hard-newline-properties (from to)
502 (let ((sticky (get-text-property from 'rear-nonsticky)))
503 (put-text-property from to 'hard 't)
504 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
505 (if (and (listp sticky) (not (memq 'hard sticky)))
506 (put-text-property from (point) 'rear-nonsticky
507 (cons 'hard sticky)))))
eaae8106 508
e249a6d8 509(defun open-line (n)
ff1fbe3e 510 "Insert a newline and leave point before it.
f33321ad
JB
511If there is a fill prefix and/or a `left-margin', insert them
512on the new line if the line would have been blank.
616ed245 513With arg N, insert N newlines."
2076c87c 514 (interactive "*p")
616ed245 515 (let* ((do-fill-prefix (and fill-prefix (bolp)))
3db1e3b5 516 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
c156a63b 517 (loc (point-marker))
207d7545
GM
518 ;; Don't expand an abbrev before point.
519 (abbrev-mode nil))
e249a6d8 520 (newline n)
d133d835 521 (goto-char loc)
e249a6d8 522 (while (> n 0)
d133d835
RS
523 (cond ((bolp)
524 (if do-left-margin (indent-to (current-left-margin)))
525 (if do-fill-prefix (insert-and-inherit fill-prefix))))
526 (forward-line 1)
e249a6d8 527 (setq n (1- n)))
d133d835
RS
528 (goto-char loc)
529 (end-of-line)))
2076c87c 530
da7d231b
KS
531(defun split-line (&optional arg)
532 "Split current line, moving portion beyond point vertically down.
533If the current line starts with `fill-prefix', insert it on the new
f33321ad 534line as well. With prefix ARG, don't insert `fill-prefix' on new line.
da7d231b 535
e249a6d8 536When called from Lisp code, ARG may be a prefix string to copy."
da7d231b 537 (interactive "*P")
2076c87c 538 (skip-chars-forward " \t")
d77bbdc9
RS
539 (let* ((col (current-column))
540 (pos (point))
541 ;; What prefix should we check for (nil means don't).
542 (prefix (cond ((stringp arg) arg)
543 (arg nil)
544 (t fill-prefix)))
545 ;; Does this line start with it?
546 (have-prfx (and prefix
547 (save-excursion
548 (beginning-of-line)
549 (looking-at (regexp-quote prefix))))))
28191e20 550 (newline 1)
d77bbdc9 551 (if have-prfx (insert-and-inherit prefix))
2076c87c
JB
552 (indent-to col 0)
553 (goto-char pos)))
554
2076c87c
JB
555(defun delete-indentation (&optional arg)
556 "Join this line to previous and fix up whitespace at join.
ccc58657 557If there is a fill prefix, delete it from the beginning of this line.
2076c87c
JB
558With argument, join this line to following line."
559 (interactive "*P")
560 (beginning-of-line)
561 (if arg (forward-line 1))
562 (if (eq (preceding-char) ?\n)
563 (progn
564 (delete-region (point) (1- (point)))
ccc58657
RS
565 ;; If the second line started with the fill prefix,
566 ;; delete the prefix.
567 (if (and fill-prefix
01b8e020 568 (<= (+ (point) (length fill-prefix)) (point-max))
ccc58657
RS
569 (string= fill-prefix
570 (buffer-substring (point)
571 (+ (point) (length fill-prefix)))))
572 (delete-region (point) (+ (point) (length fill-prefix))))
2076c87c
JB
573 (fixup-whitespace))))
574
fc025090 575(defalias 'join-line #'delete-indentation) ; easier to find
eaae8106 576
2076c87c
JB
577(defun delete-blank-lines ()
578 "On blank line, delete all surrounding blank lines, leaving just one.
579On isolated blank line, delete that one.
6d30d416 580On nonblank line, delete any immediately following blank lines."
2076c87c
JB
581 (interactive "*")
582 (let (thisblank singleblank)
583 (save-excursion
584 (beginning-of-line)
585 (setq thisblank (looking-at "[ \t]*$"))
70e14c01 586 ;; Set singleblank if there is just one blank line here.
2076c87c
JB
587 (setq singleblank
588 (and thisblank
589 (not (looking-at "[ \t]*\n[ \t]*$"))
590 (or (bobp)
591 (progn (forward-line -1)
592 (not (looking-at "[ \t]*$")))))))
70e14c01 593 ;; Delete preceding blank lines, and this one too if it's the only one.
2076c87c
JB
594 (if thisblank
595 (progn
596 (beginning-of-line)
597 (if singleblank (forward-line 1))
598 (delete-region (point)
599 (if (re-search-backward "[^ \t\n]" nil t)
600 (progn (forward-line 1) (point))
601 (point-min)))))
70e14c01
JB
602 ;; Delete following blank lines, unless the current line is blank
603 ;; and there are no following blank lines.
2076c87c
JB
604 (if (not (and thisblank singleblank))
605 (save-excursion
606 (end-of-line)
607 (forward-line 1)
608 (delete-region (point)
609 (if (re-search-forward "[^ \t\n]" nil t)
610 (progn (beginning-of-line) (point))
70e14c01
JB
611 (point-max)))))
612 ;; Handle the special case where point is followed by newline and eob.
613 ;; Delete the line, leaving point at eob.
614 (if (looking-at "^[ \t]*\n\\'")
615 (delete-region (point) (point-max)))))
2076c87c 616
eaae8106
SS
617(defun delete-trailing-whitespace ()
618 "Delete all the trailing whitespace across the current buffer.
619All whitespace after the last non-whitespace character in a line is deleted.
103db06c
RS
620This respects narrowing, created by \\[narrow-to-region] and friends.
621A formfeed is not considered whitespace by this function."
eaae8106
SS
622 (interactive "*")
623 (save-match-data
624 (save-excursion
625 (goto-char (point-min))
5c9b3fac
MB
626 (while (re-search-forward "\\s-$" nil t)
627 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
3a768251 628 ;; Don't delete formfeeds, even if they are considered whitespace.
661aa5c7
GM
629 (save-match-data
630 (if (looking-at ".*\f")
631 (goto-char (match-end 0))))
7981d89f 632 (delete-region (point) (match-end 0))))))
eaae8106 633
2076c87c
JB
634(defun newline-and-indent ()
635 "Insert a newline, then indent according to major mode.
ff1fbe3e 636Indentation is done using the value of `indent-line-function'.
2076c87c 637In programming language modes, this is the same as TAB.
ff1fbe3e 638In some text modes, where TAB inserts a tab, this command indents to the
eed5698b 639column specified by the function `current-left-margin'."
2076c87c 640 (interactive "*")
5ff4ba3d 641 (delete-horizontal-space t)
46947372 642 (newline)
2076c87c
JB
643 (indent-according-to-mode))
644
645(defun reindent-then-newline-and-indent ()
646 "Reindent current line, insert newline, then indent the new line.
647Indentation of both lines is done according to the current major mode,
ff1fbe3e 648which means calling the current value of `indent-line-function'.
2076c87c
JB
649In programming language modes, this is the same as TAB.
650In some text modes, where TAB inserts a tab, this indents to the
eed5698b 651column specified by the function `current-left-margin'."
2076c87c 652 (interactive "*")
e1e04350
SM
653 (let ((pos (point)))
654 ;; Be careful to insert the newline before indenting the line.
655 ;; Otherwise, the indentation might be wrong.
656 (newline)
657 (save-excursion
658 (goto-char pos)
eb3d6c67
SM
659 ;; We are at EOL before the call to indent-according-to-mode, and
660 ;; after it we usually are as well, but not always. We tried to
661 ;; address it with `save-excursion' but that uses a normal marker
662 ;; whereas we need `move after insertion', so we do the save/restore
663 ;; by hand.
664 (setq pos (copy-marker pos t))
665 (indent-according-to-mode)
666 (goto-char pos)
667 ;; Remove the trailing white-space after indentation because
668 ;; indentation may introduce the whitespace.
6b61353c 669 (delete-horizontal-space t))
e1e04350 670 (indent-according-to-mode)))
eaae8106 671
93be67de
KH
672(defun quoted-insert (arg)
673 "Read next input character and insert it.
674This is useful for inserting control characters.
5626c14e 675With argument, insert ARG copies of the character.
2076c87c 676
93be67de
KH
677If the first character you type after this command is an octal digit,
678you should type a sequence of octal digits which specify a character code.
679Any nondigit terminates the sequence. If the terminator is a RET,
680it is discarded; any other terminator is used itself as input.
681The variable `read-quoted-char-radix' specifies the radix for this feature;
682set it to 10 or 16 to use decimal or hex instead of octal.
dff7d67f 683
93be67de
KH
684In overwrite mode, this function inserts the character anyway, and
685does not handle octal digits specially. This means that if you use
686overwrite as your normal editing mode, you can use this function to
687insert characters when necessary.
dff7d67f 688
93be67de
KH
689In binary overwrite mode, this function does overwrite, and octal
690digits are interpreted as a character code. This is intended to be
691useful for editing binary files."
692 (interactive "*p")
a6c39c14
EZ
693 (let* ((char
694 ;; Avoid "obsolete" warnings for translation-table-for-input.
695 (with-no-warnings
696 (let (translation-table-for-input input-method-function)
697 (if (or (not overwrite-mode)
698 (eq overwrite-mode 'overwrite-mode-binary))
699 (read-quoted-char)
700 (read-char))))))
0e3269e5
JL
701 ;; This used to assume character codes 0240 - 0377 stand for
702 ;; characters in some single-byte character set, and converted them
703 ;; to Emacs characters. But in 23.1 this feature is deprecated
704 ;; in favor of inserting the corresponding Unicode characters.
705 ;; (if (and enable-multibyte-characters
706 ;; (>= char ?\240)
707 ;; (<= char ?\377))
708 ;; (setq char (unibyte-char-to-multibyte char)))
93be67de
KH
709 (if (> arg 0)
710 (if (eq overwrite-mode 'overwrite-mode-binary)
711 (delete-char arg)))
712 (while (> arg 0)
713 (insert-and-inherit char)
714 (setq arg (1- arg)))))
eaae8106 715
6b61353c 716(defun forward-to-indentation (&optional arg)
93be67de 717 "Move forward ARG lines and position at first nonblank character."
109cfe4e 718 (interactive "^p")
6b61353c 719 (forward-line (or arg 1))
93be67de 720 (skip-chars-forward " \t"))
cc2b2b6c 721
6b61353c 722(defun backward-to-indentation (&optional arg)
93be67de 723 "Move backward ARG lines and position at first nonblank character."
109cfe4e 724 (interactive "^p")
6b61353c 725 (forward-line (- (or arg 1)))
93be67de 726 (skip-chars-forward " \t"))
2076c87c 727
93be67de
KH
728(defun back-to-indentation ()
729 "Move point to the first non-whitespace character on this line."
109cfe4e 730 (interactive "^")
93be67de 731 (beginning-of-line 1)
1e96c007 732 (skip-syntax-forward " " (line-end-position))
b9863466
RS
733 ;; Move back over chars that have whitespace syntax but have the p flag.
734 (backward-prefix-chars))
93be67de
KH
735
736(defun fixup-whitespace ()
737 "Fixup white space between objects around point.
738Leave one space or none, according to the context."
739 (interactive "*")
740 (save-excursion
741 (delete-horizontal-space)
742 (if (or (looking-at "^\\|\\s)")
743 (save-excursion (forward-char -1)
744 (looking-at "$\\|\\s(\\|\\s'")))
745 nil
f33321ad 746 (insert ?\s))))
93be67de 747
5ff4ba3d
MB
748(defun delete-horizontal-space (&optional backward-only)
749 "Delete all spaces and tabs around point.
1cfcd2db 750If BACKWARD-ONLY is non-nil, only delete them before point."
a168699d 751 (interactive "*P")
9ab59a1a
MB
752 (let ((orig-pos (point)))
753 (delete-region
754 (if backward-only
755 orig-pos
756 (progn
757 (skip-chars-forward " \t")
758 (constrain-to-field nil orig-pos t)))
5ff4ba3d 759 (progn
9ab59a1a
MB
760 (skip-chars-backward " \t")
761 (constrain-to-field nil orig-pos)))))
93be67de 762
68c16b59 763(defun just-one-space (&optional n)
88b5a757 764 "Delete all spaces and tabs around point, leaving one space (or N spaces).
1c708c1a 765If N is negative, delete newlines as well."
56abefac 766 (interactive "*p")
11c31b99 767 (unless n (setq n 1))
88b5a757
DD
768 (let ((orig-pos (point))
769 (skip-characters (if (< n 0) " \t\n\r" " \t"))
770 (n (abs n)))
771 (skip-chars-backward skip-characters)
9ab59a1a 772 (constrain-to-field nil orig-pos)
68c16b59 773 (dotimes (i (or n 1))
f33321ad 774 (if (= (following-char) ?\s)
56abefac 775 (forward-char 1)
f33321ad 776 (insert ?\s)))
9ab59a1a
MB
777 (delete-region
778 (point)
779 (progn
88b5a757 780 (skip-chars-forward skip-characters)
9ab59a1a 781 (constrain-to-field nil orig-pos t)))))
2d88b556 782\f
2076c87c 783(defun beginning-of-buffer (&optional arg)
8d9f4291 784 "Move point to the beginning of the buffer.
a416e7ef 785With numeric arg N, put point N/10 of the way from the beginning.
8d9f4291
CY
786If the buffer is narrowed, this command uses the beginning of the
787accessible part of the buffer.
c66587fe 788
8d9f4291
CY
789If Transient Mark mode is disabled, leave mark at previous
790position, unless a \\[universal-argument] prefix is supplied.
ff1fbe3e
RS
791
792Don't use this command in Lisp programs!
8d9f4291 793\(goto-char (point-min)) is faster."
109cfe4e 794 (interactive "^P")
24199fe7 795 (or (consp arg)
d34c311a 796 (region-active-p)
705a5933 797 (push-mark))
c66587fe 798 (let ((size (- (point-max) (point-min))))
a416e7ef 799 (goto-char (if (and arg (not (consp arg)))
c66587fe
RS
800 (+ (point-min)
801 (if (> size 10000)
802 ;; Avoid overflow for large buffer sizes!
803 (* (prefix-numeric-value arg)
804 (/ size 10))
805 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
806 (point-min))))
d7e7ecd7 807 (if (and arg (not (consp arg))) (forward-line 1)))
2076c87c
JB
808
809(defun end-of-buffer (&optional arg)
8d9f4291 810 "Move point to the end of the buffer.
a416e7ef 811With numeric arg N, put point N/10 of the way from the end.
8d9f4291
CY
812If the buffer is narrowed, this command uses the end of the
813accessible part of the buffer.
c66587fe 814
8d9f4291
CY
815If Transient Mark mode is disabled, leave mark at previous
816position, unless a \\[universal-argument] prefix is supplied.
ff1fbe3e
RS
817
818Don't use this command in Lisp programs!
8d9f4291 819\(goto-char (point-max)) is faster."
109cfe4e 820 (interactive "^P")
d34c311a 821 (or (consp arg) (region-active-p) (push-mark))
c66587fe 822 (let ((size (- (point-max) (point-min))))
a416e7ef 823 (goto-char (if (and arg (not (consp arg)))
c66587fe
RS
824 (- (point-max)
825 (if (> size 10000)
826 ;; Avoid overflow for large buffer sizes!
827 (* (prefix-numeric-value arg)
828 (/ size 10))
829 (/ (* size (prefix-numeric-value arg)) 10)))
830 (point-max))))
3a801d0c
ER
831 ;; If we went to a place in the middle of the buffer,
832 ;; adjust it to the beginning of a line.
d7e7ecd7 833 (cond ((and arg (not (consp arg))) (forward-line 1))
919f2812 834 ((> (point) (window-end nil t))
314808dc
GM
835 ;; If the end of the buffer is not already on the screen,
836 ;; then scroll specially to put it near, but not at, the bottom.
837 (overlay-recenter (point))
838 (recenter -3))))
2076c87c 839
b9229673
CY
840(defcustom delete-active-region t
841 "Whether single-char deletion commands delete an active region.
842This has an effect only if Transient Mark mode is enabled, and
843affects `delete-forward-char' and `delete-backward-char', though
844not `delete-char'.
845
846If the value is the symbol `kill', the active region is killed
847instead of deleted."
848 :type '(choice (const :tag "Delete active region" t)
849 (const :tag "Kill active region" kill)
850 (const :tag "Do ordinary deletion" nil))
851 :group 'editing
852 :version "24.1")
853
854(defun delete-backward-char (n &optional killflag)
855 "Delete the previous N characters (following if N is negative).
856If Transient Mark mode is enabled, the mark is active, and N is 1,
857delete the text in the region and deactivate the mark instead.
858To disable this, set `delete-active-region' to nil.
859
860Optional second arg KILLFLAG, if non-nil, means to kill (save in
861kill ring) instead of delete. Interactively, N is the prefix
862arg, and KILLFLAG is set if N is explicitly specified.
863
864In Overwrite mode, single character backward deletion may replace
865tabs with spaces so as to back over columns, unless point is at
866the end of the line."
867 (interactive "p\nP")
868 (unless (integerp n)
869 (signal 'wrong-type-argument (list 'integerp n)))
870 (cond ((and (use-region-p)
871 delete-active-region
872 (= n 1))
873 ;; If a region is active, kill or delete it.
874 (if (eq delete-active-region 'kill)
875 (kill-region (region-beginning) (region-end))
876 (delete-region (region-beginning) (region-end))))
877 ;; In Overwrite mode, maybe untabify while deleting
878 ((null (or (null overwrite-mode)
879 (<= n 0)
880 (memq (char-before) '(?\t ?\n))
881 (eobp)
882 (eq (char-after) ?\n)))
883 (let* ((ocol (current-column))
884 (val (delete-char (- n) killflag)))
885 (save-excursion
886 (insert-char ?\s (- ocol (current-column)) nil))))
887 ;; Otherwise, do simple deletion.
888 (t (delete-char (- n) killflag))))
889
890(defun delete-forward-char (n &optional killflag)
4c5130d6 891 "Delete the following N characters (previous if N is negative).
b9229673
CY
892If Transient Mark mode is enabled, the mark is active, and N is 1,
893delete the text in the region and deactivate the mark instead.
894To disable this, set `delete-active-region' to nil.
895
896Optional second arg KILLFLAG non-nil means to kill (save in kill
897ring) instead of delete. Interactively, N is the prefix arg, and
898KILLFLAG is set if N was explicitly specified."
899 (interactive "p\nP")
900 (unless (integerp n)
901 (signal 'wrong-type-argument (list 'integerp n)))
902 (cond ((and (use-region-p)
903 delete-active-region
904 (= n 1))
905 ;; If a region is active, kill or delete it.
906 (if (eq delete-active-region 'kill)
907 (kill-region (region-beginning) (region-end))
908 (delete-region (region-beginning) (region-end))))
909 ;; Otherwise, do simple deletion.
910 (t (delete-char n killflag))))
911
2076c87c 912(defun mark-whole-buffer ()
70e14c01
JB
913 "Put point at beginning and mark at end of buffer.
914You probably should not use this function in Lisp programs;
915it is usually a mistake for a Lisp function to use any subroutine
916that uses or sets the mark."
2076c87c
JB
917 (interactive)
918 (push-mark (point))
fd0f4056 919 (push-mark (point-max) nil t)
2076c87c 920 (goto-char (point-min)))
2d88b556 921\f
eaae8106 922
93be67de
KH
923;; Counting lines, one way or another.
924
9af967bd
LK
925(defun goto-line (line &optional buffer)
926 "Goto LINE, counting from line 1 at beginning of buffer.
927Normally, move point in the current buffer, and leave mark at the
928previous position. With just \\[universal-argument] as argument,
a5785534 929move point in the most recently selected other buffer, and switch to it.
9af967bd 930
a5785534
SM
931If there's a number in the buffer at point, it is the default for LINE.
932
933This function is usually the wrong thing to use in a Lisp program.
934What you probably want instead is something like:
935 (goto-char (point-min)) (forward-line (1- N))
936If at all possible, an even better solution is to use char counts
937rather than line counts."
00a369ac
RS
938 (interactive
939 (if (and current-prefix-arg (not (consp current-prefix-arg)))
940 (list (prefix-numeric-value current-prefix-arg))
941 ;; Look for a default, a number in the buffer at point.
942 (let* ((default
943 (save-excursion
944 (skip-chars-backward "0-9")
945 (if (looking-at "[0-9]")
946 (buffer-substring-no-properties
947 (point)
948 (progn (skip-chars-forward "0-9")
949 (point))))))
950 ;; Decide if we're switching buffers.
951 (buffer
952 (if (consp current-prefix-arg)
953 (other-buffer (current-buffer) t)))
954 (buffer-prompt
955 (if buffer
956 (concat " in " (buffer-name buffer))
957 "")))
958 ;; Read the argument, offering that number (if any) as default.
959 (list (read-from-minibuffer (format (if default "Goto line%s (%s): "
960 "Goto line%s: ")
961 buffer-prompt
962 default)
963 nil nil t
964 'minibuffer-history
965 default)
966 buffer))))
967 ;; Switch to the desired buffer, one way or another.
968 (if buffer
969 (let ((window (get-buffer-window buffer)))
970 (if window (select-window window)
971 (switch-to-buffer-other-window buffer))))
f564644b 972 ;; Leave mark at previous position
d34c311a 973 (or (region-active-p) (push-mark))
00a369ac 974 ;; Move to the specified line number in that buffer.
93be67de
KH
975 (save-restriction
976 (widen)
a5785534 977 (goto-char (point-min))
93be67de 978 (if (eq selective-display t)
9af967bd
LK
979 (re-search-forward "[\n\C-m]" nil 'end (1- line))
980 (forward-line (1- line)))))
2076c87c 981
8da5345f
HN
982(defun count-words-region (start end)
983 "Print the number of words in the region.
984When called interactively, the word count is printed in echo area."
985 (interactive "r")
986 (let ((count 0))
987 (save-excursion
988 (save-restriction
989 (narrow-to-region start end)
990 (goto-char (point-min))
991 (while (forward-word 1)
992 (setq count (1+ count)))))
993 (if (interactive-p)
994 (message "Region has %d words" count))
995 count))
996
2076c87c 997(defun count-lines-region (start end)
eb8c3be9 998 "Print number of lines and characters in the region."
2076c87c
JB
999 (interactive "r")
1000 (message "Region has %d lines, %d characters"
1001 (count-lines start end) (- end start)))
1002
1003(defun what-line ()
2578be76 1004 "Print the current buffer line number and narrowed line number of point."
2076c87c 1005 (interactive)
c6db81aa 1006 (let ((start (point-min))
6b61353c
KH
1007 (n (line-number-at-pos)))
1008 (if (= start 1)
1009 (message "Line %d" n)
1010 (save-excursion
1011 (save-restriction
1012 (widen)
1013 (message "line %d (narrowed line %d)"
1014 (+ n (line-number-at-pos start) -1) n))))))
2578be76 1015
2076c87c
JB
1016(defun count-lines (start end)
1017 "Return number of lines between START and END.
1018This is usually the number of newlines between them,
ff1fbe3e 1019but can be one more if START is not equal to END
2076c87c 1020and the greater of them is not at the start of a line."
e406700d
RS
1021 (save-excursion
1022 (save-restriction
1023 (narrow-to-region start end)
1024 (goto-char (point-min))
1025 (if (eq selective-display t)
1026 (save-match-data
dde92ca6
RS
1027 (let ((done 0))
1028 (while (re-search-forward "[\n\C-m]" nil t 40)
1029 (setq done (+ 40 done)))
1030 (while (re-search-forward "[\n\C-m]" nil t 1)
1031 (setq done (+ 1 done)))
043efc41
RS
1032 (goto-char (point-max))
1033 (if (and (/= start end)
1034 (not (bolp)))
1035 (1+ done)
e406700d
RS
1036 done)))
1037 (- (buffer-size) (forward-line (buffer-size)))))))
eaae8106 1038
6b61353c
KH
1039(defun line-number-at-pos (&optional pos)
1040 "Return (narrowed) buffer line number at position POS.
79ffb765
RS
1041If POS is nil, use current buffer location.
1042Counting starts at (point-min), so the value refers
1043to the contents of the accessible portion of the buffer."
6b61353c
KH
1044 (let ((opoint (or pos (point))) start)
1045 (save-excursion
1046 (goto-char (point-min))
1047 (setq start (point))
1048 (goto-char opoint)
1049 (forward-line 0)
1050 (1+ (count-lines start (point))))))
1051
d5d99b80
KH
1052(defun what-cursor-position (&optional detail)
1053 "Print info on cursor position (on screen and within buffer).
e38dff0c 1054Also describe the character after point, and give its character code
c6fcc518
KH
1055in octal, decimal and hex.
1056
1057For a non-ASCII multibyte character, also give its encoding in the
1058buffer's selected coding system if the coding system encodes the
1059character safely. If the character is encoded into one byte, that
1060code is shown in hex. If the character is encoded into more than one
1061byte, just \"...\" is shown.
e5a902cf 1062
24dad5d5 1063In addition, with prefix argument, show details about that character
0b69eec5 1064in *Help* buffer. See also the command `describe-char'."
d5d99b80 1065 (interactive "P")
2076c87c
JB
1066 (let* ((char (following-char))
1067 (beg (point-min))
1068 (end (point-max))
1069 (pos (point))
1070 (total (buffer-size))
1071 (percent (if (> total 50000)
1072 ;; Avoid overflow from multiplying by 100!
1073 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
1074 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
1075 (hscroll (if (= (window-hscroll) 0)
1076 ""
1077 (format " Hscroll=%d" (window-hscroll))))
1078 (col (current-column)))
1079 (if (= pos end)
1080 (if (or (/= beg 1) (/= end (1+ total)))
a17a79c0 1081 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
2076c87c 1082 pos total percent beg end col hscroll)
a17a79c0 1083 (message "point=%d of %d (EOB) column=%d%s"
63219d53 1084 pos total col hscroll))
c6fcc518 1085 (let ((coding buffer-file-coding-system)
a41b50ca 1086 encoded encoding-msg display-prop under-display)
c6fcc518
KH
1087 (if (or (not coding)
1088 (eq (coding-system-type coding) t))
b56a5ae0 1089 (setq coding (default-value 'buffer-file-coding-system)))
8f924df7 1090 (if (eq (char-charset char) 'eight-bit)
28fd4883 1091 (setq encoding-msg
41882805 1092 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
a41b50ca
KH
1093 ;; Check if the character is displayed with some `display'
1094 ;; text property. In that case, set under-display to the
1095 ;; buffer substring covered by that property.
1096 (setq display-prop (get-text-property pos 'display))
1097 (if display-prop
1098 (let ((to (or (next-single-property-change pos 'display)
1099 (point-max))))
1100 (if (< to (+ pos 4))
1101 (setq under-display "")
1102 (setq under-display "..."
1103 to (+ pos 4)))
1104 (setq under-display
1105 (concat (buffer-substring-no-properties pos to)
1106 under-display)))
1107 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
28fd4883 1108 (setq encoding-msg
a41b50ca
KH
1109 (if display-prop
1110 (if (not (stringp display-prop))
a17a79c0 1111 (format "(%d, #o%o, #x%x, part of display \"%s\")"
a41b50ca 1112 char char char under-display)
a17a79c0 1113 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
a41b50ca
KH
1114 char char char under-display display-prop))
1115 (if encoded
a17a79c0 1116 (format "(%d, #o%o, #x%x, file %s)"
a41b50ca
KH
1117 char char char
1118 (if (> (length encoded) 1)
1119 "..."
1120 (encoded-string-description encoded coding)))
a17a79c0 1121 (format "(%d, #o%o, #x%x)" char char char)))))
e5e89e48 1122 (if detail
24dad5d5 1123 ;; We show the detailed information about CHAR.
0b69eec5 1124 (describe-char (point)))
24dad5d5 1125 (if (or (/= beg 1) (/= end (1+ total)))
a17a79c0 1126 (message "Char: %s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
e5a902cf
KH
1127 (if (< char 256)
1128 (single-key-description char)
f0d16a7f 1129 (buffer-substring-no-properties (point) (1+ (point))))
24dad5d5 1130 encoding-msg pos total percent beg end col hscroll)
a17a79c0 1131 (message "Char: %s %s point=%d of %d (%d%%) column=%d%s"
a41b50ca
KH
1132 (if enable-multibyte-characters
1133 (if (< char 128)
1134 (single-key-description char)
1135 (buffer-substring-no-properties (point) (1+ (point))))
1136 (single-key-description char))
24dad5d5 1137 encoding-msg pos total percent col hscroll))))))
2d88b556 1138\f
71a05b36
RS
1139;; Initialize read-expression-map. It is defined at C level.
1140(let ((m (make-sparse-keymap)))
1141 (define-key m "\M-\t" 'lisp-complete-symbol)
1142 (set-keymap-parent m minibuffer-local-map)
1143 (setq read-expression-map m))
854c16c5 1144
ad6aa5ed
CY
1145(defvar minibuffer-completing-symbol nil
1146 "Non-nil means completing a Lisp symbol in the minibuffer.")
1147
d658acb6
CY
1148(defvar minibuffer-default nil
1149 "The current default value or list of default values in the minibuffer.
1150The functions `read-from-minibuffer' and `completing-read' bind
1151this variable locally.")
1152
b49df39d 1153(defcustom eval-expression-print-level 4
2f7e1f5a 1154 "Value for `print-level' while printing value in `eval-expression'.
d26b26dc 1155A value of nil means no limit."
b49df39d 1156 :group 'lisp
058d4999 1157 :type '(choice (const :tag "No Limit" nil) integer)
b49df39d
RS
1158 :version "21.1")
1159
1160(defcustom eval-expression-print-length 12
2f7e1f5a 1161 "Value for `print-length' while printing value in `eval-expression'.
d26b26dc 1162A value of nil means no limit."
b49df39d 1163 :group 'lisp
058d4999 1164 :type '(choice (const :tag "No Limit" nil) integer)
b49df39d
RS
1165 :version "21.1")
1166
1167(defcustom eval-expression-debug-on-error t
2f7e1f5a 1168 "If non-nil set `debug-on-error' to t in `eval-expression'.
ed8bcabe 1169If nil, don't change the value of `debug-on-error'."
b49df39d
RS
1170 :group 'lisp
1171 :type 'boolean
1172 :version "21.1")
1173
fa219ebd
JL
1174(defun eval-expression-print-format (value)
1175 "Format VALUE as a result of evaluated expression.
1176Return a formatted string which is displayed in the echo area
1177in addition to the value printed by prin1 in functions which
1178display the result of expression evaluation."
1179 (if (and (integerp value)
c9f0110e 1180 (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
fa219ebd 1181 (eq this-command last-command)
56abefac 1182 (if (boundp 'edebug-active) edebug-active)))
fa219ebd 1183 (let ((char-string
9bb25ed3 1184 (if (or (if (boundp 'edebug-active) edebug-active)
3137dda8 1185 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
fa219ebd
JL
1186 (prin1-char value))))
1187 (if char-string
1b5fd09e
SM
1188 (format " (#o%o, #x%x, %s)" value value char-string)
1189 (format " (#o%o, #x%x)" value value)))))
fa219ebd 1190
8570b0ca 1191;; We define this, rather than making `eval' interactive,
ac052b48 1192;; for the sake of completion of names like eval-region, eval-buffer.
ecb7ad00
RS
1193(defun eval-expression (eval-expression-arg
1194 &optional eval-expression-insert-value)
a6a1ee53
EZ
1195 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
1196Value is also consed on to front of the variable `values'.
a7a8618b
EZ
1197Optional argument EVAL-EXPRESSION-INSERT-VALUE non-nil (interactively,
1198with prefix argument) means insert the result into the current buffer
1199instead of printing it in the echo area. Truncates long output
1200according to the value of the variables `eval-expression-print-length'
1201and `eval-expression-print-level'.
b4f73994
RS
1202
1203If `eval-expression-debug-on-error' is non-nil, which is the default,
1204this command arranges for all errors to enter the debugger."
adca5fa6 1205 (interactive
ad6aa5ed
CY
1206 (list (let ((minibuffer-completing-symbol t))
1207 (read-from-minibuffer "Eval: "
1208 nil read-expression-map t
1209 'read-expression-history))
ecb7ad00 1210 current-prefix-arg))
eaae8106 1211
ed8bcabe 1212 (if (null eval-expression-debug-on-error)
a0ee6f27 1213 (push (eval eval-expression-arg lexical-binding) values)
ed8bcabe
GM
1214 (let ((old-value (make-symbol "t")) new-value)
1215 ;; Bind debug-on-error to something unique so that we can
1216 ;; detect when evaled code changes it.
1217 (let ((debug-on-error old-value))
a0ee6f27 1218 (push (eval eval-expression-arg lexical-binding) values)
ed8bcabe
GM
1219 (setq new-value debug-on-error))
1220 ;; If evaled code has changed the value of debug-on-error,
1221 ;; propagate that change to the global binding.
1222 (unless (eq old-value new-value)
1223 (setq debug-on-error new-value))))
eaae8106 1224
b49df39d
RS
1225 (let ((print-length eval-expression-print-length)
1226 (print-level eval-expression-print-level))
6b61353c
KH
1227 (if eval-expression-insert-value
1228 (with-no-warnings
1229 (let ((standard-output (current-buffer)))
22e088c6 1230 (prin1 (car values))))
fa219ebd
JL
1231 (prog1
1232 (prin1 (car values) t)
1233 (let ((str (eval-expression-print-format (car values))))
1234 (if str (princ str t)))))))
2076c87c
JB
1235
1236(defun edit-and-eval-command (prompt command)
1237 "Prompting with PROMPT, let user edit COMMAND and eval result.
1238COMMAND is a Lisp expression. Let user edit that expression in
1239the minibuffer, then read and evaluate the result."
9f4b6084 1240 (let ((command
6b61353c
KH
1241 (let ((print-level nil)
1242 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1243 (unwind-protect
1244 (read-from-minibuffer prompt
1245 (prin1-to-string command)
1246 read-expression-map t
1247 'command-history)
1248 ;; If command was added to command-history as a string,
1249 ;; get rid of that. We want only evaluable expressions there.
1250 (if (stringp (car command-history))
1251 (setq command-history (cdr command-history)))))))
5d6c83ae
KH
1252
1253 ;; If command to be redone does not match front of history,
1254 ;; add it to the history.
1255 (or (equal command (car command-history))
1256 (setq command-history (cons command command-history)))
2076c87c
JB
1257 (eval command)))
1258
ebb61177 1259(defun repeat-complex-command (arg)
2076c87c
JB
1260 "Edit and re-evaluate last complex command, or ARGth from last.
1261A complex command is one which used the minibuffer.
1262The command is placed in the minibuffer as a Lisp form for editing.
1263The result is executed, repeating the command as changed.
5626c14e
JB
1264If the command has been changed or is not the most recent previous
1265command it is added to the front of the command history.
1266You can use the minibuffer history commands \
1267\\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
eb6e9899 1268to get different commands to edit and resubmit."
2076c87c 1269 (interactive "p")
ba343182 1270 (let ((elt (nth (1- arg) command-history))
2076c87c
JB
1271 newcmd)
1272 (if elt
854c16c5 1273 (progn
eab22e27 1274 (setq newcmd
74ae5fab
RS
1275 (let ((print-level nil)
1276 (minibuffer-history-position arg)
99ea24de 1277 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
9f4b6084
MR
1278 (unwind-protect
1279 (read-from-minibuffer
1280 "Redo: " (prin1-to-string elt) read-expression-map t
1281 (cons 'command-history arg))
1282
1283 ;; If command was added to command-history as a
1284 ;; string, get rid of that. We want only
1285 ;; evaluable expressions there.
1286 (if (stringp (car command-history))
1287 (setq command-history (cdr command-history))))))
db16f109
RS
1288
1289 ;; If command to be redone does not match front of history,
1290 ;; add it to the history.
1291 (or (equal newcmd (car command-history))
1292 (setq command-history (cons newcmd command-history)))
2076c87c 1293 (eval newcmd))
536b728a
RS
1294 (if command-history
1295 (error "Argument %d is beyond length of command history" arg)
1296 (error "There are no previous complex commands to repeat")))))
7133b7ee
JL
1297
1298(defun read-extended-command ()
1299 "Read command name to invoke in `execute-extended-command'."
1300 (minibuffer-with-setup-hook
1301 (lambda ()
1302 (set (make-local-variable 'minibuffer-default-add-function)
1303 (lambda ()
1304 ;; Get a command name at point in the original buffer
1305 ;; to propose it after M-n.
1306 (with-current-buffer (window-buffer (minibuffer-selected-window))
1307 (and (commandp (function-called-at-point))
1308 (format "%S" (function-called-at-point)))))))
1309 ;; Read a string, completing from and restricting to the set of
1310 ;; all defined commands. Don't provide any initial input.
1311 ;; Save the command read on the extended-command history list.
1312 (completing-read
1313 (concat (cond
1314 ((eq current-prefix-arg '-) "- ")
1315 ((and (consp current-prefix-arg)
1316 (eq (car current-prefix-arg) 4)) "C-u ")
1317 ((and (consp current-prefix-arg)
1318 (integerp (car current-prefix-arg)))
1319 (format "%d " (car current-prefix-arg)))
1320 ((integerp current-prefix-arg)
1321 (format "%d " current-prefix-arg)))
1322 ;; This isn't strictly correct if `execute-extended-command'
1323 ;; is bound to anything else (e.g. [menu]).
1324 ;; It could use (key-description (this-single-command-keys)),
1325 ;; but actually a prompt other than "M-x" would be confusing,
1326 ;; because "M-x" is a well-known prompt to read a command
1327 ;; and it serves as a shorthand for "Extended command: ".
1328 "M-x ")
1329 obarray 'commandp t nil 'extended-command-history)))
1330
2d88b556 1331\f
854c16c5
RS
1332(defvar minibuffer-history nil
1333 "Default minibuffer history list.
1334This is used for all minibuffer input
e5f0c02f
EZ
1335except when an alternate history list is specified.
1336
1337Maximum length of the history list is determined by the value
1338of `history-length', which see.")
854c16c5 1339(defvar minibuffer-history-sexp-flag nil
6b61353c
KH
1340 "Control whether history list elements are expressions or strings.
1341If the value of this variable equals current minibuffer depth,
1342they are expressions; otherwise they are strings.
7979163c 1343\(That convention is designed to do the right thing for
6b61353c 1344recursive uses of the minibuffer.)")
e91f80c4 1345(setq minibuffer-history-variable 'minibuffer-history)
535c8bdb 1346(setq minibuffer-history-position nil) ;; Defvar is in C code.
854c16c5 1347(defvar minibuffer-history-search-history nil)
e91f80c4 1348
93cee14b
RS
1349(defvar minibuffer-text-before-history nil
1350 "Text that was in this minibuffer before any history commands.
1351This is nil if there have not yet been any history commands
1352in this use of the minibuffer.")
1353
1354(add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1355
1356(defun minibuffer-history-initialize ()
1357 (setq minibuffer-text-before-history nil))
1358
6e7d0ff7
MB
1359(defun minibuffer-avoid-prompt (new old)
1360 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1361 (constrain-to-field nil (point-max)))
1362
6e30a99a 1363(defcustom minibuffer-history-case-insensitive-variables nil
1d2b0303 1364 "Minibuffer history variables for which matching should ignore case.
6e30a99a
RS
1365If a history variable is a member of this list, then the
1366\\[previous-matching-history-element] and \\[next-matching-history-element]\
1367 commands ignore case when searching it, regardless of `case-fold-search'."
1368 :type '(repeat variable)
1369 :group 'minibuffer)
1370
e91f80c4 1371(defun previous-matching-history-element (regexp n)
854c16c5
RS
1372 "Find the previous history element that matches REGEXP.
1373\(Previous history elements refer to earlier actions.)
1374With prefix argument N, search for Nth previous match.
5c2010f0 1375If N is negative, find the next or Nth next match.
9889af08
EZ
1376Normally, history elements are matched case-insensitively if
1377`case-fold-search' is non-nil, but an uppercase letter in REGEXP
1378makes the search case-sensitive.
6e30a99a 1379See also `minibuffer-history-case-insensitive-variables'."
854c16c5 1380 (interactive
c1172a19 1381 (let* ((enable-recursive-minibuffers t)
c1172a19
RS
1382 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1383 nil
1384 minibuffer-local-map
1385 nil
5794c45d
RS
1386 'minibuffer-history-search-history
1387 (car minibuffer-history-search-history))))
c1172a19
RS
1388 ;; Use the last regexp specified, by default, if input is empty.
1389 (list (if (string= regexp "")
a8e96cea
KH
1390 (if minibuffer-history-search-history
1391 (car minibuffer-history-search-history)
1392 (error "No previous history search regexp"))
c1172a19 1393 regexp)
854c16c5 1394 (prefix-numeric-value current-prefix-arg))))
e276a14a
MB
1395 (unless (zerop n)
1396 (if (and (zerop minibuffer-history-position)
1397 (null minibuffer-text-before-history))
efaac2e6 1398 (setq minibuffer-text-before-history
6d74d713 1399 (minibuffer-contents-no-properties)))
e276a14a
MB
1400 (let ((history (symbol-value minibuffer-history-variable))
1401 (case-fold-search
1402 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1403 ;; On some systems, ignore case for file names.
1404 (if (memq minibuffer-history-variable
1405 minibuffer-history-case-insensitive-variables)
1406 t
1407 ;; Respect the user's setting for case-fold-search:
1408 case-fold-search)
1409 nil))
1410 prevpos
1411 match-string
1412 match-offset
1413 (pos minibuffer-history-position))
1414 (while (/= n 0)
1415 (setq prevpos pos)
1416 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1417 (when (= pos prevpos)
e91f80c4 1418 (error (if (= pos 1)
ccc58657
RS
1419 "No later matching history item"
1420 "No earlier matching history item")))
e276a14a
MB
1421 (setq match-string
1422 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
7908d27c 1423 (let ((print-level nil))
e276a14a
MB
1424 (prin1-to-string (nth (1- pos) history)))
1425 (nth (1- pos) history)))
1426 (setq match-offset
1427 (if (< n 0)
1428 (and (string-match regexp match-string)
1429 (match-end 0))
1430 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1431 (match-beginning 1))))
1432 (when match-offset
1433 (setq n (+ n (if (< n 0) 1 -1)))))
1434 (setq minibuffer-history-position pos)
1435 (goto-char (point-max))
efaac2e6 1436 (delete-minibuffer-contents)
e276a14a 1437 (insert match-string)
6d74d713 1438 (goto-char (+ (minibuffer-prompt-end) match-offset))))
e1e04350
SM
1439 (if (memq (car (car command-history)) '(previous-matching-history-element
1440 next-matching-history-element))
854c16c5 1441 (setq command-history (cdr command-history))))
e91f80c4 1442
e91f80c4 1443(defun next-matching-history-element (regexp n)
854c16c5
RS
1444 "Find the next history element that matches REGEXP.
1445\(The next history element refers to a more recent action.)
1446With prefix argument N, search for Nth next match.
5c2010f0 1447If N is negative, find the previous or Nth previous match.
9889af08
EZ
1448Normally, history elements are matched case-insensitively if
1449`case-fold-search' is non-nil, but an uppercase letter in REGEXP
1450makes the search case-sensitive."
854c16c5 1451 (interactive
c1172a19 1452 (let* ((enable-recursive-minibuffers t)
c1172a19
RS
1453 (regexp (read-from-minibuffer "Next element matching (regexp): "
1454 nil
1455 minibuffer-local-map
1456 nil
e967cd11
RS
1457 'minibuffer-history-search-history
1458 (car minibuffer-history-search-history))))
c1172a19
RS
1459 ;; Use the last regexp specified, by default, if input is empty.
1460 (list (if (string= regexp "")
e967cd11
RS
1461 (if minibuffer-history-search-history
1462 (car minibuffer-history-search-history)
1463 (error "No previous history search regexp"))
c1172a19 1464 regexp)
854c16c5 1465 (prefix-numeric-value current-prefix-arg))))
e91f80c4 1466 (previous-matching-history-element regexp (- n)))
2076c87c 1467
8dc3ba7d
MB
1468(defvar minibuffer-temporary-goal-position nil)
1469
7f914bbe 1470(defvar minibuffer-default-add-function 'minibuffer-default-add-completions
0eb5f40f
JL
1471 "Function run by `goto-history-element' before consuming default values.
1472This is useful to dynamically add more elements to the list of default values
7f914bbe
JL
1473when `goto-history-element' reaches the end of this list.
1474Before calling this function `goto-history-element' sets the variable
1475`minibuffer-default-add-done' to t, so it will call this function only
1476once. In special cases, when this function needs to be called more
1477than once, it can set `minibuffer-default-add-done' to nil explicitly,
1478overriding the setting of this variable to t in `goto-history-element'.")
1479
1480(defvar minibuffer-default-add-done nil
1481 "When nil, add more elements to the end of the list of default values.
1482The value nil causes `goto-history-element' to add more elements to
1483the list of defaults when it reaches the end of this list. It does
1484this by calling a function defined by `minibuffer-default-add-function'.")
1485
1486(make-variable-buffer-local 'minibuffer-default-add-done)
1487
1488(defun minibuffer-default-add-completions ()
1489 "Return a list of all completions without the default value.
1490This function is used to add all elements of the completion table to
1491the end of the list of defaults just after the default value."
7f914bbe
JL
1492 (let ((def minibuffer-default)
1493 (all (all-completions ""
1494 minibuffer-completion-table
e96d62cd 1495 minibuffer-completion-predicate)))
7f914bbe
JL
1496 (if (listp def)
1497 (append def all)
1498 (cons def (delete def all)))))
1499
297b8ccd
JL
1500(defun goto-history-element (nabs)
1501 "Puts element of the minibuffer history in the minibuffer.
1502The argument NABS specifies the absolute history position."
1503 (interactive "p")
7f914bbe
JL
1504 (when (and (not minibuffer-default-add-done)
1505 (functionp minibuffer-default-add-function)
1506 (< nabs (- (if (listp minibuffer-default)
1507 (length minibuffer-default)
1508 1))))
1509 (setq minibuffer-default-add-done t
1510 minibuffer-default (funcall minibuffer-default-add-function)))
b38fc7f1
JL
1511 (let ((minimum (if minibuffer-default
1512 (- (if (listp minibuffer-default)
1513 (length minibuffer-default)
1514 1))
1515 0))
297b8ccd
JL
1516 elt minibuffer-returned-to-present)
1517 (if (and (zerop minibuffer-history-position)
1518 (null minibuffer-text-before-history))
1519 (setq minibuffer-text-before-history
1520 (minibuffer-contents-no-properties)))
1521 (if (< nabs minimum)
1522 (if minibuffer-default
7f914bbe 1523 (error "End of defaults; no next item")
297b8ccd
JL
1524 (error "End of history; no default available")))
1525 (if (> nabs (length (symbol-value minibuffer-history-variable)))
1526 (error "Beginning of history; no preceding item"))
1527 (unless (memq last-command '(next-history-element
1528 previous-history-element))
1529 (let ((prompt-end (minibuffer-prompt-end)))
1530 (set (make-local-variable 'minibuffer-temporary-goal-position)
1531 (cond ((<= (point) prompt-end) prompt-end)
1532 ((eobp) nil)
1533 (t (point))))))
1534 (goto-char (point-max))
1535 (delete-minibuffer-contents)
1536 (setq minibuffer-history-position nabs)
b38fc7f1
JL
1537 (cond ((< nabs 0)
1538 (setq elt (if (listp minibuffer-default)
1539 (nth (1- (abs nabs)) minibuffer-default)
1540 minibuffer-default)))
297b8ccd
JL
1541 ((= nabs 0)
1542 (setq elt (or minibuffer-text-before-history ""))
1543 (setq minibuffer-returned-to-present t)
1544 (setq minibuffer-text-before-history nil))
1545 (t (setq elt (nth (1- minibuffer-history-position)
1546 (symbol-value minibuffer-history-variable)))))
1547 (insert
1548 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1549 (not minibuffer-returned-to-present))
1550 (let ((print-level nil))
1551 (prin1-to-string elt))
1552 elt))
1553 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
1554
ebb61177 1555(defun next-history-element (n)
1459a43b
RS
1556 "Puts next element of the minibuffer history in the minibuffer.
1557With argument N, it uses the Nth following element."
2076c87c 1558 (interactive "p")
0818b15e 1559 (or (zerop n)
297b8ccd 1560 (goto-history-element (- minibuffer-history-position n))))
2076c87c 1561
ebb61177 1562(defun previous-history-element (n)
1459a43b
RS
1563 "Puts previous element of the minibuffer history in the minibuffer.
1564With argument N, it uses the Nth previous element."
2076c87c 1565 (interactive "p")
297b8ccd
JL
1566 (or (zerop n)
1567 (goto-history-element (+ minibuffer-history-position n))))
d0678801
RM
1568
1569(defun next-complete-history-element (n)
a4d1159b
GM
1570 "Get next history element which completes the minibuffer before the point.
1571The contents of the minibuffer after the point are deleted, and replaced
1572by the new completion."
d0678801 1573 (interactive "p")
b5e6f936
RM
1574 (let ((point-at-start (point)))
1575 (next-matching-history-element
a4d1159b 1576 (concat
efaac2e6 1577 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
a4d1159b 1578 n)
b5e6f936
RM
1579 ;; next-matching-history-element always puts us at (point-min).
1580 ;; Move to the position we were at before changing the buffer contents.
1581 ;; This is still sensical, because the text before point has not changed.
1582 (goto-char point-at-start)))
d0678801
RM
1583
1584(defun previous-complete-history-element (n)
1f6fcec3 1585 "\
a4d1159b
GM
1586Get previous history element which completes the minibuffer before the point.
1587The contents of the minibuffer after the point are deleted, and replaced
1588by the new completion."
d0678801
RM
1589 (interactive "p")
1590 (next-complete-history-element (- n)))
a4d1159b 1591
efaac2e6 1592;; For compatibility with the old subr of the same name.
a4d1159b
GM
1593(defun minibuffer-prompt-width ()
1594 "Return the display width of the minibuffer prompt.
f33321ad 1595Return 0 if current buffer is not a minibuffer."
a4d1159b
GM
1596 ;; Return the width of everything before the field at the end of
1597 ;; the buffer; this should be 0 for normal buffers.
efaac2e6 1598 (1- (minibuffer-prompt-end)))
2d88b556 1599\f
297b8ccd
JL
1600;; isearch minibuffer history
1601(add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
1602
1603(defvar minibuffer-history-isearch-message-overlay)
1604(make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
1605
1606(defun minibuffer-history-isearch-setup ()
1607 "Set up a minibuffer for using isearch to search the minibuffer history.
1608Intended to be added to `minibuffer-setup-hook'."
1609 (set (make-local-variable 'isearch-search-fun-function)
1610 'minibuffer-history-isearch-search)
1611 (set (make-local-variable 'isearch-message-function)
1612 'minibuffer-history-isearch-message)
1613 (set (make-local-variable 'isearch-wrap-function)
1614 'minibuffer-history-isearch-wrap)
1615 (set (make-local-variable 'isearch-push-state-function)
1616 'minibuffer-history-isearch-push-state)
1617 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
1618
1619(defun minibuffer-history-isearch-end ()
1620 "Clean up the minibuffer after terminating isearch in the minibuffer."
1621 (if minibuffer-history-isearch-message-overlay
1622 (delete-overlay minibuffer-history-isearch-message-overlay)))
1623
1624(defun minibuffer-history-isearch-search ()
1625 "Return the proper search function, for isearch in minibuffer history."
1626 (cond
1627 (isearch-word
1628 (if isearch-forward 'word-search-forward 'word-search-backward))
1629 (t
1630 (lambda (string bound noerror)
1631 (let ((search-fun
1632 ;; Use standard functions to search within minibuffer text
1633 (cond
1634 (isearch-regexp
1635 (if isearch-forward 're-search-forward 're-search-backward))
1636 (t
1637 (if isearch-forward 'search-forward 'search-backward))))
1638 found)
1639 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
1640 ;; searching forward. Lazy-highlight calls this lambda with the
1641 ;; bound arg, so skip the minibuffer prompt.
1642 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
1643 (goto-char (minibuffer-prompt-end)))
1644 (or
1645 ;; 1. First try searching in the initial minibuffer text
1646 (funcall search-fun string
1647 (if isearch-forward bound (minibuffer-prompt-end))
1648 noerror)
1649 ;; 2. If the above search fails, start putting next/prev history
1650 ;; elements in the minibuffer successively, and search the string
1651 ;; in them. Do this only when bound is nil (i.e. not while
1652 ;; lazy-highlighting search strings in the current minibuffer text).
1653 (unless bound
1654 (condition-case nil
1655 (progn
1656 (while (not found)
1657 (cond (isearch-forward
1658 (next-history-element 1)
1659 (goto-char (minibuffer-prompt-end)))
1660 (t
1661 (previous-history-element 1)
1662 (goto-char (point-max))))
1663 (setq isearch-barrier (point) isearch-opoint (point))
1664 ;; After putting the next/prev history element, search
1665 ;; the string in them again, until next-history-element
1666 ;; or previous-history-element raises an error at the
1667 ;; beginning/end of history.
1668 (setq found (funcall search-fun string
1669 (unless isearch-forward
1670 ;; For backward search, don't search
1671 ;; in the minibuffer prompt
1672 (minibuffer-prompt-end))
1673 noerror)))
1674 ;; Return point of the new search result
1675 (point))
1676 ;; Return nil when next(prev)-history-element fails
1677 (error nil)))))))))
1678
1679(defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
1680 "Display the minibuffer history search prompt.
1681If there are no search errors, this function displays an overlay with
1682the isearch prompt which replaces the original minibuffer prompt.
1683Otherwise, it displays the standard isearch message returned from
1684`isearch-message'."
1685 (if (not (and (minibufferp) isearch-success (not isearch-error)))
1686 ;; Use standard function `isearch-message' when not in the minibuffer,
1687 ;; or search fails, or has an error (like incomplete regexp).
1688 ;; This function overwrites minibuffer text with isearch message,
1689 ;; so it's possible to see what is wrong in the search string.
1690 (isearch-message c-q-hack ellipsis)
1691 ;; Otherwise, put the overlay with the standard isearch prompt over
1692 ;; the initial minibuffer prompt.
1693 (if (overlayp minibuffer-history-isearch-message-overlay)
1694 (move-overlay minibuffer-history-isearch-message-overlay
1695 (point-min) (minibuffer-prompt-end))
1696 (setq minibuffer-history-isearch-message-overlay
1697 (make-overlay (point-min) (minibuffer-prompt-end)))
1698 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
1699 (overlay-put minibuffer-history-isearch-message-overlay
1700 'display (isearch-message-prefix c-q-hack ellipsis))
1701 ;; And clear any previous isearch message.
1702 (message "")))
1703
1704(defun minibuffer-history-isearch-wrap ()
1d2b0303 1705 "Wrap the minibuffer history search when search fails.
297b8ccd
JL
1706Move point to the first history element for a forward search,
1707or to the last history element for a backward search."
1708 (unless isearch-word
1709 ;; When `minibuffer-history-isearch-search' fails on reaching the
1710 ;; beginning/end of the history, wrap the search to the first/last
1711 ;; minibuffer history element.
1712 (if isearch-forward
1713 (goto-history-element (length (symbol-value minibuffer-history-variable)))
1714 (goto-history-element 0))
1715 (setq isearch-success t))
1716 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
1717
1718(defun minibuffer-history-isearch-push-state ()
1719 "Save a function restoring the state of minibuffer history search.
1720Save `minibuffer-history-position' to the additional state parameter
1721in the search status stack."
1722 `(lambda (cmd)
1723 (minibuffer-history-isearch-pop-state cmd ,minibuffer-history-position)))
1724
1725(defun minibuffer-history-isearch-pop-state (cmd hist-pos)
1726 "Restore the minibuffer history search state.
5626c14e 1727Go to the history element by the absolute history position HIST-POS."
297b8ccd
JL
1728 (goto-history-element hist-pos))
1729
1730\f
2076c87c 1731;Put this on C-x u, so we can force that rather than C-_ into startup msg
8cb95edf 1732(define-obsolete-function-alias 'advertised-undo 'undo "23.2")
2076c87c 1733
1e96c007 1734(defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
713c9020
RS
1735 "Table mapping redo records to the corresponding undo one.
1736A redo record for undo-in-region maps to t.
1737A redo record for ordinary undo maps to the following (earlier) undo.")
1e96c007
SM
1738
1739(defvar undo-in-region nil
1740 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1741
1742(defvar undo-no-redo nil
1743 "If t, `undo' doesn't go through redo entries.")
1744
a7fe694c
RS
1745(defvar pending-undo-list nil
1746 "Within a run of consecutive undo commands, list remaining to be undone.
8ac28be5 1747If t, we undid all the way to the end of it.")
a7fe694c 1748
2076c87c
JB
1749(defun undo (&optional arg)
1750 "Undo some previous changes.
1751Repeat this command to undo more changes.
5626c14e 1752A numeric ARG serves as a repeat count.
65627aad 1753
3c1b77ca 1754In Transient Mark mode when the mark is active, only undo changes within
1e96c007 1755the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
3c1b77ca 1756as an argument limits undo to changes within the current region."
65627aad 1757 (interactive "*P")
2e033693
RS
1758 ;; Make last-command indicate for the next command that this was an undo.
1759 ;; That way, another undo will undo more.
1760 ;; If we get to the end of the undo history and get an error,
1761 ;; another undo command will find the undo history empty
1762 ;; and will get another error. To begin undoing the undos,
1763 ;; you must type some other command.
b553cffa 1764 (let ((modified (buffer-modified-p))
cb3b2ec0
RS
1765 (recent-save (recent-auto-save-p))
1766 message)
6b61353c
KH
1767 ;; If we get an error in undo-start,
1768 ;; the next command should not be a "consecutive undo".
1769 ;; So set `this-command' to something other than `undo'.
1770 (setq this-command 'undo-start)
1771
e967cd11 1772 (unless (and (eq last-command 'undo)
a7fe694c
RS
1773 (or (eq pending-undo-list t)
1774 ;; If something (a timer or filter?) changed the buffer
1775 ;; since the previous command, don't continue the undo seq.
1776 (let ((list buffer-undo-list))
1777 (while (eq (car list) nil)
1778 (setq list (cdr list)))
1779 ;; If the last undo record made was made by undo
1780 ;; it shows nothing else happened in between.
1781 (gethash list undo-equiv-table))))
1e96c007 1782 (setq undo-in-region
d34c311a 1783 (or (region-active-p) (and arg (not (numberp arg)))))
1e96c007 1784 (if undo-in-region
3c1b77ca
MB
1785 (undo-start (region-beginning) (region-end))
1786 (undo-start))
1787 ;; get rid of initial undo boundary
1788 (undo-more 1))
9a1120ea 1789 ;; If we got this far, the next command should be a consecutive undo.
6b61353c 1790 (setq this-command 'undo)
1e96c007
SM
1791 ;; Check to see whether we're hitting a redo record, and if
1792 ;; so, ask the user whether she wants to skip the redo/undo pair.
1793 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
1794 (or (eq (selected-window) (minibuffer-window))
cb3b2ec0
RS
1795 (setq message (if undo-in-region
1796 (if equiv "Redo in region!" "Undo in region!")
1797 (if equiv "Redo!" "Undo!"))))
0047373b 1798 (when (and (consp equiv) undo-no-redo)
1e96c007
SM
1799 ;; The equiv entry might point to another redo record if we have done
1800 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1801 (while (let ((next (gethash equiv undo-equiv-table)))
1802 (if next (setq equiv next))))
1803 (setq pending-undo-list equiv)))
3c1b77ca 1804 (undo-more
d34c311a 1805 (if (numberp arg)
3c1b77ca
MB
1806 (prefix-numeric-value arg)
1807 1))
1e96c007 1808 ;; Record the fact that the just-generated undo records come from an
713c9020
RS
1809 ;; undo operation--that is, they are redo records.
1810 ;; In the ordinary case (not within a region), map the redo
1811 ;; record to the following undos.
1e96c007 1812 ;; I don't know how to do that in the undo-in-region case.
86f0d932
SM
1813 (let ((list buffer-undo-list))
1814 ;; Strip any leading undo boundaries there might be, like we do
1815 ;; above when checking.
1816 (while (eq (car list) nil)
1817 (setq list (cdr list)))
1818 (puthash list (if undo-in-region t pending-undo-list)
1819 undo-equiv-table))
2512c9f0
RS
1820 ;; Don't specify a position in the undo record for the undo command.
1821 ;; Instead, undoing this should move point to where the change is.
1822 (let ((tail buffer-undo-list)
003550c5
GM
1823 (prev nil))
1824 (while (car tail)
1825 (when (integerp (car tail))
1826 (let ((pos (car tail)))
1e96c007
SM
1827 (if prev
1828 (setcdr prev (cdr tail))
1829 (setq buffer-undo-list (cdr tail)))
003550c5
GM
1830 (setq tail (cdr tail))
1831 (while (car tail)
1832 (if (eq pos (car tail))
1833 (if prev
1834 (setcdr prev (cdr tail))
1835 (setq buffer-undo-list (cdr tail)))
1836 (setq prev tail))
1837 (setq tail (cdr tail)))
1838 (setq tail nil)))
1839 (setq prev tail tail (cdr tail))))
e967cd11
RS
1840 ;; Record what the current undo list says,
1841 ;; so the next command can tell if the buffer was modified in between.
2076c87c 1842 (and modified (not (buffer-modified-p))
cb3b2ec0
RS
1843 (delete-auto-save-file-if-necessary recent-save))
1844 ;; Display a message announcing success.
1845 (if message
f6e7ec02 1846 (message "%s" message))))
2076c87c 1847
e967cd11
RS
1848(defun buffer-disable-undo (&optional buffer)
1849 "Make BUFFER stop keeping undo information.
1850No argument or nil as argument means do this for the current buffer."
1851 (interactive)
0d808a63 1852 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
d020fce0 1853 (setq buffer-undo-list t)))
e967cd11 1854
1e96c007
SM
1855(defun undo-only (&optional arg)
1856 "Undo some previous changes.
1857Repeat this command to undo more changes.
5626c14e 1858A numeric ARG serves as a repeat count.
1e96c007
SM
1859Contrary to `undo', this will not redo a previous undo."
1860 (interactive "*p")
1861 (let ((undo-no-redo t)) (undo arg)))
1e96c007 1862
52d1110d
RS
1863(defvar undo-in-progress nil
1864 "Non-nil while performing an undo.
1865Some change-hooks test this variable to do something different.")
1866
8ac28be5 1867(defun undo-more (n)
2076c87c 1868 "Undo back N undo-boundaries beyond what was already undone recently.
ff1fbe3e
RS
1869Call `undo-start' to get ready to undo recent changes,
1870then call `undo-more' one or more times to undo them."
a7fe694c 1871 (or (listp pending-undo-list)
8ac28be5 1872 (error (concat "No further undo information"
00fa4024 1873 (and undo-in-region " for region"))))
52d1110d 1874 (let ((undo-in-progress t))
b553f685
AM
1875 ;; Note: The following, while pulling elements off
1876 ;; `pending-undo-list' will call primitive change functions which
1877 ;; will push more elements onto `buffer-undo-list'.
8ac28be5 1878 (setq pending-undo-list (primitive-undo n pending-undo-list))
a7fe694c
RS
1879 (if (null pending-undo-list)
1880 (setq pending-undo-list t))))
2076c87c 1881
65627aad
RS
1882;; Deep copy of a list
1883(defun undo-copy-list (list)
1884 "Make a copy of undo list LIST."
1885 (mapcar 'undo-copy-list-1 list))
1886
1887(defun undo-copy-list-1 (elt)
1888 (if (consp elt)
1889 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1890 elt))
1891
1892(defun undo-start (&optional beg end)
1893 "Set `pending-undo-list' to the front of the undo list.
1894The next call to `undo-more' will undo the most recently made change.
1895If BEG and END are specified, then only undo elements
1896that apply to text between BEG and END are used; other undo elements
1897are ignored. If BEG and END are nil, all undo elements are used."
1898 (if (eq buffer-undo-list t)
1899 (error "No undo information in this buffer"))
1e722f9f 1900 (setq pending-undo-list
65627aad
RS
1901 (if (and beg end (not (= beg end)))
1902 (undo-make-selective-list (min beg end) (max beg end))
1903 buffer-undo-list)))
1904
1905(defvar undo-adjusted-markers)
1906
1907(defun undo-make-selective-list (start end)
1908 "Return a list of undo elements for the region START to END.
1909The elements come from `buffer-undo-list', but we keep only
1910the elements inside this region, and discard those outside this region.
1911If we find an element that crosses an edge of this region,
1912we stop and ignore all further elements."
1913 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1914 (undo-list (list nil))
1915 undo-adjusted-markers
1916 some-rejected
1917 undo-elt undo-elt temp-undo-list delta)
1918 (while undo-list-copy
1919 (setq undo-elt (car undo-list-copy))
1920 (let ((keep-this
1921 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1922 ;; This is a "was unmodified" element.
1923 ;; Keep it if we have kept everything thus far.
1924 (not some-rejected))
1925 (t
1926 (undo-elt-in-region undo-elt start end)))))
1927 (if keep-this
1928 (progn
1929 (setq end (+ end (cdr (undo-delta undo-elt))))
1930 ;; Don't put two nils together in the list
1931 (if (not (and (eq (car undo-list) nil)
1932 (eq undo-elt nil)))
1933 (setq undo-list (cons undo-elt undo-list))))
1934 (if (undo-elt-crosses-region undo-elt start end)
1935 (setq undo-list-copy nil)
1936 (setq some-rejected t)
1937 (setq temp-undo-list (cdr undo-list-copy))
1938 (setq delta (undo-delta undo-elt))
1939
1940 (when (/= (cdr delta) 0)
1941 (let ((position (car delta))
1942 (offset (cdr delta)))
1943
e1e04350
SM
1944 ;; Loop down the earlier events adjusting their buffer
1945 ;; positions to reflect the fact that a change to the buffer
1946 ;; isn't being undone. We only need to process those element
1947 ;; types which undo-elt-in-region will return as being in
1948 ;; the region since only those types can ever get into the
1949 ;; output
65627aad
RS
1950
1951 (while temp-undo-list
1952 (setq undo-elt (car temp-undo-list))
1953 (cond ((integerp undo-elt)
1954 (if (>= undo-elt position)
1955 (setcar temp-undo-list (- undo-elt offset))))
1956 ((atom undo-elt) nil)
1957 ((stringp (car undo-elt))
1958 ;; (TEXT . POSITION)
1959 (let ((text-pos (abs (cdr undo-elt)))
1960 (point-at-end (< (cdr undo-elt) 0 )))
1961 (if (>= text-pos position)
1e722f9f 1962 (setcdr undo-elt (* (if point-at-end -1 1)
65627aad
RS
1963 (- text-pos offset))))))
1964 ((integerp (car undo-elt))
1965 ;; (BEGIN . END)
1966 (when (>= (car undo-elt) position)
1967 (setcar undo-elt (- (car undo-elt) offset))
1968 (setcdr undo-elt (- (cdr undo-elt) offset))))
1969 ((null (car undo-elt))
1970 ;; (nil PROPERTY VALUE BEG . END)
1971 (let ((tail (nthcdr 3 undo-elt)))
1972 (when (>= (car tail) position)
1973 (setcar tail (- (car tail) offset))
1974 (setcdr tail (- (cdr tail) offset))))))
1975 (setq temp-undo-list (cdr temp-undo-list))))))))
1976 (setq undo-list-copy (cdr undo-list-copy)))
1977 (nreverse undo-list)))
1978
1979(defun undo-elt-in-region (undo-elt start end)
1980 "Determine whether UNDO-ELT falls inside the region START ... END.
1981If it crosses the edge, we return nil."
1982 (cond ((integerp undo-elt)
1983 (and (>= undo-elt start)
12a93712 1984 (<= undo-elt end)))
65627aad
RS
1985 ((eq undo-elt nil)
1986 t)
1987 ((atom undo-elt)
1988 nil)
1989 ((stringp (car undo-elt))
1990 ;; (TEXT . POSITION)
1991 (and (>= (abs (cdr undo-elt)) start)
1992 (< (abs (cdr undo-elt)) end)))
1993 ((and (consp undo-elt) (markerp (car undo-elt)))
1994 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1995 ;; See if MARKER is inside the region.
1996 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1997 (unless alist-elt
1998 (setq alist-elt (cons (car undo-elt)
1999 (marker-position (car undo-elt))))
2000 (setq undo-adjusted-markers
2001 (cons alist-elt undo-adjusted-markers)))
2002 (and (cdr alist-elt)
2003 (>= (cdr alist-elt) start)
12a93712 2004 (<= (cdr alist-elt) end))))
65627aad
RS
2005 ((null (car undo-elt))
2006 ;; (nil PROPERTY VALUE BEG . END)
2007 (let ((tail (nthcdr 3 undo-elt)))
2008 (and (>= (car tail) start)
12a93712 2009 (<= (cdr tail) end))))
65627aad
RS
2010 ((integerp (car undo-elt))
2011 ;; (BEGIN . END)
2012 (and (>= (car undo-elt) start)
12a93712 2013 (<= (cdr undo-elt) end)))))
65627aad
RS
2014
2015(defun undo-elt-crosses-region (undo-elt start end)
2016 "Test whether UNDO-ELT crosses one edge of that region START ... END.
2017This assumes we have already decided that UNDO-ELT
2018is not *inside* the region START...END."
2019 (cond ((atom undo-elt) nil)
2020 ((null (car undo-elt))
2021 ;; (nil PROPERTY VALUE BEG . END)
2022 (let ((tail (nthcdr 3 undo-elt)))
1f8a132d
RS
2023 (and (< (car tail) end)
2024 (> (cdr tail) start))))
65627aad
RS
2025 ((integerp (car undo-elt))
2026 ;; (BEGIN . END)
1f8a132d
RS
2027 (and (< (car undo-elt) end)
2028 (> (cdr undo-elt) start)))))
65627aad
RS
2029
2030;; Return the first affected buffer position and the delta for an undo element
2031;; delta is defined as the change in subsequent buffer positions if we *did*
2032;; the undo.
2033(defun undo-delta (undo-elt)
2034 (if (consp undo-elt)
2035 (cond ((stringp (car undo-elt))
2036 ;; (TEXT . POSITION)
2037 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
2038 ((integerp (car undo-elt))
2039 ;; (BEGIN . END)
2040 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
2041 (t
2042 '(0 . 0)))
2043 '(0 . 0)))
b6e8e8e5 2044
1223933d 2045(defcustom undo-ask-before-discard nil
28cb725d
LT
2046 "If non-nil ask about discarding undo info for the current command.
2047Normally, Emacs discards the undo info for the current command if
2048it exceeds `undo-outer-limit'. But if you set this option
2049non-nil, it asks in the echo area whether to discard the info.
a3545af4 2050If you answer no, there is a slight risk that Emacs might crash, so
28cb725d
LT
2051only do it if you really want to undo the command.
2052
2053This option is mainly intended for debugging. You have to be
2054careful if you use it for other purposes. Garbage collection is
2055inhibited while the question is asked, meaning that Emacs might
2056leak memory. So you should make sure that you do not wait
2057excessively long before answering the question."
2058 :type 'boolean
2059 :group 'undo
bf247b6e 2060 :version "22.1")
28cb725d 2061
a1a801de
RS
2062(defvar undo-extra-outer-limit nil
2063 "If non-nil, an extra level of size that's ok in an undo item.
2064We don't ask the user about truncating the undo list until the
28cb725d
LT
2065current item gets bigger than this amount.
2066
2067This variable only matters if `undo-ask-before-discard' is non-nil.")
a1a801de
RS
2068(make-variable-buffer-local 'undo-extra-outer-limit)
2069
28cb725d
LT
2070;; When the first undo batch in an undo list is longer than
2071;; undo-outer-limit, this function gets called to warn the user that
2072;; the undo info for the current command was discarded. Garbage
2073;; collection is inhibited around the call, so it had better not do a
2074;; lot of consing.
b6e8e8e5
RS
2075(setq undo-outer-limit-function 'undo-outer-limit-truncate)
2076(defun undo-outer-limit-truncate (size)
28cb725d
LT
2077 (if undo-ask-before-discard
2078 (when (or (null undo-extra-outer-limit)
2079 (> size undo-extra-outer-limit))
2080 ;; Don't ask the question again unless it gets even bigger.
2081 ;; This applies, in particular, if the user quits from the question.
2082 ;; Such a quit quits out of GC, but something else will call GC
2083 ;; again momentarily. It will call this function again,
2084 ;; but we don't want to ask the question again.
2085 (setq undo-extra-outer-limit (+ size 50000))
2086 (if (let (use-dialog-box track-mouse executing-kbd-macro )
d5aa078b 2087 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
28cb725d
LT
2088 (buffer-name) size)))
2089 (progn (setq buffer-undo-list nil)
2090 (setq undo-extra-outer-limit nil)
2091 t)
2092 nil))
2093 (display-warning '(undo discard-info)
2094 (concat
d5aa078b 2095 (format "Buffer `%s' undo info was %d bytes long.\n"
28cb725d
LT
2096 (buffer-name) size)
2097 "The undo info was discarded because it exceeded \
2098`undo-outer-limit'.
2099
2100This is normal if you executed a command that made a huge change
2101to the buffer. In that case, to prevent similar problems in the
2102future, set `undo-outer-limit' to a value that is large enough to
2103cover the maximum size of normal changes you expect a single
2104command to make, but not so large that it might exceed the
2105maximum memory allotted to Emacs.
2106
2107If you did not execute any such command, the situation is
2108probably due to a bug and you should report it.
2109
2110You can disable the popping up of this buffer by adding the entry
14f01bef
CY
2111\(undo discard-info) to the user option `warning-suppress-types',
2112which is defined in the `warnings' library.\n")
28cb725d
LT
2113 :warning)
2114 (setq buffer-undo-list nil)
2115 t))
e1e04350 2116\f
009ef402 2117(defvar shell-command-history nil
e5f0c02f
EZ
2118 "History list for some commands that read shell commands.
2119
2120Maximum length of the history list is determined by the value
2121of `history-length', which see.")
009ef402 2122
6d341a2a 2123(defvar shell-command-switch (purecopy "-c")
59fc41e5
RS
2124 "Switch used to have the shell execute its command line argument.")
2125
cc039f78
KH
2126(defvar shell-command-default-error-buffer nil
2127 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
637fff82 2128This buffer is used when `shell-command' or `shell-command-on-region'
cc039f78
KH
2129is run interactively. A value of nil means that output to stderr and
2130stdout will be intermixed in the output stream.")
2131
a98a2fe8 2132(declare-function mailcap-file-default-commands "mailcap" (files))
e0987650 2133(declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
a98a2fe8
JL
2134
2135(defun minibuffer-default-add-shell-commands ()
263bc3fa 2136 "Return a list of all commands associated with the current file.
086a7dd4 2137This function is used to add all related commands retrieved by `mailcap'
a98a2fe8
JL
2138to the end of the list of defaults just after the default value."
2139 (interactive)
2140 (let* ((filename (if (listp minibuffer-default)
2141 (car minibuffer-default)
2142 minibuffer-default))
2143 (commands (and filename (require 'mailcap nil t)
2144 (mailcap-file-default-commands (list filename)))))
2145 (setq commands (mapcar (lambda (command)
2146 (concat command " " filename))
2147 commands))
2148 (if (listp minibuffer-default)
2149 (append minibuffer-default commands)
2150 (cons minibuffer-default commands))))
2151
2e7bd464
GM
2152(defvar shell-delimiter-argument-list)
2153(defvar shell-file-name-chars)
2154(defvar shell-file-name-quote-list)
2155
e5c4079c
SM
2156(defun minibuffer-complete-shell-command ()
2157 "Dynamically complete shell command at point."
2158 (interactive)
2159 (require 'shell)
79ccd1b8
AS
2160 (let ((comint-delimiter-argument-list shell-delimiter-argument-list)
2161 (comint-file-name-chars shell-file-name-chars)
2162 (comint-file-name-quote-list shell-file-name-quote-list))
2163 (run-hook-with-args-until-success 'shell-dynamic-complete-functions)))
e5c4079c
SM
2164
2165(defvar minibuffer-local-shell-command-map
2166 (let ((map (make-sparse-keymap)))
2167 (set-keymap-parent map minibuffer-local-map)
2168 (define-key map "\t" 'minibuffer-complete-shell-command)
2169 map)
1d2b0303 2170 "Keymap used for completing shell commands in minibuffer.")
e5c4079c
SM
2171
2172(defun read-shell-command (prompt &optional initial-contents hist &rest args)
2173 "Read a shell command from the minibuffer.
2174The arguments are the same as the ones of `read-from-minibuffer',
2175except READ and KEYMAP are missing and HIST defaults
2176to `shell-command-history'."
d6601455
JL
2177 (minibuffer-with-setup-hook
2178 (lambda ()
2179 (set (make-local-variable 'minibuffer-default-add-function)
2180 'minibuffer-default-add-shell-commands))
2181 (apply 'read-from-minibuffer prompt initial-contents
2182 minibuffer-local-shell-command-map
2183 nil
2184 (or hist 'shell-command-history)
2185 args)))
e5c4079c 2186
c945a962
JL
2187(defun async-shell-command (command &optional output-buffer error-buffer)
2188 "Execute string COMMAND asynchronously in background.
2189
2190Like `shell-command' but if COMMAND doesn't end in ampersand, adds `&'
2191surrounded by whitespace and executes the command asynchronously.
5ad4bef5
SM
2192The output appears in the buffer `*Async Shell Command*'.
2193
2194In Elisp, you will often be better served by calling `start-process'
2195directly, since it offers more control and does not impose the use of a
2196shell (with its need to quote arguments)."
c945a962
JL
2197 (interactive
2198 (list
2199 (read-shell-command "Async shell command: " nil nil
2200 (and buffer-file-name
2201 (file-relative-name buffer-file-name)))
2202 current-prefix-arg
2203 shell-command-default-error-buffer))
2204 (unless (string-match "&[ \t]*\\'" command)
2205 (setq command (concat command " &")))
2206 (shell-command command output-buffer error-buffer))
2207
cc039f78 2208(defun shell-command (command &optional output-buffer error-buffer)
2076c87c 2209 "Execute string COMMAND in inferior shell; display output, if any.
0b3f96d4 2210With prefix argument, insert the COMMAND's output at point.
d382f610 2211
2076c87c 2212If COMMAND ends in ampersand, execute it asynchronously.
d382f610 2213The output appears in the buffer `*Async Shell Command*'.
bcad4985 2214That buffer is in shell mode.
d382f610 2215
939ac10c
GM
2216Otherwise, COMMAND is executed synchronously. The output appears in
2217the buffer `*Shell Command Output*'. If the output is short enough to
2218display in the echo area (which is determined by the variables
2219`resize-mini-windows' and `max-mini-window-height'), it is shown
2220there, but it is nonetheless available in buffer `*Shell Command
e1e04350 2221Output*' even though that buffer is not automatically displayed.
d0d74413 2222
07f458c1 2223To specify a coding system for converting non-ASCII characters
5626c14e 2224in the shell command output, use \\[universal-coding-system-argument] \
07f458c1
RS
2225before this command.
2226
2227Noninteractive callers can specify coding systems by binding
2228`coding-system-for-read' and `coding-system-for-write'.
2229
d0d74413
RS
2230The optional second argument OUTPUT-BUFFER, if non-nil,
2231says to put the output in some other buffer.
2232If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2233If OUTPUT-BUFFER is not a buffer and not nil,
2234insert output in current buffer. (This cannot be done asynchronously.)
e7791447
CY
2235In either case, the buffer is first erased, and the output is
2236inserted after point (leaving mark after it).
cc039f78 2237
2e033693
RS
2238If the command terminates without error, but generates output,
2239and you did not specify \"insert it in the current buffer\",
2240the output can be displayed in the echo area or in its buffer.
2241If the output is short enough to display in the echo area
2242\(determined by the variable `max-mini-window-height' if
5626c14e
JB
2243`resize-mini-windows' is non-nil), it is shown there.
2244Otherwise,the buffer containing the output is displayed.
2e033693
RS
2245
2246If there is output and an error, and you did not specify \"insert it
2247in the current buffer\", a message about the error goes at the end
2248of the output.
2249
2250If there is no output, or if output is inserted in the current buffer,
2251then `*Shell Command Output*' is deleted.
2252
cc039f78
KH
2253If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2254or buffer name to which to direct the command's standard error output.
2255If it is nil, error output is mingled with regular output.
2256In an interactive call, the variable `shell-command-default-error-buffer'
5ad4bef5
SM
2257specifies the value of ERROR-BUFFER.
2258
2259In Elisp, you will often be better served by calling `call-process' or
2260`start-process' directly, since it offers more control and does not impose
2261the use of a shell (with its need to quote arguments)."
cc039f78 2262
a98a2fe8
JL
2263 (interactive
2264 (list
d6601455 2265 (read-shell-command "Shell command: " nil nil
e0987650
JL
2266 (let ((filename
2267 (cond
2268 (buffer-file-name)
2269 ((eq major-mode 'dired-mode)
2270 (dired-get-filename nil t)))))
2271 (and filename (file-relative-name filename))))
a98a2fe8
JL
2272 current-prefix-arg
2273 shell-command-default-error-buffer))
c7edd03c
KH
2274 ;; Look for a handler in case default-directory is a remote file name.
2275 (let ((handler
2276 (find-file-name-handler (directory-file-name default-directory)
2277 'shell-command)))
2278 (if handler
cc039f78 2279 (funcall handler 'shell-command command output-buffer error-buffer)
c7edd03c
KH
2280 (if (and output-buffer
2281 (not (or (bufferp output-buffer) (stringp output-buffer))))
2e033693 2282 ;; Output goes in current buffer.
cc039f78 2283 (let ((error-file
1e722f9f 2284 (if error-buffer
b005abd5 2285 (make-temp-file
171a45d9
EZ
2286 (expand-file-name "scor"
2287 (or small-temporary-file-directory
2288 temporary-file-directory)))
cc039f78
KH
2289 nil)))
2290 (barf-if-buffer-read-only)
63437623 2291 (push-mark nil t)
cc039f78
KH
2292 ;; We do not use -f for csh; we will not support broken use of
2293 ;; .cshrcs. Even the BSD csh manual says to use
2294 ;; "if ($?prompt) exit" before things which are not useful
2295 ;; non-interactively. Besides, if someone wants their other
2296 ;; aliases for shell commands then they can still have them.
1e722f9f 2297 (call-process shell-file-name nil
cc039f78
KH
2298 (if error-file
2299 (list t error-file)
2300 t)
2301 nil shell-command-switch command)
2302 (when (and error-file (file-exists-p error-file))
2303 (if (< 0 (nth 7 (file-attributes error-file)))
2304 (with-current-buffer (get-buffer-create error-buffer)
2305 (let ((pos-from-end (- (point-max) (point))))
2306 (or (bobp)
2307 (insert "\f\n"))
2308 ;; Do no formatting while reading error file,
2309 ;; because that can run a shell command, and we
2310 ;; don't want that to cause an infinite recursion.
2311 (format-insert-file error-file nil)
2312 ;; Put point after the inserted errors.
2313 (goto-char (- (point-max) pos-from-end)))
2314 (display-buffer (current-buffer))))
2315 (delete-file error-file))
2316 ;; This is like exchange-point-and-mark, but doesn't
2317 ;; activate the mark. It is cleaner to avoid activation,
2318 ;; even though the command loop would deactivate the mark
2319 ;; because we inserted text.
2320 (goto-char (prog1 (mark t)
2321 (set-marker (mark-marker) (point)
2322 (current-buffer)))))
2e033693 2323 ;; Output goes in a separate buffer.
c7edd03c
KH
2324 ;; Preserve the match data in case called from a program.
2325 (save-match-data
aab5d2c5 2326 (if (string-match "[ \t]*&[ \t]*\\'" command)
c7edd03c
KH
2327 ;; Command ending with ampersand means asynchronous.
2328 (let ((buffer (get-buffer-create
2329 (or output-buffer "*Async Shell Command*")))
2330 (directory default-directory)
2331 proc)
2332 ;; Remove the ampersand.
2333 (setq command (substring command 0 (match-beginning 0)))
2334 ;; If will kill a process, query first.
2335 (setq proc (get-buffer-process buffer))
2336 (if proc
2337 (if (yes-or-no-p "A command is running. Kill it? ")
2338 (kill-process proc)
2339 (error "Shell command in progress")))
1e96c007 2340 (with-current-buffer buffer
c7edd03c 2341 (setq buffer-read-only nil)
50f8cd96
TH
2342 ;; Setting buffer-read-only to nil doesn't suffice
2343 ;; if some text has a non-nil read-only property,
2344 ;; which comint sometimes adds for prompts.
2345 (let ((inhibit-read-only t))
2346 (erase-buffer))
c7edd03c
KH
2347 (display-buffer buffer)
2348 (setq default-directory directory)
1e722f9f 2349 (setq proc (start-process "Shell" buffer shell-file-name
c7edd03c
KH
2350 shell-command-switch command))
2351 (setq mode-line-process '(":%s"))
c2020c27 2352 (require 'shell) (shell-mode)
c7edd03c 2353 (set-process-sentinel proc 'shell-command-sentinel)
50c737e4
JL
2354 ;; Use the comint filter for proper handling of carriage motion
2355 ;; (see `comint-inhibit-carriage-motion'),.
2356 (set-process-filter proc 'comint-output-filter)
c7edd03c 2357 ))
50c737e4 2358 ;; Otherwise, command is executed synchronously.
cc039f78
KH
2359 (shell-command-on-region (point) (point) command
2360 output-buffer nil error-buffer)))))))
eaae8106 2361
f69aad2b
MB
2362(defun display-message-or-buffer (message
2363 &optional buffer-name not-this-window frame)
2364 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2365MESSAGE may be either a string or a buffer.
2366
2367A buffer is displayed using `display-buffer' if MESSAGE is too long for
939ac10c
GM
2368the maximum height of the echo area, as defined by `max-mini-window-height'
2369if `resize-mini-windows' is non-nil.
f69aad2b 2370
2a3f00bf
MB
2371Returns either the string shown in the echo area, or when a pop-up
2372buffer is used, the window used to display it.
2373
f69aad2b
MB
2374If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2375name of the buffer used to display it in the case where a pop-up buffer
2376is used, defaulting to `*Message*'. In the case where MESSAGE is a
2377string and it is displayed in the echo area, it is not specified whether
2378the contents are inserted into the buffer anyway.
2379
2380Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
2381and only used if a buffer is displayed."
39a8d88a 2382 (cond ((and (stringp message) (not (string-match "\n" message)))
f69aad2b
MB
2383 ;; Trivial case where we can use the echo area
2384 (message "%s" message))
2385 ((and (stringp message)
39a8d88a 2386 (= (string-match "\n" message) (1- (length message))))
f69aad2b
MB
2387 ;; Trivial case where we can just remove single trailing newline
2388 (message "%s" (substring message 0 (1- (length message)))))
2389 (t
2390 ;; General case
2391 (with-current-buffer
2392 (if (bufferp message)
2393 message
2394 (get-buffer-create (or buffer-name "*Message*")))
2395
2396 (unless (bufferp message)
2397 (erase-buffer)
2398 (insert message))
2399
2400 (let ((lines
2401 (if (= (buffer-size) 0)
2402 0
62ffcd76 2403 (count-screen-lines nil nil nil (minibuffer-window)))))
4f017185
RS
2404 (cond ((= lines 0))
2405 ((and (or (<= lines 1)
aab5d2c5
RS
2406 (<= lines
2407 (if resize-mini-windows
2408 (cond ((floatp max-mini-window-height)
2409 (* (frame-height)
2410 max-mini-window-height))
2411 ((integerp max-mini-window-height)
2412 max-mini-window-height)
2413 (t
2414 1))
2415 1)))
2416 ;; Don't use the echo area if the output buffer is
2417 ;; already dispayed in the selected frame.
61b80ebf 2418 (not (get-buffer-window (current-buffer))))
f69aad2b
MB
2419 ;; Echo area
2420 (goto-char (point-max))
2421 (when (bolp)
2422 (backward-char 1))
2423 (message "%s" (buffer-substring (point-min) (point))))
2424 (t
2425 ;; Buffer
2426 (goto-char (point-min))
31252c00
MB
2427 (display-buffer (current-buffer)
2428 not-this-window frame))))))))
f69aad2b
MB
2429
2430
2076c87c
JB
2431;; We have a sentinel to prevent insertion of a termination message
2432;; in the buffer itself.
2433(defun shell-command-sentinel (process signal)
bcad4985 2434 (if (memq (process-status process) '(exit signal))
1e722f9f 2435 (message "%s: %s."
bcad4985
KH
2436 (car (cdr (cdr (process-command process))))
2437 (substring signal 0 -1))))
2076c87c 2438
d0d74413 2439(defun shell-command-on-region (start end command
cce1c318 2440 &optional output-buffer replace
63619f42 2441 error-buffer display-error-buffer)
2076c87c
JB
2442 "Execute string COMMAND in inferior shell with region as input.
2443Normally display output (if any) in temp buffer `*Shell Command Output*';
a0184aeb
DL
2444Prefix arg means replace the region with it. Return the exit code of
2445COMMAND.
56c0450e 2446
07f458c1
RS
2447To specify a coding system for converting non-ASCII characters
2448in the input and output to the shell command, use \\[universal-coding-system-argument]
2449before this command. By default, the input (from the current buffer)
2450is encoded in the same coding system that will be used to save the file,
2451`buffer-file-coding-system'. If the output is going to replace the region,
2452then it is decoded from that same coding system.
2453
63619f42
RS
2454The noninteractive arguments are START, END, COMMAND,
2455OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
2456Noninteractive callers can specify coding systems by binding
2457`coding-system-for-read' and `coding-system-for-write'.
2076c87c 2458
2e033693
RS
2459If the command generates output, the output may be displayed
2460in the echo area or in a buffer.
2461If the output is short enough to display in the echo area
2462\(determined by the variable `max-mini-window-height' if
2463`resize-mini-windows' is non-nil), it is shown there. Otherwise
2464it is displayed in the buffer `*Shell Command Output*'. The output
2465is available in that buffer in both cases.
2466
2467If there is output and an error, a message about the error
2468appears at the end of the output.
2469
2470If there is no output, or if output is inserted in the current buffer,
2471then `*Shell Command Output*' is deleted.
d0d74413 2472
56c0450e
RS
2473If the optional fourth argument OUTPUT-BUFFER is non-nil,
2474that says to put the output in some other buffer.
d0d74413
RS
2475If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2476If OUTPUT-BUFFER is not a buffer and not nil,
2477insert output in the current buffer.
cce1c318
RS
2478In either case, the output is inserted after point (leaving mark after it).
2479
8923a211
RS
2480If REPLACE, the optional fifth argument, is non-nil, that means insert
2481the output in place of text from START to END, putting point and mark
2482around it.
2483
b735c991 2484If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
cce1c318 2485or buffer name to which to direct the command's standard error output.
7fd47839 2486If it is nil, error output is mingled with regular output.
63619f42
RS
2487If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2488were any errors. (This is always t, interactively.)
cc039f78
KH
2489In an interactive call, the variable `shell-command-default-error-buffer'
2490specifies the value of ERROR-BUFFER."
195ce311
RS
2491 (interactive (let (string)
2492 (unless (mark)
2493 (error "The mark is not set now, so there is no region"))
2494 ;; Do this before calling region-beginning
2495 ;; and region-end, in case subprocess output
2496 ;; relocates them while we are in the minibuffer.
e5c4079c 2497 (setq string (read-shell-command "Shell command on region: "))
2b03c506
RS
2498 ;; call-interactively recognizes region-beginning and
2499 ;; region-end specially, leaving them in the history.
2500 (list (region-beginning) (region-end)
cae49185
RS
2501 string
2502 current-prefix-arg
7fd47839 2503 current-prefix-arg
63619f42
RS
2504 shell-command-default-error-buffer
2505 t)))
cce1c318 2506 (let ((error-file
171a45d9 2507 (if error-buffer
b005abd5 2508 (make-temp-file
171a45d9
EZ
2509 (expand-file-name "scor"
2510 (or small-temporary-file-directory
2511 temporary-file-directory)))
a0184aeb
DL
2512 nil))
2513 exit-status)
7fd47839
RS
2514 (if (or replace
2515 (and output-buffer
748d6ca4 2516 (not (or (bufferp output-buffer) (stringp output-buffer)))))
7fd47839
RS
2517 ;; Replace specified region with output from command.
2518 (let ((swap (and replace (< start end))))
2519 ;; Don't muck with mark unless REPLACE says we should.
2520 (goto-char start)
30883773 2521 (and replace (push-mark (point) 'nomsg))
a0184aeb
DL
2522 (setq exit-status
2523 (call-process-region start end shell-file-name t
2524 (if error-file
2525 (list t error-file)
2526 t)
2527 nil shell-command-switch command))
e1e04350
SM
2528 ;; It is rude to delete a buffer which the command is not using.
2529 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2530 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2531 ;; (kill-buffer shell-buffer)))
7fd47839
RS
2532 ;; Don't muck with mark unless REPLACE says we should.
2533 (and replace swap (exchange-point-and-mark)))
2534 ;; No prefix argument: put the output in a temp buffer,
2535 ;; replacing its entire contents.
2536 (let ((buffer (get-buffer-create
d4bbcbb4 2537 (or output-buffer "*Shell Command Output*"))))
7fd47839
RS
2538 (unwind-protect
2539 (if (eq buffer (current-buffer))
2540 ;; If the input is the same buffer as the output,
2541 ;; delete everything but the specified region,
2542 ;; then replace that region with the output.
2543 (progn (setq buffer-read-only nil)
2544 (delete-region (max start end) (point-max))
2545 (delete-region (point-min) (min start end))
2546 (setq exit-status
2547 (call-process-region (point-min) (point-max)
1e722f9f 2548 shell-file-name t
7fd47839
RS
2549 (if error-file
2550 (list t error-file)
2551 t)
a0184aeb
DL
2552 nil shell-command-switch
2553 command)))
2554 ;; Clear the output buffer, then run the command with
2555 ;; output there.
c2e303c8 2556 (let ((directory default-directory))
7fdbcd83 2557 (with-current-buffer buffer
c2e303c8
GM
2558 (setq buffer-read-only nil)
2559 (if (not output-buffer)
2560 (setq default-directory directory))
2561 (erase-buffer)))
7fd47839
RS
2562 (setq exit-status
2563 (call-process-region start end shell-file-name nil
2564 (if error-file
2565 (list buffer error-file)
2566 buffer)
a0184aeb 2567 nil shell-command-switch command)))
2e033693 2568 ;; Report the output.
9a98fa64 2569 (with-current-buffer buffer
f1180544 2570 (setq mode-line-process
d4bbcbb4
AS
2571 (cond ((null exit-status)
2572 " - Error")
2573 ((stringp exit-status)
2574 (format " - Signal [%s]" exit-status))
2575 ((not (equal 0 exit-status))
2576 (format " - Exit [%d]" exit-status)))))
f69aad2b
MB
2577 (if (with-current-buffer buffer (> (point-max) (point-min)))
2578 ;; There's some output, display it
9a98fa64 2579 (display-message-or-buffer buffer)
f69aad2b 2580 ;; No output; error?
94ddbe6d
RS
2581 (let ((output
2582 (if (and error-file
2583 (< 0 (nth 7 (file-attributes error-file))))
2584 "some error output"
2585 "no output")))
d4bbcbb4
AS
2586 (cond ((null exit-status)
2587 (message "(Shell command failed with error)"))
2588 ((equal 0 exit-status)
2589 (message "(Shell command succeeded with %s)"
2590 output))
2591 ((stringp exit-status)
2592 (message "(Shell command killed by signal %s)"
2593 exit-status))
2594 (t
2595 (message "(Shell command failed with code %d and %s)"
2596 exit-status output))))
e1e04350
SM
2597 ;; Don't kill: there might be useful info in the undo-log.
2598 ;; (kill-buffer buffer)
2599 ))))
f69aad2b 2600
cc039f78
KH
2601 (when (and error-file (file-exists-p error-file))
2602 (if (< 0 (nth 7 (file-attributes error-file)))
2603 (with-current-buffer (get-buffer-create error-buffer)
2604 (let ((pos-from-end (- (point-max) (point))))
2605 (or (bobp)
2606 (insert "\f\n"))
2607 ;; Do no formatting while reading error file,
2608 ;; because that can run a shell command, and we
2609 ;; don't want that to cause an infinite recursion.
2610 (format-insert-file error-file nil)
2611 ;; Put point after the inserted errors.
2612 (goto-char (- (point-max) pos-from-end)))
63619f42
RS
2613 (and display-error-buffer
2614 (display-buffer (current-buffer)))))
cc039f78 2615 (delete-file error-file))
a0184aeb 2616 exit-status))
1e722f9f 2617
d589bd99
RS
2618(defun shell-command-to-string (command)
2619 "Execute shell command COMMAND and return its output as a string."
2620 (with-output-to-string
17cc9013
RS
2621 (with-current-buffer
2622 standard-output
2623 (call-process shell-file-name nil t nil shell-command-switch command))))
0457dd55
KG
2624
2625(defun process-file (program &optional infile buffer display &rest args)
2626 "Process files synchronously in a separate process.
2627Similar to `call-process', but may invoke a file handler based on
2628`default-directory'. The current working directory of the
2629subprocess is `default-directory'.
2630
2631File names in INFILE and BUFFER are handled normally, but file
2632names in ARGS should be relative to `default-directory', as they
2633are passed to the process verbatim. \(This is a difference to
2634`call-process' which does not support file handlers for INFILE
2635and BUFFER.\)
2636
2637Some file handlers might not support all variants, for example
2638they might behave as if DISPLAY was nil, regardless of the actual
2639value passed."
2640 (let ((fh (find-file-name-handler default-directory 'process-file))
2641 lc stderr-file)
2642 (unwind-protect
2643 (if fh (apply fh 'process-file program infile buffer display args)
8de40f9f 2644 (when infile (setq lc (file-local-copy infile)))
0457dd55 2645 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
85af630d
KG
2646 (make-temp-file "emacs")))
2647 (prog1
2648 (apply 'call-process program
2649 (or lc infile)
2650 (if stderr-file (list (car buffer) stderr-file) buffer)
2651 display args)
2652 (when stderr-file (copy-file stderr-file (cadr buffer)))))
0457dd55
KG
2653 (when stderr-file (delete-file stderr-file))
2654 (when lc (delete-file lc)))))
2655
2c4f2562
MA
2656(defvar process-file-side-effects t
2657 "Whether a call of `process-file' changes remote files.
2658
2659Per default, this variable is always set to `t', meaning that a
2660call of `process-file' could potentially change any file on a
2661remote host. When set to `nil', a file handler could optimize
2662its behaviour with respect to remote file attributes caching.
2663
2664This variable should never be changed by `setq'. Instead of, it
2665shall be set only by let-binding.")
2666
7cb76caa
MA
2667(defun start-file-process (name buffer program &rest program-args)
2668 "Start a program in a subprocess. Return the process object for it.
5a5abb2c 2669
7cb76caa 2670Similar to `start-process', but may invoke a file handler based on
5a5abb2c
MA
2671`default-directory'. See Info node `(elisp)Magic File Names'.
2672
2673This handler ought to run PROGRAM, perhaps on the local host,
2674perhaps on a remote host that corresponds to `default-directory'.
2675In the latter case, the local part of `default-directory' becomes
2676the working directory of the process.
7cb76caa
MA
2677
2678PROGRAM and PROGRAM-ARGS might be file names. They are not
91f11424
MA
2679objects of file handler invocation. File handlers might not
2680support pty association, if PROGRAM is nil."
7cb76caa
MA
2681 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
2682 (if fh (apply fh 'start-file-process name buffer program program-args)
2683 (apply 'start-process name buffer program program-args))))
2684
2d88b556 2685\f
1b43f83f 2686(defvar universal-argument-map
69d4c3c4
KH
2687 (let ((map (make-sparse-keymap)))
2688 (define-key map [t] 'universal-argument-other-key)
b9ff190d 2689 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
69d4c3c4
KH
2690 (define-key map [switch-frame] nil)
2691 (define-key map [?\C-u] 'universal-argument-more)
2692 (define-key map [?-] 'universal-argument-minus)
2693 (define-key map [?0] 'digit-argument)
2694 (define-key map [?1] 'digit-argument)
2695 (define-key map [?2] 'digit-argument)
2696 (define-key map [?3] 'digit-argument)
2697 (define-key map [?4] 'digit-argument)
2698 (define-key map [?5] 'digit-argument)
2699 (define-key map [?6] 'digit-argument)
2700 (define-key map [?7] 'digit-argument)
2701 (define-key map [?8] 'digit-argument)
2702 (define-key map [?9] 'digit-argument)
bd7acc8d
GM
2703 (define-key map [kp-0] 'digit-argument)
2704 (define-key map [kp-1] 'digit-argument)
2705 (define-key map [kp-2] 'digit-argument)
2706 (define-key map [kp-3] 'digit-argument)
2707 (define-key map [kp-4] 'digit-argument)
2708 (define-key map [kp-5] 'digit-argument)
2709 (define-key map [kp-6] 'digit-argument)
2710 (define-key map [kp-7] 'digit-argument)
2711 (define-key map [kp-8] 'digit-argument)
2712 (define-key map [kp-9] 'digit-argument)
2713 (define-key map [kp-subtract] 'universal-argument-minus)
69d4c3c4
KH
2714 map)
2715 "Keymap used while processing \\[universal-argument].")
2716
0de84e16
RS
2717(defvar universal-argument-num-events nil
2718 "Number of argument-specifying events read by `universal-argument'.
2719`universal-argument-other-key' uses this to discard those events
2720from (this-command-keys), and reread only the final command.")
2721
6b61353c
KH
2722(defvar overriding-map-is-bound nil
2723 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2724
2725(defvar saved-overriding-map nil
2726 "The saved value of `overriding-terminal-local-map'.
2727That variable gets restored to this value on exiting \"universal
2728argument mode\".")
2729
2730(defun ensure-overriding-map-is-bound ()
2731 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2732 (unless overriding-map-is-bound
2733 (setq saved-overriding-map overriding-terminal-local-map)
2734 (setq overriding-terminal-local-map universal-argument-map)
2735 (setq overriding-map-is-bound t)))
2736
2737(defun restore-overriding-map ()
2738 "Restore `overriding-terminal-local-map' to its saved value."
2739 (setq overriding-terminal-local-map saved-overriding-map)
2740 (setq overriding-map-is-bound nil))
2741
e8d1a377
KH
2742(defun universal-argument ()
2743 "Begin a numeric argument for the following command.
2744Digits or minus sign following \\[universal-argument] make up the numeric argument.
2745\\[universal-argument] following the digits or minus sign ends the argument.
2746\\[universal-argument] without digits or minus sign provides 4 as argument.
2747Repeating \\[universal-argument] without digits or minus sign
0565d307
RS
2748 multiplies the argument by 4 each time.
2749For some commands, just \\[universal-argument] by itself serves as a flag
a697fc62
RS
2750which is different in effect from any particular numeric argument.
2751These commands include \\[set-mark-command] and \\[start-kbd-macro]."
69d4c3c4
KH
2752 (interactive)
2753 (setq prefix-arg (list 4))
0de84e16 2754 (setq universal-argument-num-events (length (this-command-keys)))
6b61353c 2755 (ensure-overriding-map-is-bound))
e8d1a377 2756
69d4c3c4
KH
2757;; A subsequent C-u means to multiply the factor by 4 if we've typed
2758;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2759(defun universal-argument-more (arg)
e8d1a377 2760 (interactive "P")
69d4c3c4
KH
2761 (if (consp arg)
2762 (setq prefix-arg (list (* 4 (car arg))))
1cd24721
RS
2763 (if (eq arg '-)
2764 (setq prefix-arg (list -4))
2765 (setq prefix-arg arg)
6b61353c 2766 (restore-overriding-map)))
0de84e16 2767 (setq universal-argument-num-events (length (this-command-keys))))
e8d1a377
KH
2768
2769(defun negative-argument (arg)
2770 "Begin a negative numeric argument for the next command.
2771\\[universal-argument] following digits or minus sign ends the argument."
2772 (interactive "P")
69d4c3c4
KH
2773 (cond ((integerp arg)
2774 (setq prefix-arg (- arg)))
2775 ((eq arg '-)
2776 (setq prefix-arg nil))
2777 (t
b9ff190d 2778 (setq prefix-arg '-)))
0de84e16 2779 (setq universal-argument-num-events (length (this-command-keys)))
6b61353c 2780 (ensure-overriding-map-is-bound))
69d4c3c4
KH
2781
2782(defun digit-argument (arg)
2783 "Part of the numeric argument for the next command.
2784\\[universal-argument] following digits or minus sign ends the argument."
2785 (interactive "P")
8989a920
GM
2786 (let* ((char (if (integerp last-command-event)
2787 last-command-event
2788 (get last-command-event 'ascii-character)))
bd7acc8d 2789 (digit (- (logand char ?\177) ?0)))
69d4c3c4
KH
2790 (cond ((integerp arg)
2791 (setq prefix-arg (+ (* arg 10)
2792 (if (< arg 0) (- digit) digit))))
2793 ((eq arg '-)
2794 ;; Treat -0 as just -, so that -01 will work.
2795 (setq prefix-arg (if (zerop digit) '- (- digit))))
2796 (t
b9ff190d 2797 (setq prefix-arg digit))))
0de84e16 2798 (setq universal-argument-num-events (length (this-command-keys)))
6b61353c 2799 (ensure-overriding-map-is-bound))
69d4c3c4
KH
2800
2801;; For backward compatibility, minus with no modifiers is an ordinary
2802;; command if digits have already been entered.
2803(defun universal-argument-minus (arg)
2804 (interactive "P")
2805 (if (integerp arg)
2806 (universal-argument-other-key arg)
2807 (negative-argument arg)))
2808
2809;; Anything else terminates the argument and is left in the queue to be
2810;; executed as a command.
2811(defun universal-argument-other-key (arg)
2812 (interactive "P")
2813 (setq prefix-arg arg)
0de84e16
RS
2814 (let* ((key (this-command-keys))
2815 (keylist (listify-key-sequence key)))
2816 (setq unread-command-events
06697cdb
RS
2817 (append (nthcdr universal-argument-num-events keylist)
2818 unread-command-events)))
f0ef2555 2819 (reset-this-command-lengths)
6b61353c 2820 (restore-overriding-map))
2d88b556 2821\f
8f92b8ad
SM
2822;; This function is here rather than in subr.el because it uses CL.
2823(defmacro with-wrapper-hook (var args &rest body)
2824 "Run BODY wrapped with the VAR hook.
2825VAR is a special hook: its functions are called with a first argument
2826which is the \"original\" code (the BODY), so the hook function can wrap
2827the original function, or call it any number of times (including not calling
2828it at all). This is similar to an `around' advice.
2829VAR is normally a symbol (a variable) in which case it is treated like
2830a hook, with a buffer-local and a global part. But it can also be an
2831arbitrary expression.
2832ARGS is a list of variables which will be passed as additional arguments
2833to each function, after the initial argument, and which the first argument
2834expects to receive when called."
2835 (declare (indent 2) (debug t))
2836 ;; We need those two gensyms because CL's lexical scoping is not available
2837 ;; for function arguments :-(
2838 (let ((funs (make-symbol "funs"))
2839 (global (make-symbol "global"))
2840 (argssym (make-symbol "args")))
2841 ;; Since the hook is a wrapper, the loop has to be done via
2842 ;; recursion: a given hook function will call its parameter in order to
2843 ;; continue looping.
2844 `(labels ((runrestofhook (,funs ,global ,argssym)
2845 ;; `funs' holds the functions left on the hook and `global'
2846 ;; holds the functions left on the global part of the hook
2847 ;; (in case the hook is local).
2848 (lexical-let ((funs ,funs)
2849 (global ,global))
2850 (if (consp funs)
2851 (if (eq t (car funs))
2852 (runrestofhook
2853 (append global (cdr funs)) nil ,argssym)
2854 (apply (car funs)
2855 (lambda (&rest ,argssym)
2856 (runrestofhook (cdr funs) global ,argssym))
2857 ,argssym))
2858 ;; Once there are no more functions on the hook, run
2859 ;; the original body.
2860 (apply (lambda ,args ,@body) ,argssym)))))
2861 (runrestofhook ,var
2862 ;; The global part of the hook, if any.
2863 ,(if (symbolp var)
2864 `(if (local-variable-p ',var)
2865 (default-value ',var)))
2866 (list ,@args)))))
2867
2868(defvar filter-buffer-substring-functions nil
2869 "Wrapper hook around `filter-buffer-substring'.
2870The functions on this special hook are called with 4 arguments:
2871 NEXT-FUN BEG END DELETE
2872NEXT-FUN is a function of 3 arguments (BEG END DELETE)
2873that performs the default operation. The other 3 arguments are like
2874the ones passed to `filter-buffer-substring'.")
2875
7fcce20f
RS
2876(defvar buffer-substring-filters nil
2877 "List of filter functions for `filter-buffer-substring'.
2878Each function must accept a single argument, a string, and return
2879a string. The buffer substring is passed to the first function
2880in the list, and the return value of each function is passed to
2881the next. The return value of the last function is used as the
2882return value of `filter-buffer-substring'.
2883
2884If this variable is nil, no filtering is performed.")
8f92b8ad
SM
2885(make-obsolete-variable 'buffer-substring-filters
2886 'filter-buffer-substring-functions "24.1")
7fcce20f 2887
8f92b8ad 2888(defun filter-buffer-substring (beg end &optional delete)
7fcce20f 2889 "Return the buffer substring between BEG and END, after filtering.
8f92b8ad 2890The filtering is performed by `filter-buffer-substring-functions'.
7fcce20f
RS
2891
2892If DELETE is non-nil, the text between BEG and END is deleted
2893from the buffer.
2894
398c9ffb
KS
2895This function should be used instead of `buffer-substring',
2896`buffer-substring-no-properties', or `delete-and-extract-region'
2897when you want to allow filtering to take place. For example,
8f92b8ad 2898major or minor modes can use `filter-buffer-substring-functions' to
398c9ffb
KS
2899extract characters that are special to a buffer, and should not
2900be copied into other buffers."
8f92b8ad
SM
2901 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
2902 (cond
2903 ((or delete buffer-substring-filters)
2904 (save-excursion
2905 (goto-char beg)
2906 (let ((string (if delete (delete-and-extract-region beg end)
2907 (buffer-substring beg end))))
2908 (dolist (filter buffer-substring-filters)
2909 (setq string (funcall filter string)))
2910 string)))
2911 (t
2912 (buffer-substring beg end)))))
398c9ffb 2913
7fcce20f 2914
93be67de 2915;;;; Window system cut and paste hooks.
70e14c01
JB
2916
2917(defvar interprogram-cut-function nil
2918 "Function to call to make a killed region available to other programs.
2919
2920Most window systems provide some sort of facility for cutting and
9f112a3d
RS
2921pasting text between the windows of different programs.
2922This variable holds a function that Emacs calls whenever text
2923is put in the kill ring, to make the new kill available to other
70e14c01
JB
2924programs.
2925
6d7cc563
JD
2926The function takes one argument, TEXT, which is a string containing
2927the text which should be made available.")
70e14c01
JB
2928
2929(defvar interprogram-paste-function nil
2930 "Function to call to get text cut from other programs.
2931
2932Most window systems provide some sort of facility for cutting and
9f112a3d
RS
2933pasting text between the windows of different programs.
2934This variable holds a function that Emacs calls to obtain
70e14c01
JB
2935text that other programs have provided for pasting.
2936
2937The function should be called with no arguments. If the function
2938returns nil, then no other program has provided such text, and the top
2939of the Emacs kill ring should be used. If the function returns a
6b61353c
KH
2940string, then the caller of the function \(usually `current-kill')
2941should put this string in the kill ring as the latest kill.
daa37602 2942
d4cb4833 2943This function may also return a list of strings if the window
1d2b0303 2944system supports multiple selections. The first string will be
d4cb4833
GM
2945used as the pasted text, but the other will be placed in the
2946kill ring for easy access via `yank-pop'.
2947
daa37602
JB
2948Note that the function should return a string only if a program other
2949than Emacs has provided a string for pasting; if Emacs provided the
2950most recent string, the function should return nil. If it is
2951difficult to tell whether Emacs or some other program provided the
2952current string, it is probably good enough to return nil if the string
2953is equal (according to `string=') to the last text Emacs provided.")
2d88b556 2954\f
70e14c01 2955
eaae8106 2956
70e14c01 2957;;;; The kill ring data structure.
2076c87c
JB
2958
2959(defvar kill-ring nil
70e14c01
JB
2960 "List of killed text sequences.
2961Since the kill ring is supposed to interact nicely with cut-and-paste
2962facilities offered by window systems, use of this variable should
2963interact nicely with `interprogram-cut-function' and
2964`interprogram-paste-function'. The functions `kill-new',
2965`kill-append', and `current-kill' are supposed to implement this
2966interaction; you may want to use them instead of manipulating the kill
2967ring directly.")
2076c87c 2968
bffa4d92 2969(defcustom kill-ring-max 60
1d2b0303 2970 "Maximum length of kill ring before oldest elements are thrown away."
69c1dd37
RS
2971 :type 'integer
2972 :group 'killing)
2076c87c
JB
2973
2974(defvar kill-ring-yank-pointer nil
2975 "The tail of the kill ring whose car is the last thing yanked.")
2976
4ed8c7aa 2977(defcustom save-interprogram-paste-before-kill nil
e8ab3908 2978 "Save clipboard strings into kill ring before replacing them.
4ed8c7aa
SS
2979When one selects something in another program to paste it into Emacs,
2980but kills something in Emacs before actually pasting it,
2981this selection is gone unless this variable is non-nil,
2982in which case the other program's selection is saved in the `kill-ring'
2983before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
2984 :type 'boolean
2985 :group 'killing
2986 :version "23.2")
2987
ba83a64e
SS
2988(defcustom kill-do-not-save-duplicates nil
2989 "Do not add a new string to `kill-ring' when it is the same as the last one."
2990 :type 'boolean
2991 :group 'killing
2992 :version "23.2")
2993
be5936a7 2994(defun kill-new (string &optional replace yank-handler)
70e14c01 2995 "Make STRING the latest kill in the kill ring.
3e505153 2996Set `kill-ring-yank-pointer' to point to it.
f914dc91
KH
2997If `interprogram-cut-function' is non-nil, apply it to STRING.
2998Optional second argument REPLACE non-nil means that STRING will replace
be5936a7
KS
2999the front of the kill ring, rather than being added to the list.
3000
4ed8c7aa
SS
3001When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
3002are non-nil, saves the interprogram paste string(s) into `kill-ring' before
3003STRING.
3004
2a262563
KS
3005When the yank handler has a non-nil PARAM element, the original STRING
3006argument is not used by `insert-for-yank'. However, since Lisp code
f33321ad 3007may access and use elements from the kill ring directly, the STRING
2a262563
KS
3008argument should still be a \"useful\" string for such uses."
3009 (if (> (length string) 0)
f1180544 3010 (if yank-handler
6b61353c
KH
3011 (put-text-property 0 (length string)
3012 'yank-handler yank-handler string))
2a262563 3013 (if yank-handler
f1180544 3014 (signal 'args-out-of-range
2a262563 3015 (list string "yank-handler specified for empty string"))))
0665f661
JL
3016 (unless (and kill-do-not-save-duplicates
3017 (equal string (car kill-ring)))
3018 (if (fboundp 'menu-bar-update-yank-menu)
3019 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
4ed8c7aa
SS
3020 (when save-interprogram-paste-before-kill
3021 (let ((interprogram-paste (and interprogram-paste-function
3022 (funcall interprogram-paste-function))))
3023 (when interprogram-paste
0665f661
JL
3024 (dolist (s (if (listp interprogram-paste)
3025 (nreverse interprogram-paste)
3026 (list interprogram-paste)))
3027 (unless (and kill-do-not-save-duplicates
3028 (equal s (car kill-ring)))
3029 (push s kill-ring))))))
3030 (unless (and kill-do-not-save-duplicates
3031 (equal string (car kill-ring)))
3032 (if (and replace kill-ring)
3033 (setcar kill-ring string)
3034 (push string kill-ring)
3035 (if (> (length kill-ring) kill-ring-max)
3036 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
70e14c01
JB
3037 (setq kill-ring-yank-pointer kill-ring)
3038 (if interprogram-cut-function
08d4877e 3039 (funcall interprogram-cut-function string)))
9fca7811
SM
3040(set-advertised-calling-convention
3041 'kill-new '(string &optional replace) "23.3")
70e14c01 3042
be5936a7 3043(defun kill-append (string before-p &optional yank-handler)
70e14c01
JB
3044 "Append STRING to the end of the latest kill in the kill ring.
3045If BEFORE-P is non-nil, prepend STRING to the kill.
be5936a7
KS
3046If `interprogram-cut-function' is set, pass the resulting kill to it."
3047 (let* ((cur (car kill-ring)))
3048 (kill-new (if before-p (concat string cur) (concat cur string))
3049 (or (= (length cur) 0)
3050 (equal yank-handler (get-text-property 0 'yank-handler cur)))
3051 yank-handler)))
9fca7811 3052(set-advertised-calling-convention 'kill-append '(string before-p) "23.3")
70e14c01 3053
4496b02b
RS
3054(defcustom yank-pop-change-selection nil
3055 "If non-nil, rotating the kill ring changes the window system selection."
3056 :type 'boolean
3057 :group 'killing
3058 :version "23.1")
3059
70e14c01
JB
3060(defun current-kill (n &optional do-not-move)
3061 "Rotate the yanking point by N places, and then return that kill.
1d2b0303
JB
3062If N is zero, `interprogram-paste-function' is set, and calling
3063it returns a string or list of strings, then that string (or
3064list) is added to the front of the kill ring and the string (or
3065first string in the list) is returned as the latest kill.
4496b02b
RS
3066
3067If N is not zero, and if `yank-pop-change-selection' is
3068non-nil, use `interprogram-cut-function' to transfer the
3069kill at the new yank point into the window system selection.
3070
3071If optional arg DO-NOT-MOVE is non-nil, then don't actually
3072move the yanking point; just return the Nth kill forward."
3073
70e14c01
JB
3074 (let ((interprogram-paste (and (= n 0)
3075 interprogram-paste-function
3076 (funcall interprogram-paste-function))))
3077 (if interprogram-paste
3078 (progn
3079 ;; Disable the interprogram cut function when we add the new
3080 ;; text to the kill ring, so Emacs doesn't try to own the
3081 ;; selection, with identical text.
3082 (let ((interprogram-cut-function nil))
d4cb4833
GM
3083 (if (listp interprogram-paste)
3084 (mapc 'kill-new (nreverse interprogram-paste))
3085 (kill-new interprogram-paste)))
3086 (car kill-ring))
70e14c01 3087 (or kill-ring (error "Kill ring is empty"))
47096a67
PE
3088 (let ((ARGth-kill-element
3089 (nthcdr (mod (- n (length kill-ring-yank-pointer))
3090 (length kill-ring))
3091 kill-ring)))
4496b02b
RS
3092 (unless do-not-move
3093 (setq kill-ring-yank-pointer ARGth-kill-element)
3094 (when (and yank-pop-change-selection
3095 (> n 0)
3096 interprogram-cut-function)
3097 (funcall interprogram-cut-function (car ARGth-kill-element))))
70e14c01 3098 (car ARGth-kill-element)))))
c88ab9ce 3099
c88ab9ce 3100
eaae8106 3101
70e14c01 3102;;;; Commands for manipulating the kill ring.
c88ab9ce 3103
69c1dd37 3104(defcustom kill-read-only-ok nil
1d2b0303 3105 "Non-nil means don't signal an error for killing read-only text."
69c1dd37
RS
3106 :type 'boolean
3107 :group 'killing)
e6291fe1 3108
3a5da8a8
RS
3109(put 'text-read-only 'error-conditions
3110 '(text-read-only buffer-read-only error))
6d341a2a 3111(put 'text-read-only 'error-message (purecopy "Text is read-only"))
3a5da8a8 3112
be5936a7 3113(defun kill-region (beg end &optional yank-handler)
66e9b2b2
RS
3114 "Kill (\"cut\") text between point and mark.
3115This deletes the text from the buffer and saves it in the kill ring.
2076c87c 3116The command \\[yank] can retrieve it from there.
ba2b460a 3117\(If you want to save the region without killing it, use \\[kill-ring-save].)
81558867
EZ
3118
3119If you want to append the killed region to the last killed text,
3120use \\[append-next-kill] before \\[kill-region].
3121
2aa7a8bf
JB
3122If the buffer is read-only, Emacs will beep and refrain from deleting
3123the text, but put the text in the kill ring anyway. This means that
3124you can use the killing commands to copy text from a read-only buffer.
2076c87c 3125
a4aae1a5
CY
3126Lisp programs should use this function for killing text.
3127 (To delete text, use `delete-region'.)
c15dc81f 3128Supply two arguments, character positions indicating the stretch of text
2076c87c
JB
3129 to be killed.
3130Any command that calls this function is a \"kill command\".
3131If the previous command was also a kill command,
3132the text killed this time appends to the text killed last time
9fca7811 3133to make one entry in the kill ring."
214a3db0
RS
3134 ;; Pass point first, then mark, because the order matters
3135 ;; when calling kill-append.
3136 (interactive (list (point) (mark)))
f39d6be0
RS
3137 (unless (and beg end)
3138 (error "The mark is not set now, so there is no region"))
ccd19b9f 3139 (condition-case nil
7fcce20f 3140 (let ((string (filter-buffer-substring beg end t)))
a1eb02bd
SM
3141 (when string ;STRING is nil if BEG = END
3142 ;; Add that string to the kill ring, one way or another.
3143 (if (eq last-command 'kill-region)
be5936a7
KS
3144 (kill-append string (< end beg) yank-handler)
3145 (kill-new string nil yank-handler)))
8a7cda9b 3146 (when (or string (eq last-command 'kill-region))
6b61353c
KH
3147 (setq this-command 'kill-region))
3148 nil)
ccd19b9f
KH
3149 ((buffer-read-only text-read-only)
3150 ;; The code above failed because the buffer, or some of the characters
3151 ;; in the region, are read-only.
3152 ;; We should beep, in case the user just isn't aware of this.
3153 ;; However, there's no harm in putting
3154 ;; the region's text in the kill ring, anyway.
3155 (copy-region-as-kill beg end)
cb3e1b4c
RS
3156 ;; Set this-command now, so it will be set even if we get an error.
3157 (setq this-command 'kill-region)
3158 ;; This should barf, if appropriate, and give us the correct error.
ccd19b9f 3159 (if kill-read-only-ok
6b61353c 3160 (progn (message "Read only text copied to kill ring") nil)
ccd19b9f
KH
3161 ;; Signal an error if the buffer is read-only.
3162 (barf-if-buffer-read-only)
3163 ;; If the buffer isn't read-only, the text is.
3164 (signal 'text-read-only (list (current-buffer)))))))
9fca7811 3165(set-advertised-calling-convention 'kill-region '(beg end) "23.3")
2076c87c 3166
a382890a
KH
3167;; copy-region-as-kill no longer sets this-command, because it's confusing
3168;; to get two copies of the text when the user accidentally types M-w and
3169;; then corrects it with the intended C-w.
2076c87c
JB
3170(defun copy-region-as-kill (beg end)
3171 "Save the region as if killed, but don't kill it.
0e264847 3172In Transient Mark mode, deactivate the mark.
46947372 3173If `interprogram-cut-function' is non-nil, also save the text for a window
b66eb11b
RS
3174system cut and paste.
3175
3176This command's old key binding has been given to `kill-ring-save'."
2076c87c
JB
3177 (interactive "r")
3178 (if (eq last-command 'kill-region)
7fcce20f
RS
3179 (kill-append (filter-buffer-substring beg end) (< end beg))
3180 (kill-new (filter-buffer-substring beg end)))
d34c311a 3181 (setq deactivate-mark t)
2076c87c
JB
3182 nil)
3183
3184(defun kill-ring-save (beg end)
0964e562 3185 "Save the region as if killed, but don't kill it.
0e264847 3186In Transient Mark mode, deactivate the mark.
0964e562 3187If `interprogram-cut-function' is non-nil, also save the text for a window
0e264847
RS
3188system cut and paste.
3189
81558867
EZ
3190If you want to append the killed line to the last killed text,
3191use \\[append-next-kill] before \\[kill-ring-save].
3192
0e264847
RS
3193This command is similar to `copy-region-as-kill', except that it gives
3194visual feedback indicating the extent of the region being copied."
2076c87c
JB
3195 (interactive "r")
3196 (copy-region-as-kill beg end)
32226619 3197 ;; This use of called-interactively-p is correct
bbf41690 3198 ;; because the code it controls just gives the user visual feedback.
32226619 3199 (if (called-interactively-p 'interactive)
66050f10
RS
3200 (let ((other-end (if (= (point) beg) end beg))
3201 (opoint (point))
3202 ;; Inhibit quitting so we can make a quit here
3203 ;; look like a C-g typed as a command.
3204 (inhibit-quit t))
3205 (if (pos-visible-in-window-p other-end (selected-window))
d34c311a
SM
3206 ;; Swap point-and-mark quickly so as to show the region that
3207 ;; was selected. Don't do it if the region is highlighted.
3208 (unless (and (region-active-p)
977e2654 3209 (face-background 'region))
66050f10
RS
3210 ;; Swap point and mark.
3211 (set-marker (mark-marker) (point) (current-buffer))
3212 (goto-char other-end)
e4ef3e92 3213 (sit-for blink-matching-delay)
66050f10
RS
3214 ;; Swap back.
3215 (set-marker (mark-marker) other-end (current-buffer))
3216 (goto-char opoint)
3217 ;; If user quit, deactivate the mark
3218 ;; as C-g would as a command.
e4e593ae 3219 (and quit-flag mark-active
fcadf1c7 3220 (deactivate-mark)))
66050f10
RS
3221 (let* ((killed-text (current-kill 0))
3222 (message-len (min (length killed-text) 40)))
3223 (if (= (point) beg)
3224 ;; Don't say "killed"; that is misleading.
3225 (message "Saved text until \"%s\""
3226 (substring killed-text (- message-len)))
3227 (message "Saved text from \"%s\""
3228 (substring killed-text 0 message-len))))))))
2076c87c 3229
c75d4986
KH
3230(defun append-next-kill (&optional interactive)
3231 "Cause following command, if it kills, to append to previous kill.
3232The argument is used for internal purposes; do not supply one."
3233 (interactive "p")
3234 ;; We don't use (interactive-p), since that breaks kbd macros.
3235 (if interactive
2076c87c
JB
3236 (progn
3237 (setq this-command 'kill-region)
3238 (message "If the next command is a kill, it will append"))
3239 (setq last-command 'kill-region)))
cfb4f123 3240\f
93be67de 3241;; Yanking.
2076c87c 3242
cfb4f123
RS
3243;; This is actually used in subr.el but defcustom does not work there.
3244(defcustom yank-excluded-properties
be5936a7 3245 '(read-only invisible intangible field mouse-face help-echo local-map keymap
7408ee97 3246 yank-handler follow-link fontified)
3137dda8 3247 "Text properties to discard when yanking.
c6ff5a4c
LT
3248The value should be a list of text properties to discard or t,
3249which means to discard all text properties."
cfb4f123 3250 :type '(choice (const :tag "All" t) (repeat symbol))
c9f0110e 3251 :group 'killing
bf247b6e 3252 :version "22.1")
cfb4f123 3253
120de5bd 3254(defvar yank-window-start nil)
be5936a7 3255(defvar yank-undo-function nil
44f5a7b2
KS
3256 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
3257Function is called with two parameters, START and END corresponding to
3258the value of the mark and point; it is guaranteed that START <= END.
3259Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
120de5bd 3260
6b61353c 3261(defun yank-pop (&optional arg)
ff1fbe3e
RS
3262 "Replace just-yanked stretch of killed text with a different stretch.
3263This command is allowed only immediately after a `yank' or a `yank-pop'.
2076c87c 3264At such a time, the region contains a stretch of reinserted
ff1fbe3e 3265previously-killed text. `yank-pop' deletes that text and inserts in its
2076c87c
JB
3266place a different stretch of killed text.
3267
3268With no argument, the previous kill is inserted.
ff1fbe3e
RS
3269With argument N, insert the Nth previous kill.
3270If N is negative, this is a more recent kill.
2076c87c
JB
3271
3272The sequence of kills wraps around, so that after the oldest one
a0e8eaa3
EZ
3273comes the newest one.
3274
3275When this command inserts killed text into the buffer, it honors
3276`yank-excluded-properties' and `yank-handler' as described in the
3277doc string for `insert-for-yank-1', which see."
2076c87c
JB
3278 (interactive "*p")
3279 (if (not (eq last-command 'yank))
3280 (error "Previous command was not a yank"))
3281 (setq this-command 'yank)
6b61353c 3282 (unless arg (setq arg 1))
3a5da8a8
RS
3283 (let ((inhibit-read-only t)
3284 (before (< (point) (mark t))))
8254897f
KS
3285 (if before
3286 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
3287 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
be5936a7 3288 (setq yank-undo-function nil)
fd0f4056 3289 (set-marker (mark-marker) (point) (current-buffer))
cfb4f123 3290 (insert-for-yank (current-kill arg))
120de5bd
RS
3291 ;; Set the window start back where it was in the yank command,
3292 ;; if possible.
3293 (set-window-start (selected-window) yank-window-start t)
fd0f4056
RS
3294 (if before
3295 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3296 ;; It is cleaner to avoid activation, even though the command
3297 ;; loop would deactivate the mark because we inserted text.
3298 (goto-char (prog1 (mark t)
3299 (set-marker (mark-marker) (point) (current-buffer))))))
0964e562 3300 nil)
2076c87c
JB
3301
3302(defun yank (&optional arg)
f894e671 3303 "Reinsert (\"paste\") the last stretch of killed text.
2076c87c 3304More precisely, reinsert the stretch of killed text most recently
ff1fbe3e 3305killed OR yanked. Put point at end, and set mark at beginning.
d99f8496 3306With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
ff1fbe3e 3307With argument N, reinsert the Nth most recently killed stretch of killed
2076c87c 3308text.
a0e8eaa3
EZ
3309
3310When this command inserts killed text into the buffer, it honors
3311`yank-excluded-properties' and `yank-handler' as described in the
3312doc string for `insert-for-yank-1', which see.
3313
a9b9303c 3314See also the command `yank-pop' (\\[yank-pop])."
2076c87c 3315 (interactive "*P")
120de5bd 3316 (setq yank-window-start (window-start))
456c617c
RS
3317 ;; If we don't get all the way thru, make last-command indicate that
3318 ;; for the following command.
3319 (setq this-command t)
2076c87c 3320 (push-mark (point))
cfb4f123
RS
3321 (insert-for-yank (current-kill (cond
3322 ((listp arg) 0)
6b61353c 3323 ((eq arg '-) -2)
cfb4f123 3324 (t (1- arg)))))
2076c87c 3325 (if (consp arg)
fd0f4056
RS
3326 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3327 ;; It is cleaner to avoid activation, even though the command
3328 ;; loop would deactivate the mark because we inserted text.
3329 (goto-char (prog1 (mark t)
3330 (set-marker (mark-marker) (point) (current-buffer)))))
456c617c 3331 ;; If we do get all the way thru, make this-command indicate that.
be5936a7
KS
3332 (if (eq this-command t)
3333 (setq this-command 'yank))
0964e562 3334 nil)
70e14c01
JB
3335
3336(defun rotate-yank-pointer (arg)
3337 "Rotate the yanking point in the kill ring.
5626c14e 3338With ARG, rotate that many kills forward (or backward, if negative)."
70e14c01
JB
3339 (interactive "p")
3340 (current-kill arg))
2d88b556 3341\f
93be67de
KH
3342;; Some kill commands.
3343
3344;; Internal subroutine of delete-char
3345(defun kill-forward-chars (arg)
3346 (if (listp arg) (setq arg (car arg)))
3347 (if (eq arg '-) (setq arg -1))
673e5169 3348 (kill-region (point) (+ (point) arg)))
93be67de
KH
3349
3350;; Internal subroutine of backward-delete-char
3351(defun kill-backward-chars (arg)
3352 (if (listp arg) (setq arg (car arg)))
3353 (if (eq arg '-) (setq arg -1))
673e5169 3354 (kill-region (point) (- (point) arg)))
93be67de
KH
3355
3356(defcustom backward-delete-char-untabify-method 'untabify
1d2b0303 3357 "The method for untabifying when deleting backward.
1e722f9f
SS
3358Can be `untabify' -- turn a tab to many spaces, then delete one space;
3359 `hungry' -- delete all whitespace, both tabs and spaces;
3360 `all' -- delete all whitespace, including tabs, spaces and newlines;
93be67de 3361 nil -- just delete one character."
1e722f9f 3362 :type '(choice (const untabify) (const hungry) (const all) (const nil))
03167a34 3363 :version "20.3"
93be67de
KH
3364 :group 'killing)
3365
3366(defun backward-delete-char-untabify (arg &optional killp)
3367 "Delete characters backward, changing tabs into spaces.
3368The exact behavior depends on `backward-delete-char-untabify-method'.
3369Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
3370Interactively, ARG is the prefix arg (default 1)
3371and KILLP is t if a prefix arg was specified."
3372 (interactive "*p\nP")
3373 (when (eq backward-delete-char-untabify-method 'untabify)
3374 (let ((count arg))
3375 (save-excursion
3376 (while (and (> count 0) (not (bobp)))
3377 (if (= (preceding-char) ?\t)
3378 (let ((col (current-column)))
3379 (forward-char -1)
3380 (setq col (- col (current-column)))
f33321ad 3381 (insert-char ?\s col)
93be67de
KH
3382 (delete-char 1)))
3383 (forward-char -1)
3384 (setq count (1- count))))))
3385 (delete-backward-char
1e722f9f
SS
3386 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
3387 ((eq backward-delete-char-untabify-method 'all)
3388 " \t\n\r"))))
3389 (if skip
3390 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
93be67de
KH
3391 (point)))))
3392 (+ arg (if (zerop wh) 0 (1- wh))))
1e722f9f 3393 arg))
93be67de
KH
3394 killp))
3395
3396(defun zap-to-char (arg char)
5626c14e 3397 "Kill up to and including ARGth occurrence of CHAR.
93be67de
KH
3398Case is ignored if `case-fold-search' is non-nil in the current buffer.
3399Goes backward if ARG is negative; error if CHAR not found."
e761e42c 3400 (interactive "p\ncZap to char: ")
a6c39c14
EZ
3401 ;; Avoid "obsolete" warnings for translation-table-for-input.
3402 (with-no-warnings
3403 (if (char-table-p translation-table-for-input)
3404 (setq char (or (aref translation-table-for-input char) char))))
93be67de
KH
3405 (kill-region (point) (progn
3406 (search-forward (char-to-string char) nil nil arg)
3407; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
3408 (point))))
eaae8106 3409
93be67de
KH
3410;; kill-line and its subroutines.
3411
3412(defcustom kill-whole-line nil
1d2b0303 3413 "If non-nil, `kill-line' with no arg at beg of line kills the whole line."
93be67de
KH
3414 :type 'boolean
3415 :group 'killing)
3416
3417(defun kill-line (&optional arg)
3418 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
5626c14e 3419With prefix argument ARG, kill that many lines from point.
93be67de 3420Negative arguments kill lines backward.
8be7408c 3421With zero argument, kills the text before point on the current line.
93be67de
KH
3422
3423When calling from a program, nil means \"no arg\",
3424a number counts as a prefix arg.
3425
3426To kill a whole line, when point is not at the beginning, type \
602157ab 3427\\[move-beginning-of-line] \\[kill-line] \\[kill-line].
93be67de
KH
3428
3429If `kill-whole-line' is non-nil, then this command kills the whole line
3430including its terminating newline, when used at the beginning of a line
3431with no argument. As a consequence, you can always kill a whole line
602157ab 3432by typing \\[move-beginning-of-line] \\[kill-line].
d3f22784 3433
81558867
EZ
3434If you want to append the killed line to the last killed text,
3435use \\[append-next-kill] before \\[kill-line].
3436
d3f22784
EZ
3437If the buffer is read-only, Emacs will beep and refrain from deleting
3438the line, but put the line in the kill ring anyway. This means that
1a534b89
RS
3439you can use this command to copy text from a read-only buffer.
3440\(If the variable `kill-read-only-ok' is non-nil, then this won't
3441even beep.)"
e761e42c 3442 (interactive "P")
93be67de
KH
3443 (kill-region (point)
3444 ;; It is better to move point to the other end of the kill
3445 ;; before killing. That way, in a read-only buffer, point
3446 ;; moves across the text that is copied to the kill ring.
3447 ;; The choice has no effect on undo now that undo records
3448 ;; the value of point from before the command was run.
3449 (progn
3450 (if arg
3451 (forward-visible-line (prefix-numeric-value arg))
3452 (if (eobp)
3453 (signal 'end-of-buffer nil))
5560dc5d
RS
3454 (let ((end
3455 (save-excursion
3456 (end-of-visible-line) (point))))
3457 (if (or (save-excursion
6b61353c
KH
3458 ;; If trailing whitespace is visible,
3459 ;; don't treat it as nothing.
3460 (unless show-trailing-whitespace
3461 (skip-chars-forward " \t" end))
5560dc5d
RS
3462 (= (point) end))
3463 (and kill-whole-line (bolp)))
3464 (forward-visible-line 1)
3465 (goto-char end))))
93be67de
KH
3466 (point))))
3467
348de80b
KG
3468(defun kill-whole-line (&optional arg)
3469 "Kill current line.
5626c14e
JB
3470With prefix ARG, kill that many lines starting from the current line.
3471If ARG is negative, kill backward. Also kill the preceding newline.
01ba9662 3472\(This is meant to make \\[repeat] work well with negative arguments.\)
5626c14e 3473If ARG is zero, kill current line but exclude the trailing newline."
f8b0f284 3474 (interactive "p")
186133b4 3475 (or arg (setq arg 1))
6c770e38
LT
3476 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
3477 (signal 'end-of-buffer nil))
3478 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
3479 (signal 'beginning-of-buffer nil))
3480 (unless (eq last-command 'kill-region)
3481 (kill-new "")
3482 (setq last-command 'kill-region))
348de80b 3483 (cond ((zerop arg)
6c770e38
LT
3484 ;; We need to kill in two steps, because the previous command
3485 ;; could have been a kill command, in which case the text
3486 ;; before point needs to be prepended to the current kill
3487 ;; ring entry and the text after point appended. Also, we
3488 ;; need to use save-excursion to avoid copying the same text
3489 ;; twice to the kill ring in read-only buffers.
3490 (save-excursion
3491 (kill-region (point) (progn (forward-visible-line 0) (point))))
348de80b
KG
3492 (kill-region (point) (progn (end-of-visible-line) (point))))
3493 ((< arg 0)
6c770e38
LT
3494 (save-excursion
3495 (kill-region (point) (progn (end-of-visible-line) (point))))
3496 (kill-region (point)
3497 (progn (forward-visible-line (1+ arg))
3498 (unless (bobp) (backward-char))
3499 (point))))
348de80b 3500 (t
6c770e38
LT
3501 (save-excursion
3502 (kill-region (point) (progn (forward-visible-line 0) (point))))
3503 (kill-region (point)
3504 (progn (forward-visible-line arg) (point))))))
12a93712 3505
93be67de
KH
3506(defun forward-visible-line (arg)
3507 "Move forward by ARG lines, ignoring currently invisible newlines only.
3508If ARG is negative, move backward -ARG lines.
3509If ARG is zero, move to the beginning of the current line."
3510 (condition-case nil
3511 (if (> arg 0)
12a93712
RS
3512 (progn
3513 (while (> arg 0)
93be67de 3514 (or (zerop (forward-line 1))
12a93712
RS
3515 (signal 'end-of-buffer nil))
3516 ;; If the newline we just skipped is invisible,
3517 ;; don't count it.
3518 (let ((prop
3519 (get-char-property (1- (point)) 'invisible)))
3520 (if (if (eq buffer-invisibility-spec t)
3521 prop
3522 (or (memq prop buffer-invisibility-spec)
3523 (assq prop buffer-invisibility-spec)))
3524 (setq arg (1+ arg))))
3525 (setq arg (1- arg)))
3526 ;; If invisible text follows, and it is a number of complete lines,
3527 ;; skip it.
3528 (let ((opoint (point)))
3529 (while (and (not (eobp))
3530 (let ((prop
3531 (get-char-property (point) 'invisible)))
3532 (if (eq buffer-invisibility-spec t)
3533 prop
3534 (or (memq prop buffer-invisibility-spec)
3535 (assq prop buffer-invisibility-spec)))))
3536 (goto-char
3537 (if (get-text-property (point) 'invisible)
3538 (or (next-single-property-change (point) 'invisible)
3539 (point-max))
3540 (next-overlay-change (point)))))
3541 (unless (bolp)
3542 (goto-char opoint))))
93be67de 3543 (let ((first t))
f5fd8833
JB
3544 (while (or first (<= arg 0))
3545 (if first
93be67de
KH
3546 (beginning-of-line)
3547 (or (zerop (forward-line -1))
3548 (signal 'beginning-of-buffer nil)))
12a93712
RS
3549 ;; If the newline we just moved to is invisible,
3550 ;; don't count it.
3551 (unless (bobp)
3552 (let ((prop
3553 (get-char-property (1- (point)) 'invisible)))
f5fd8833
JB
3554 (unless (if (eq buffer-invisibility-spec t)
3555 prop
3556 (or (memq prop buffer-invisibility-spec)
3557 (assq prop buffer-invisibility-spec)))
3558 (setq arg (1+ arg)))))
3559 (setq first nil))
12a93712
RS
3560 ;; If invisible text follows, and it is a number of complete lines,
3561 ;; skip it.
3562 (let ((opoint (point)))
93be67de
KH
3563 (while (and (not (bobp))
3564 (let ((prop
3565 (get-char-property (1- (point)) 'invisible)))
3566 (if (eq buffer-invisibility-spec t)
3567 prop
3568 (or (memq prop buffer-invisibility-spec)
3569 (assq prop buffer-invisibility-spec)))))
3570 (goto-char
3571 (if (get-text-property (1- (point)) 'invisible)
3572 (or (previous-single-property-change (point) 'invisible)
3573 (point-min))
12a93712
RS
3574 (previous-overlay-change (point)))))
3575 (unless (bolp)
3576 (goto-char opoint)))))
93be67de
KH
3577 ((beginning-of-buffer end-of-buffer)
3578 nil)))
70e14c01 3579
93be67de
KH
3580(defun end-of-visible-line ()
3581 "Move to end of current visible line."
3582 (end-of-line)
3583 ;; If the following character is currently invisible,
3584 ;; skip all characters with that same `invisible' property value,
3585 ;; then find the next newline.
3586 (while (and (not (eobp))
5560dc5d
RS
3587 (save-excursion
3588 (skip-chars-forward "^\n")
3589 (let ((prop
3590 (get-char-property (point) 'invisible)))
3591 (if (eq buffer-invisibility-spec t)
3592 prop
3593 (or (memq prop buffer-invisibility-spec)
3594 (assq prop buffer-invisibility-spec))))))
3595 (skip-chars-forward "^\n")
93be67de
KH
3596 (if (get-text-property (point) 'invisible)
3597 (goto-char (next-single-property-change (point) 'invisible))
3598 (goto-char (next-overlay-change (point))))
3599 (end-of-line)))
2d88b556 3600\f
2076c87c
JB
3601(defun insert-buffer (buffer)
3602 "Insert after point the contents of BUFFER.
3603Puts mark after the inserted text.
6cb6e7a2
GM
3604BUFFER may be a buffer or a buffer name.
3605
3606This function is meant for the user to run interactively.
1e96c007 3607Don't call it from programs: use `insert-buffer-substring' instead!"
c3d4f949 3608 (interactive
a3e7c391
FP
3609 (list
3610 (progn
3611 (barf-if-buffer-read-only)
3612 (read-buffer "Insert buffer: "
3613 (if (eq (selected-window) (next-window (selected-window)))
3614 (other-buffer (current-buffer))
3615 (window-buffer (next-window (selected-window))))
3616 t))))
1e96c007
SM
3617 (push-mark
3618 (save-excursion
3619 (insert-buffer-substring (get-buffer buffer))
3620 (point)))
1537a263 3621 nil)
2076c87c
JB
3622
3623(defun append-to-buffer (buffer start end)
3624 "Append to specified buffer the text of the region.
3625It is inserted into that buffer before its point.
3626
3627When calling from a program, give three arguments:
3628BUFFER (or buffer name), START and END.
3629START and END specify the portion of the current buffer to be copied."
70e14c01 3630 (interactive
5d771766 3631 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
23efee2c 3632 (region-beginning) (region-end)))
85626eef
SM
3633 (let* ((oldbuf (current-buffer))
3634 (append-to (get-buffer-create buffer))
3635 (windows (get-buffer-window-list append-to t t))
3636 point)
3637 (save-excursion
3638 (with-current-buffer append-to
3639 (setq point (point))
3640 (barf-if-buffer-read-only)
3641 (insert-buffer-substring oldbuf start end)
3642 (dolist (window windows)
3643 (when (= (window-point window) point)
3644 (set-window-point window (point))))))))
2076c87c
JB
3645
3646(defun prepend-to-buffer (buffer start end)
3647 "Prepend to specified buffer the text of the region.
3648It is inserted into that buffer after its point.
3649
3650When calling from a program, give three arguments:
3651BUFFER (or buffer name), START and END.
3652START and END specify the portion of the current buffer to be copied."
3653 (interactive "BPrepend to buffer: \nr")
3654 (let ((oldbuf (current-buffer)))
7fdbcd83 3655 (with-current-buffer (get-buffer-create buffer)
74399eac 3656 (barf-if-buffer-read-only)
2076c87c
JB
3657 (save-excursion
3658 (insert-buffer-substring oldbuf start end)))))
3659
3660(defun copy-to-buffer (buffer start end)
3661 "Copy to specified buffer the text of the region.
3662It is inserted into that buffer, replacing existing text there.
3663
3664When calling from a program, give three arguments:
3665BUFFER (or buffer name), START and END.
3666START and END specify the portion of the current buffer to be copied."
3667 (interactive "BCopy to buffer: \nr")
3668 (let ((oldbuf (current-buffer)))
1b5fd09e 3669 (with-current-buffer (get-buffer-create buffer)
74399eac 3670 (barf-if-buffer-read-only)
2076c87c
JB
3671 (erase-buffer)
3672 (save-excursion
3673 (insert-buffer-substring oldbuf start end)))))
2d88b556 3674\f
62d1c1fc 3675(put 'mark-inactive 'error-conditions '(mark-inactive error))
8f43cbf3 3676(put 'mark-inactive 'error-message (purecopy "The mark is not active now"))
62d1c1fc 3677
0251bafb
RS
3678(defvar activate-mark-hook nil
3679 "Hook run when the mark becomes active.
3680It is also run at the end of a command, if the mark is active and
6cbb0bb0 3681it is possible that the region may have changed.")
0251bafb
RS
3682
3683(defvar deactivate-mark-hook nil
3684 "Hook run when the mark becomes inactive.")
3685
af39530e 3686(defun mark (&optional force)
f00239cf
RS
3687 "Return this buffer's mark value as integer, or nil if never set.
3688
3689In Transient Mark mode, this function signals an error if
3690the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3691or the argument FORCE is non-nil, it disregards whether the mark
3692is active, and returns an integer or nil in the usual way.
af39530e 3693
2076c87c
JB
3694If you are using this in an editing command, you are most likely making
3695a mistake; see the documentation of `set-mark'."
0e3a7b14 3696 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
af39530e 3697 (marker-position (mark-marker))
62d1c1fc 3698 (signal 'mark-inactive nil)))
2076c87c 3699
f9be2e35 3700(defsubst deactivate-mark (&optional force)
19d35374 3701 "Deactivate the mark by setting `mark-active' to nil.
f9be2e35
CY
3702Unless FORCE is non-nil, this function does nothing if Transient
3703Mark mode is disabled.
3704This function also runs `deactivate-mark-hook'."
3705 (when (or transient-mark-mode force)
7c23dd44
CY
3706 (when (and (if (eq select-active-regions 'only)
3707 (eq (car-safe transient-mark-mode) 'only)
3708 select-active-regions)
9852377f
CY
3709 (region-active-p)
3710 (display-selections-p))
3711 ;; The var `saved-region-selection', if non-nil, is the text in
3712 ;; the region prior to the last command modifying the buffer.
3713 ;; Set the selection to that, or to the current region.
3714 (cond (saved-region-selection
3715 (x-set-selection 'PRIMARY saved-region-selection)
3716 (setq saved-region-selection nil))
3717 ((/= (region-beginning) (region-end))
3718 (x-set-selection 'PRIMARY
3719 (buffer-substring-no-properties
1bcb9e65
CY
3720 (region-beginning)
3721 (region-end))))))
f9be2e35
CY
3722 (if (and (null force)
3723 (or (eq transient-mark-mode 'lambda)
3724 (and (eq (car-safe transient-mark-mode) 'only)
3725 (null (cdr transient-mark-mode)))))
3726 ;; When deactivating a temporary region, don't change
3727 ;; `mark-active' or run `deactivate-mark-hook'.
109cfe4e
CY
3728 (setq transient-mark-mode nil)
3729 (if (eq (car-safe transient-mark-mode) 'only)
3730 (setq transient-mark-mode (cdr transient-mark-mode)))
3731 (setq mark-active nil)
3732 (run-hooks 'deactivate-mark-hook))))
19d35374 3733
2977fc37
SM
3734(defun activate-mark ()
3735 "Activate the mark."
3736 (when (mark t)
3737 (setq mark-active t)
3738 (unless transient-mark-mode
9852377f 3739 (setq transient-mark-mode 'lambda))))
98b2fff4 3740
2076c87c
JB
3741(defun set-mark (pos)
3742 "Set this buffer's mark to POS. Don't use this function!
3743That is to say, don't use this function unless you want
3744the user to see that the mark has moved, and you want the previous
3745mark position to be lost.
3746
3747Normally, when a new mark is set, the old one should go on the stack.
f59006cb 3748This is why most applications should use `push-mark', not `set-mark'.
2076c87c 3749
ff1fbe3e 3750Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
3751purposes. The mark saves a location for the user's convenience.
3752Most editing commands should not alter the mark.
3753To remember a location for internal use in the Lisp program,
3754store it in a Lisp variable. Example:
3755
3756 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3757
fcadf1c7
RS
3758 (if pos
3759 (progn
3760 (setq mark-active t)
3761 (run-hooks 'activate-mark-hook)
3762 (set-marker (mark-marker) pos (current-buffer)))
24c22852 3763 ;; Normally we never clear mark-active except in Transient Mark mode.
f9be2e35
CY
3764 ;; But when we actually clear out the mark value too, we must
3765 ;; clear mark-active in any mode.
3766 (deactivate-mark t)
24c22852 3767 (set-marker (mark-marker) nil)))
2076c87c 3768
d03b9b31 3769(defcustom use-empty-active-region nil
6a9127b6
CY
3770 "Whether \"region-aware\" commands should act on empty regions.
3771If nil, region-aware commands treat empty regions as inactive.
3772If non-nil, region-aware commands treat the region as active as
3773long as the mark is active, even if the region is empty.
3774
58b356e9
CY
3775Region-aware commands are those that act on the region if it is
3776active and Transient Mark mode is enabled, and on the text near
3777point otherwise."
d03b9b31
RS
3778 :type 'boolean
3779 :version "23.1"
3780 :group 'editing-basics)
3781
cb3a9d33 3782(defun use-region-p ()
6a9127b6
CY
3783 "Return t if the region is active and it is appropriate to act on it.
3784This is used by commands that act specially on the region under
16f2e9fc 3785Transient Mark mode.
6a9127b6 3786
c876b263 3787The return value is t if Transient Mark mode is enabled and the
e5b826ae
CY
3788mark is active; furthermore, if `use-empty-active-region' is nil,
3789the region must not be empty. Otherwise, the return value is nil.
16f2e9fc
CY
3790
3791For some commands, it may be appropriate to ignore the value of
3792`use-empty-active-region'; in that case, use `region-active-p'."
d34c311a 3793 (and (region-active-p)
d03b9b31
RS
3794 (or use-empty-active-region (> (region-end) (region-beginning)))))
3795
02d52519 3796(defun region-active-p ()
afa39f21 3797 "Return t if Transient Mark mode is enabled and the mark is active.
6a9127b6 3798
16f2e9fc
CY
3799Some commands act specially on the region when Transient Mark
3800mode is enabled. Usually, such commands should use
3801`use-region-p' instead of this function, because `use-region-p'
3802also checks the value of `use-empty-active-region'."
02d52519
RS
3803 (and transient-mark-mode mark-active))
3804
2076c87c 3805(defvar mark-ring nil
e55e2267 3806 "The list of former marks of the current buffer, most recent first.")
2076c87c 3807(make-variable-buffer-local 'mark-ring)
e55e2267 3808(put 'mark-ring 'permanent-local t)
2076c87c 3809
69c1dd37 3810(defcustom mark-ring-max 16
1d2b0303 3811 "Maximum size of mark ring. Start discarding off end if gets this big."
69c1dd37
RS
3812 :type 'integer
3813 :group 'editing-basics)
2076c87c 3814
dc029f0b
RM
3815(defvar global-mark-ring nil
3816 "The list of saved global marks, most recent first.")
3817
69c1dd37 3818(defcustom global-mark-ring-max 16
1d2b0303 3819 "Maximum size of global mark ring. \
69c1dd37
RS
3820Start discarding off end if gets this big."
3821 :type 'integer
3822 :group 'editing-basics)
dc029f0b 3823
868c2f49 3824(defun pop-to-mark-command ()
5626c14e
JB
3825 "Jump to mark, and pop a new position for mark off the ring.
3826\(Does not affect global mark ring\)."
868c2f49
KS
3827 (interactive)
3828 (if (null (mark t))
3829 (error "No mark set in this buffer")
fb2c06a3
RS
3830 (if (= (point) (mark t))
3831 (message "Mark popped"))
868c2f49
KS
3832 (goto-char (mark t))
3833 (pop-mark)))
3834
d00ffe21 3835(defun push-mark-command (arg &optional nomsg)
868c2f49 3836 "Set mark at where point is.
5626c14e 3837If no prefix ARG and mark is already set there, just activate it.
d00ffe21 3838Display `Mark set' unless the optional second arg NOMSG is non-nil."
868c2f49
KS
3839 (interactive "P")
3840 (let ((mark (marker-position (mark-marker))))
3841 (if (or arg (null mark) (/= mark (point)))
d00ffe21 3842 (push-mark nil nomsg t)
868c2f49 3843 (setq mark-active t)
0251bafb 3844 (run-hooks 'activate-mark-hook)
d00ffe21
KS
3845 (unless nomsg
3846 (message "Mark activated")))))
868c2f49 3847
6a936796 3848(defcustom set-mark-command-repeat-pop nil
1d2b0303 3849 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
ebd2fc0d
RS
3850That means that C-u \\[set-mark-command] \\[set-mark-command]
3851will pop the mark twice, and
3852C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
3853will pop the mark three times.
3854
7b17b503 3855A value of nil means \\[set-mark-command]'s behavior does not change
ebd2fc0d 3856after C-u \\[set-mark-command]."
6a936796 3857 :type 'boolean
034ce0ec 3858 :group 'editing-basics)
6a936796 3859
125f7951
SM
3860(defcustom set-mark-default-inactive nil
3861 "If non-nil, setting the mark does not activate it.
3862This causes \\[set-mark-command] and \\[exchange-point-and-mark] to
0fc10137
JL
3863behave the same whether or not `transient-mark-mode' is enabled."
3864 :type 'boolean
3865 :group 'editing-basics
3866 :version "23.1")
125f7951 3867
2076c87c 3868(defun set-mark-command (arg)
fb2c06a3
RS
3869 "Set the mark where point is, or jump to the mark.
3870Setting the mark also alters the region, which is the text
3871between point and mark; this is the closest equivalent in
3872Emacs to what some editors call the \"selection\".
146adea3 3873
fb2c06a3
RS
3874With no prefix argument, set the mark at point, and push the
3875old mark position on local mark ring. Also push the old mark on
3876global mark ring, if the previous mark was set in another buffer.
146adea3 3877
17923ef2
CY
3878When Transient Mark Mode is off, immediately repeating this
3879command activates `transient-mark-mode' temporarily.
66ef2df9 3880
146adea3 3881With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
fb2c06a3 3882jump to the mark, and set the mark from
146adea3
EZ
3883position popped off the local mark ring \(this does not affect the global
3884mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
66ef2df9 3885mark ring \(see `pop-global-mark'\).
18c5df40 3886
2ef0a47e 3887If `set-mark-command-repeat-pop' is non-nil, repeating
146adea3 3888the \\[set-mark-command] command with no prefix argument pops the next position
2ef0a47e 3889off the local (or global) mark ring and jumps there.
66ef2df9 3890
fb2c06a3
RS
3891With \\[universal-argument] \\[universal-argument] as prefix
3892argument, unconditionally set mark where point is, even if
3893`set-mark-command-repeat-pop' is non-nil.
7cb42362 3894
ff1fbe3e 3895Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
3896purposes. See the documentation of `set-mark' for more information."
3897 (interactive "P")
109cfe4e
CY
3898 (cond ((eq transient-mark-mode 'lambda)
3899 (setq transient-mark-mode nil))
3900 ((eq (car-safe transient-mark-mode) 'only)
3901 (deactivate-mark)))
868c2f49 3902 (cond
18c5df40
KS
3903 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3904 (push-mark-command nil))
868c2f49 3905 ((not (eq this-command 'set-mark-command))
1841f9e3
KS
3906 (if arg
3907 (pop-to-mark-command)
3908 (push-mark-command t)))
6a936796
RS
3909 ((and set-mark-command-repeat-pop
3910 (eq last-command 'pop-to-mark-command))
66ef2df9
KS
3911 (setq this-command 'pop-to-mark-command)
3912 (pop-to-mark-command))
6a936796
RS
3913 ((and set-mark-command-repeat-pop
3914 (eq last-command 'pop-global-mark)
3915 (not arg))
66ef2df9
KS
3916 (setq this-command 'pop-global-mark)
3917 (pop-global-mark))
868c2f49 3918 (arg
1841f9e3 3919 (setq this-command 'pop-to-mark-command)
868c2f49 3920 (pop-to-mark-command))
2977fc37
SM
3921 ((eq last-command 'set-mark-command)
3922 (if (region-active-p)
3923 (progn
3924 (deactivate-mark)
3925 (message "Mark deactivated"))
3926 (activate-mark)
3927 (message "Mark activated")))
868c2f49 3928 (t
125f7951
SM
3929 (push-mark-command nil)
3930 (if set-mark-default-inactive (deactivate-mark)))))
2076c87c 3931
fd0f4056 3932(defun push-mark (&optional location nomsg activate)
2076c87c 3933 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
f1382a3d
RM
3934If the last global mark pushed was not in the current buffer,
3935also push LOCATION on the global mark ring.
fd0f4056 3936Display `Mark set' unless the optional second arg NOMSG is non-nil.
2076c87c 3937
ff1fbe3e 3938Novice Emacs Lisp programmers often try to use the mark for the wrong
9a1277dd
RS
3939purposes. See the documentation of `set-mark' for more information.
3940
de9606f0 3941In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
1a0d0b6a 3942 (unless (null (mark t))
2076c87c 3943 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
1a0d0b6a
JPW
3944 (when (> (length mark-ring) mark-ring-max)
3945 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3946 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
9a1277dd 3947 (set-marker (mark-marker) (or location (point)) (current-buffer))
dc029f0b 3948 ;; Now push the mark on the global mark ring.
f1382a3d 3949 (if (and global-mark-ring
e08d3f7c 3950 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
f1382a3d
RM
3951 ;; The last global mark pushed was in this same buffer.
3952 ;; Don't push another one.
3953 nil
3954 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
1a0d0b6a
JPW
3955 (when (> (length global-mark-ring) global-mark-ring-max)
3956 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3957 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
efcf38c7 3958 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
2076c87c 3959 (message "Mark set"))
8cdc660f
RS
3960 (if (or activate (not transient-mark-mode))
3961 (set-mark (mark t)))
2076c87c
JB
3962 nil)
3963
3964(defun pop-mark ()
3965 "Pop off mark ring into the buffer's actual mark.
3966Does not set point. Does nothing if mark ring is empty."
1a0d0b6a
JPW
3967 (when mark-ring
3968 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3969 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
1a0d0b6a
JPW
3970 (move-marker (car mark-ring) nil)
3971 (if (null (mark t)) (ding))
0137bae6
JL
3972 (setq mark-ring (cdr mark-ring)))
3973 (deactivate-mark))
2076c87c 3974
c613687b
SM
3975(define-obsolete-function-alias
3976 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
868c2f49 3977(defun exchange-point-and-mark (&optional arg)
af39530e
RS
3978 "Put the mark where point is now, and point where the mark is now.
3979This command works even when the mark is not active,
868c2f49 3980and it reactivates the mark.
109cfe4e 3981
5626c14e 3982If Transient Mark mode is on, a prefix ARG deactivates the mark
109cfe4e 3983if it is active, and otherwise avoids reactivating it. If
5626c14e 3984Transient Mark mode is off, a prefix ARG enables Transient Mark
109cfe4e 3985mode temporarily."
868c2f49 3986 (interactive "P")
109cfe4e
CY
3987 (let ((omark (mark t))
3988 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
2977fc37
SM
3989 (if (null omark)
3990 (error "No mark set in this buffer"))
109cfe4e 3991 (deactivate-mark)
2977fc37
SM
3992 (set-mark (point))
3993 (goto-char omark)
125f7951 3994 (if set-mark-default-inactive (deactivate-mark))
109cfe4e
CY
3995 (cond (temp-highlight
3996 (setq transient-mark-mode (cons 'only transient-mark-mode)))
3997 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
3998 (not (or arg (region-active-p))))
3999 (deactivate-mark))
4000 (t (activate-mark)))
2977fc37 4001 nil))
e23c2c21 4002
11ff3b67 4003(defcustom shift-select-mode t
84db11d6
SM
4004 "When non-nil, shifted motion keys activate the mark momentarily.
4005
4006While the mark is activated in this way, any shift-translated point
4007motion key extends the region, and if Transient Mark mode was off, it
4008is temporarily turned on. Furthermore, the mark will be deactivated
4009by any subsequent point motion key that was not shift-translated, or
4010by any action that normally deactivates the mark in Transient Mark mode.
4011
4012See `this-command-keys-shift-translated' for the meaning of
11ff3b67
AS
4013shift-translation."
4014 :type 'boolean
4015 :group 'editing-basics)
84db11d6
SM
4016
4017(defun handle-shift-selection ()
337c561c
CY
4018 "Activate/deactivate mark depending on invocation thru shift translation.
4019This function is called by `call-interactively' when a command
4020with a `^' character in its `interactive' spec is invoked, before
4021running the command itself.
4022
4023If `shift-select-mode' is enabled and the command was invoked
4024through shift translation, set the mark and activate the region
4025temporarily, unless it was already set in this way. See
4026`this-command-keys-shift-translated' for the meaning of shift
4027translation.
4028
4029Otherwise, if the region has been activated temporarily,
4030deactivate it, and restore the variable `transient-mark-mode' to
4031its earlier value."
84db11d6 4032 (cond ((and shift-select-mode this-command-keys-shift-translated)
9852377f
CY
4033 (unless (and mark-active
4034 (eq (car-safe transient-mark-mode) 'only))
91023c68 4035 (setq transient-mark-mode
84db11d6
SM
4036 (cons 'only
4037 (unless (eq transient-mark-mode 'lambda)
4038 transient-mark-mode)))
4039 (push-mark nil nil t)))
4040 ((eq (car-safe transient-mark-mode) 'only)
4041 (setq transient-mark-mode (cdr transient-mark-mode))
4042 (deactivate-mark))))
109cfe4e 4043
6710df48 4044(define-minor-mode transient-mark-mode
e23c2c21 4045 "Toggle Transient Mark mode.
1d2b0303 4046With ARG, turn Transient Mark mode on if ARG is positive, off otherwise.
e23c2c21 4047
5dd1220d
RS
4048In Transient Mark mode, when the mark is active, the region is highlighted.
4049Changing the buffer \"deactivates\" the mark.
4050So do certain other operations that set the mark
4051but whose main purpose is something else--for example,
cfa70244
EZ
4052incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
4053
8e843bc4
EZ
4054You can also deactivate the mark by typing \\[keyboard-quit] or
4055\\[keyboard-escape-quit].
1465c66b 4056
cfa70244
EZ
4057Many commands change their behavior when Transient Mark mode is in effect
4058and the mark is active, by acting on the region instead of their usual
4c5f7215 4059default part of the buffer's text. Examples of such commands include
705a5933
JL
4060\\[comment-dwim], \\[flush-lines], \\[keep-lines], \
4061\\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
4062Invoke \\[apropos-documentation] and type \"transient\" or
4063\"mark.*active\" at the prompt, to see the documentation of
4064commands which are sensitive to the Transient Mark mode."
43d16385 4065 :global t
9d794026
GM
4066 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
4067 :variable transient-mark-mode)
109cfe4e 4068
d0c4882d
RS
4069(defvar widen-automatically t
4070 "Non-nil means it is ok for commands to call `widen' when they want to.
4071Some commands will do this in order to go to positions outside
4072the current accessible part of the buffer.
4073
4074If `widen-automatically' is nil, these commands will do something else
4075as a fallback, and won't change the buffer bounds.")
4076
38111a5a
SM
4077(defvar non-essential nil
4078 "Whether the currently executing code is performing an essential task.
4079This variable should be non-nil only when running code which should not
4080disturb the user. E.g. it can be used to prevent Tramp from prompting the
4081user for a password when we are simply scanning a set of files in the
4082background or displaying possible completions before the user even asked
4083for it.")
4084
dc029f0b
RM
4085(defun pop-global-mark ()
4086 "Pop off global mark ring and jump to the top location."
4087 (interactive)
52b6d445
RS
4088 ;; Pop entries which refer to non-existent buffers.
4089 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
4090 (setq global-mark-ring (cdr global-mark-ring)))
dc029f0b
RM
4091 (or global-mark-ring
4092 (error "No global mark set"))
4093 (let* ((marker (car global-mark-ring))
4094 (buffer (marker-buffer marker))
4095 (position (marker-position marker)))
34c31301
RS
4096 (setq global-mark-ring (nconc (cdr global-mark-ring)
4097 (list (car global-mark-ring))))
dc029f0b
RM
4098 (set-buffer buffer)
4099 (or (and (>= position (point-min))
4100 (<= position (point-max)))
d0c4882d 4101 (if widen-automatically
60aee8b2
RS
4102 (widen)
4103 (error "Global mark position is outside accessible part of buffer")))
dc029f0b
RM
4104 (goto-char position)
4105 (switch-to-buffer buffer)))
2d88b556 4106\f
95791033 4107(defcustom next-line-add-newlines nil
1d2b0303 4108 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
69c1dd37 4109 :type 'boolean
e1d6e383 4110 :version "21.1"
69c1dd37 4111 :group 'editing-basics)
38ebcf29 4112
295f6616 4113(defun next-line (&optional arg try-vscroll)
2076c87c 4114 "Move cursor vertically down ARG lines.
295f6616 4115Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
2076c87c
JB
4116If there is no character in the target line exactly under the current column,
4117the cursor is positioned after the character in that line which spans this
4118column, or at the end of the line if it is not long enough.
38ebcf29 4119If there is no line in the buffer after this one, behavior depends on the
1a2c3941
RS
4120value of `next-line-add-newlines'. If non-nil, it inserts a newline character
4121to create a line, and moves the cursor to that line. Otherwise it moves the
e47d38f6 4122cursor to the end of the buffer.
2076c87c 4123
53a22af4
CY
4124If the variable `line-move-visual' is non-nil, this command moves
4125by display lines. Otherwise, it moves by buffer lines, without
4126taking variable-width characters or continued lines into account.
4127
2076c87c 4128The command \\[set-goal-column] can be used to create
85969cb1
RS
4129a semipermanent goal column for this command.
4130Then instead of trying to move exactly vertically (or as close as possible),
4131this command moves to the specified goal column (or as close as possible).
4132The goal column is stored in the variable `goal-column', which is nil
4133when there is no goal column.
2076c87c
JB
4134
4135If you are thinking of using this in a Lisp program, consider
4136using `forward-line' instead. It is usually easier to use
4137and more reliable (no dependence on goal column, etc.)."
109cfe4e 4138 (interactive "^p\np")
6b61353c 4139 (or arg (setq arg 1))
028922cf 4140 (if (and next-line-add-newlines (= arg 1))
207d7545
GM
4141 (if (save-excursion (end-of-line) (eobp))
4142 ;; When adding a newline, don't expand an abbrev.
4143 (let ((abbrev-mode nil))
24886813 4144 (end-of-line)
15575807 4145 (insert (if use-hard-newlines hard-newline "\n")))
295f6616 4146 (line-move arg nil nil try-vscroll))
32226619 4147 (if (called-interactively-p 'interactive)
1cd095c6 4148 (condition-case err
295f6616 4149 (line-move arg nil nil try-vscroll)
1cd095c6
JL
4150 ((beginning-of-buffer end-of-buffer)
4151 (signal (car err) (cdr err))))
295f6616 4152 (line-move arg nil nil try-vscroll)))
2076c87c
JB
4153 nil)
4154
295f6616 4155(defun previous-line (&optional arg try-vscroll)
2076c87c 4156 "Move cursor vertically up ARG lines.
295f6616 4157Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
2076c87c
JB
4158If there is no character in the target line exactly over the current column,
4159the cursor is positioned after the character in that line which spans this
4160column, or at the end of the line if it is not long enough.
4161
53a22af4
CY
4162If the variable `line-move-visual' is non-nil, this command moves
4163by display lines. Otherwise, it moves by buffer lines, without
4164taking variable-width characters or continued lines into account.
4165
2076c87c 4166The command \\[set-goal-column] can be used to create
85969cb1
RS
4167a semipermanent goal column for this command.
4168Then instead of trying to move exactly vertically (or as close as possible),
4169this command moves to the specified goal column (or as close as possible).
4170The goal column is stored in the variable `goal-column', which is nil
4171when there is no goal column.
2076c87c
JB
4172
4173If you are thinking of using this in a Lisp program, consider using
c2e8a012 4174`forward-line' with a negative argument instead. It is usually easier
2076c87c 4175to use and more reliable (no dependence on goal column, etc.)."
109cfe4e 4176 (interactive "^p\np")
6b61353c 4177 (or arg (setq arg 1))
32226619 4178 (if (called-interactively-p 'interactive)
1cd095c6 4179 (condition-case err
295f6616 4180 (line-move (- arg) nil nil try-vscroll)
1cd095c6
JL
4181 ((beginning-of-buffer end-of-buffer)
4182 (signal (car err) (cdr err))))
295f6616 4183 (line-move (- arg) nil nil try-vscroll))
2076c87c 4184 nil)
eaae8106 4185
69c1dd37 4186(defcustom track-eol nil
1d2b0303 4187 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
2076c87c 4188This means moving to the end of each line moved onto.
4efebb82
CY
4189The beginning of a blank line does not count as the end of a line.
4190This has no effect when `line-move-visual' is non-nil."
69c1dd37
RS
4191 :type 'boolean
4192 :group 'editing-basics)
4193
4194(defcustom goal-column nil
1d2b0303 4195 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
69c1dd37
RS
4196 :type '(choice integer
4197 (const :tag "None" nil))
4198 :group 'editing-basics)
912c6728 4199(make-variable-buffer-local 'goal-column)
2076c87c
JB
4200
4201(defvar temporary-goal-column 0
4202 "Current goal column for vertical motion.
4efebb82 4203It is the column where point was at the start of the current run
774409a1
CY
4204of vertical motion commands.
4205
4206When moving by visual lines via `line-move-visual', it is a cons
4207cell (COL . HSCROLL), where COL is the x-position, in pixels,
4208divided by the default column width, and HSCROLL is the number of
4209columns by which window is scrolled from left margin.
4210
4211When the `track-eol' feature is doing its job, the value is
4efebb82 4212`most-positive-fixnum'.")
2076c87c 4213
bbf41690 4214(defcustom line-move-ignore-invisible t
1d2b0303 4215 "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
69c1dd37
RS
4216Outline mode sets this."
4217 :type 'boolean
4218 :group 'editing-basics)
098fc1fb 4219
a2cf21a2 4220(defcustom line-move-visual t
4efebb82
CY
4221 "When non-nil, `line-move' moves point by visual lines.
4222This movement is based on where the cursor is displayed on the
4223screen, instead of relying on buffer contents alone. It takes
66e0718b
CY
4224into account variable-width characters and line continuation.
4225If nil, `line-move' moves point by logical lines."
a2cf21a2 4226 :type 'boolean
66e0718b
CY
4227 :group 'editing-basics
4228 :version "23.1")
4efebb82 4229
b704b1f0
KS
4230;; Returns non-nil if partial move was done.
4231(defun line-move-partial (arg noerror to-end)
4232 (if (< arg 0)
4233 ;; Move backward (up).
4234 ;; If already vscrolled, reduce vscroll
4235 (let ((vs (window-vscroll nil t)))
4236 (when (> vs (frame-char-height))
4237 (set-window-vscroll nil (- vs (frame-char-height)) t)))
4238
4239 ;; Move forward (down).
e437f99a
KS
4240 (let* ((lh (window-line-height -1))
4241 (vpos (nth 1 lh))
4242 (ypos (nth 2 lh))
4243 (rbot (nth 3 lh))
3137dda8 4244 py vs)
e437f99a
KS
4245 (when (or (null lh)
4246 (>= rbot (frame-char-height))
4247 (<= ypos (- (frame-char-height))))
4248 (unless lh
0e7a5039
KS
4249 (let ((wend (pos-visible-in-window-p t nil t)))
4250 (setq rbot (nth 3 wend)
4251 vpos (nth 5 wend))))
e437f99a
KS
4252 (cond
4253 ;; If last line of window is fully visible, move forward.
4254 ((or (null rbot) (= rbot 0))
4255 nil)
4256 ;; If cursor is not in the bottom scroll margin, move forward.
4257 ((and (> vpos 0)
95f5a37f
KS
4258 (< (setq py
4259 (or (nth 1 (window-line-height))
4260 (let ((ppos (posn-at-point)))
4261 (cdr (or (posn-actual-col-row ppos)
4262 (posn-col-row ppos))))))
e437f99a
KS
4263 (min (- (window-text-height) scroll-margin 1) (1- vpos))))
4264 nil)
4265 ;; When already vscrolled, we vscroll some more if we can,
4266 ;; or clear vscroll and move forward at end of tall image.
4267 ((> (setq vs (window-vscroll nil t)) 0)
4268 (when (> rbot 0)
4269 (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
4270 ;; If cursor just entered the bottom scroll margin, move forward,
4271 ;; but also vscroll one line so redisplay wont recenter.
4272 ((and (> vpos 0)
4273 (= py (min (- (window-text-height) scroll-margin 1)
4274 (1- vpos))))
4275 (set-window-vscroll nil (frame-char-height) t)
4276 (line-move-1 arg noerror to-end)
4277 t)
4278 ;; If there are lines above the last line, scroll-up one line.
4279 ((> vpos 0)
4280 (scroll-up 1)
4281 t)
4282 ;; Finally, start vscroll.
4283 (t
4284 (set-window-vscroll nil (frame-char-height) t)))))))
b704b1f0
KS
4285
4286
03ceda9e
RS
4287;; This is like line-move-1 except that it also performs
4288;; vertical scrolling of tall images if appropriate.
4289;; That is not really a clean thing to do, since it mixes
4290;; scrolling with cursor motion. But so far we don't have
4291;; a cleaner solution to the problem of making C-n do something
4292;; useful given a tall image.
ed02c1db 4293(defun line-move (arg &optional noerror to-end try-vscroll)
b704b1f0
KS
4294 (unless (and auto-window-vscroll try-vscroll
4295 ;; Only vscroll for single line moves
4296 (= (abs arg) 1)
4297 ;; But don't vscroll in a keyboard macro.
4298 (not defining-kbd-macro)
4299 (not executing-kbd-macro)
4300 (line-move-partial arg noerror to-end))
4301 (set-window-vscroll nil 0 t)
4efebb82
CY
4302 (if line-move-visual
4303 (line-move-visual arg noerror)
4304 (line-move-1 arg noerror to-end))))
4305
4306;; Display-based alternative to line-move-1.
4307;; Arg says how many lines to move. The value is t if we can move the
4308;; specified number of lines.
4309(defun line-move-visual (arg &optional noerror)
34be836c 4310 (let ((opoint (point))
774409a1 4311 (hscroll (window-hscroll))
34be836c 4312 target-hscroll)
774409a1
CY
4313 ;; Check if the previous command was a line-motion command, or if
4314 ;; we were called from some other command.
34be836c
CY
4315 (if (and (consp temporary-goal-column)
4316 (memq last-command `(next-line previous-line ,this-command)))
4317 ;; If so, there's no need to reset `temporary-goal-column',
4318 ;; but we may need to hscroll.
4319 (if (or (/= (cdr temporary-goal-column) hscroll)
4320 (> (cdr temporary-goal-column) 0))
4321 (setq target-hscroll (cdr temporary-goal-column)))
4322 ;; Otherwise, we should reset `temporary-goal-column'.
4323 (let ((posn (posn-at-point)))
4324 (cond
4325 ;; Handle the `overflow-newline-into-fringe' case:
4326 ((eq (nth 1 posn) 'right-fringe)
4327 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
4328 ((car (posn-x-y posn))
4329 (setq temporary-goal-column
4330 (cons (/ (float (car (posn-x-y posn)))
4331 (frame-char-width)) hscroll))))))
4332 (if target-hscroll
4333 (set-window-hscroll (selected-window) target-hscroll))
624a662f 4334 (or (and (= (vertical-motion
774409a1
CY
4335 (cons (or goal-column
4336 (if (consp temporary-goal-column)
5a66ed0f 4337 (car temporary-goal-column)
774409a1
CY
4338 temporary-goal-column))
4339 arg))
624a662f
CY
4340 arg)
4341 (or (>= arg 0)
4342 (/= (point) opoint)
4343 ;; If the goal column lies on a display string,
4344 ;; `vertical-motion' advances the cursor to the end
4345 ;; of the string. For arg < 0, this can cause the
4346 ;; cursor to get stuck. (Bug#3020).
4347 (= (vertical-motion arg) arg)))
4348 (unless noerror
4349 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
4350 nil)))))
16c2f92f 4351
8c745744
RS
4352;; This is the guts of next-line and previous-line.
4353;; Arg says how many lines to move.
bbf41690 4354;; The value is t if we can move the specified number of lines.
16c2f92f 4355(defun line-move-1 (arg &optional noerror to-end)
2596511d
RS
4356 ;; Don't run any point-motion hooks, and disregard intangibility,
4357 ;; for intermediate positions.
4358 (let ((inhibit-point-motion-hooks t)
4359 (opoint (point))
fef11f15 4360 (orig-arg arg))
774409a1
CY
4361 (if (consp temporary-goal-column)
4362 (setq temporary-goal-column (+ (car temporary-goal-column)
4363 (cdr temporary-goal-column))))
2596511d
RS
4364 (unwind-protect
4365 (progn
41d22ee0 4366 (if (not (memq last-command '(next-line previous-line)))
2596511d
RS
4367 (setq temporary-goal-column
4368 (if (and track-eol (eolp)
4369 ;; Don't count beg of empty line as end of line
4370 ;; unless we just did explicit end-of-line.
ab9623c2 4371 (or (not (bolp)) (eq last-command 'move-end-of-line)))
3137dda8 4372 most-positive-fixnum
2596511d 4373 (current-column))))
bbf41690 4374
3137dda8
SM
4375 (if (not (or (integerp selective-display)
4376 line-move-ignore-invisible))
2596511d 4377 ;; Use just newline characters.
e9cd25fe 4378 ;; Set ARG to 0 if we move as many lines as requested.
2596511d
RS
4379 (or (if (> arg 0)
4380 (progn (if (> arg 1) (forward-line (1- arg)))
4381 ;; This way of moving forward ARG lines
4382 ;; verifies that we have a newline after the last one.
4383 ;; It doesn't get confused by intangible text.
4384 (end-of-line)
e9cd25fe
RS
4385 (if (zerop (forward-line 1))
4386 (setq arg 0)))
2596511d 4387 (and (zerop (forward-line arg))
e9cd25fe
RS
4388 (bolp)
4389 (setq arg 0)))
bbf41690
RS
4390 (unless noerror
4391 (signal (if (< arg 0)
4392 'beginning-of-buffer
4393 'end-of-buffer)
4394 nil)))
2596511d 4395 ;; Move by arg lines, but ignore invisible ones.
07889873 4396 (let (done)
bbf41690
RS
4397 (while (and (> arg 0) (not done))
4398 ;; If the following character is currently invisible,
4399 ;; skip all characters with that same `invisible' property value.
c65e6942 4400 (while (and (not (eobp)) (invisible-p (point)))
bbf41690 4401 (goto-char (next-char-property-change (point))))
fef11f15
CY
4402 ;; Move a line.
4403 ;; We don't use `end-of-line', since we want to escape
40b1a3a9 4404 ;; from field boundaries occurring exactly at point.
07889873
CY
4405 (goto-char (constrain-to-field
4406 (let ((inhibit-field-text-motion t))
4407 (line-end-position))
4408 (point) t t
4409 'inhibit-line-move-field-capture))
e9ab825f 4410 ;; If there's no invisibility here, move over the newline.
3e43ae87
KS
4411 (cond
4412 ((eobp)
4413 (if (not noerror)
4414 (signal 'end-of-buffer nil)
4415 (setq done t)))
4416 ((and (> arg 1) ;; Use vertical-motion for last move
4417 (not (integerp selective-display))
c65e6942 4418 (not (invisible-p (point))))
3e43ae87
KS
4419 ;; We avoid vertical-motion when possible
4420 ;; because that has to fontify.
4421 (forward-line 1))
4422 ;; Otherwise move a more sophisticated way.
4423 ((zerop (vertical-motion 1))
4424 (if (not noerror)
4425 (signal 'end-of-buffer nil)
4426 (setq done t))))
bbf41690
RS
4427 (unless done
4428 (setq arg (1- arg))))
22c8bff1 4429 ;; The logic of this is the same as the loop above,
e9ab825f 4430 ;; it just goes in the other direction.
bbf41690 4431 (while (and (< arg 0) (not done))
ac6701ea
CY
4432 ;; For completely consistency with the forward-motion
4433 ;; case, we should call beginning-of-line here.
4434 ;; However, if point is inside a field and on a
4435 ;; continued line, the call to (vertical-motion -1)
4436 ;; below won't move us back far enough; then we return
4437 ;; to the same column in line-move-finish, and point
4438 ;; gets stuck -- cyd
4439 (forward-line 0)
3e43ae87
KS
4440 (cond
4441 ((bobp)
4442 (if (not noerror)
4443 (signal 'beginning-of-buffer nil)
4444 (setq done t)))
4445 ((and (< arg -1) ;; Use vertical-motion for last move
4446 (not (integerp selective-display))
c65e6942 4447 (not (invisible-p (1- (point)))))
3e43ae87
KS
4448 (forward-line -1))
4449 ((zerop (vertical-motion -1))
4450 (if (not noerror)
4451 (signal 'beginning-of-buffer nil)
4452 (setq done t))))
bbf41690
RS
4453 (unless done
4454 (setq arg (1+ arg))
4455 (while (and ;; Don't move over previous invis lines
4456 ;; if our target is the middle of this line.
4457 (or (zerop (or goal-column temporary-goal-column))
4458 (< arg 0))
c65e6942 4459 (not (bobp)) (invisible-p (1- (point))))
bbf41690
RS
4460 (goto-char (previous-char-property-change (point))))))))
4461 ;; This is the value the function returns.
4462 (= arg 0))
af894fc9 4463
e9cd25fe 4464 (cond ((> arg 0)
2a1e0c92
CY
4465 ;; If we did not move down as far as desired, at least go
4466 ;; to end of line. Be sure to call point-entered and
4467 ;; point-left-hooks.
4468 (let* ((npoint (prog1 (line-end-position)
4469 (goto-char opoint)))
4470 (inhibit-point-motion-hooks nil))
4471 (goto-char npoint)))
e9cd25fe 4472 ((< arg 0)
f9872a6b
JL
4473 ;; If we did not move up as far as desired,
4474 ;; at least go to beginning of line.
2a1e0c92
CY
4475 (let* ((npoint (prog1 (line-beginning-position)
4476 (goto-char opoint)))
4477 (inhibit-point-motion-hooks nil))
4478 (goto-char npoint)))
e9cd25fe 4479 (t
20782abb 4480 (line-move-finish (or goal-column temporary-goal-column)
fef11f15 4481 opoint (> orig-arg 0)))))))
2076c87c 4482
20782abb 4483(defun line-move-finish (column opoint forward)
af894fc9
RS
4484 (let ((repeat t))
4485 (while repeat
4486 ;; Set REPEAT to t to repeat the whole thing.
4487 (setq repeat nil)
4488
1f980920 4489 (let (new
963355a4 4490 (old (point))
5ed619e0 4491 (line-beg (line-beginning-position))
1f980920
RS
4492 (line-end
4493 ;; Compute the end of the line
20782abb 4494 ;; ignoring effectively invisible newlines.
bbf41690 4495 (save-excursion
a5b4a6a0
RS
4496 ;; Like end-of-line but ignores fields.
4497 (skip-chars-forward "^\n")
c65e6942 4498 (while (and (not (eobp)) (invisible-p (point)))
20782abb 4499 (goto-char (next-char-property-change (point)))
a5b4a6a0 4500 (skip-chars-forward "^\n"))
bbf41690 4501 (point))))
1f980920
RS
4502
4503 ;; Move to the desired column.
54b99340 4504 (line-move-to-column (truncate column))
963355a4
CY
4505
4506 ;; Corner case: suppose we start out in a field boundary in
4507 ;; the middle of a continued line. When we get to
4508 ;; line-move-finish, point is at the start of a new *screen*
4509 ;; line but the same text line; then line-move-to-column would
4510 ;; move us backwards. Test using C-n with point on the "x" in
4511 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
4512 (and forward
4513 (< (point) old)
4514 (goto-char old))
4515
1f980920 4516 (setq new (point))
af894fc9
RS
4517
4518 ;; Process intangibility within a line.
594a1605
CY
4519 ;; With inhibit-point-motion-hooks bound to nil, a call to
4520 ;; goto-char moves point past intangible text.
4521
4522 ;; However, inhibit-point-motion-hooks controls both the
4523 ;; intangibility and the point-entered/point-left hooks. The
4524 ;; following hack avoids calling the point-* hooks
4525 ;; unnecessarily. Note that we move *forward* past intangible
4526 ;; text when the initial and final points are the same.
d584e29d 4527 (goto-char new)
af894fc9
RS
4528 (let ((inhibit-point-motion-hooks nil))
4529 (goto-char new)
4530
4531 ;; If intangibility moves us to a different (later) place
4532 ;; in the same line, use that as the destination.
4533 (if (<= (point) line-end)
1f980920
RS
4534 (setq new (point))
4535 ;; If that position is "too late",
4536 ;; try the previous allowable position.
4537 ;; See if it is ok.
4538 (backward-char)
20782abb
RS
4539 (if (if forward
4540 ;; If going forward, don't accept the previous
4541 ;; allowable position if it is before the target line.
f1e2a033 4542 (< line-beg (point))
20782abb
RS
4543 ;; If going backward, don't accept the previous
4544 ;; allowable position if it is still after the target line.
4545 (<= (point) line-end))
1f980920
RS
4546 (setq new (point))
4547 ;; As a last resort, use the end of the line.
4548 (setq new line-end))))
af894fc9
RS
4549
4550 ;; Now move to the updated destination, processing fields
4551 ;; as well as intangibility.
4552 (goto-char opoint)
4553 (let ((inhibit-point-motion-hooks nil))
4554 (goto-char
e94e78cc
CY
4555 ;; Ignore field boundaries if the initial and final
4556 ;; positions have the same `field' property, even if the
4557 ;; fields are non-contiguous. This seems to be "nicer"
4558 ;; behavior in many situations.
4559 (if (eq (get-char-property new 'field)
4560 (get-char-property opoint 'field))
4561 new
4562 (constrain-to-field new opoint t t
4563 'inhibit-line-move-field-capture))))
af894fc9 4564
1f980920 4565 ;; If all this moved us to a different line,
af894fc9
RS
4566 ;; retry everything within that new line.
4567 (when (or (< (point) line-beg) (> (point) line-end))
4568 ;; Repeat the intangibility and field processing.
4569 (setq repeat t))))))
4570
4571(defun line-move-to-column (col)
4572 "Try to find column COL, considering invisibility.
4573This function works only in certain cases,
4574because what we really need is for `move-to-column'
4575and `current-column' to be able to ignore invisible text."
a615252b
RS
4576 (if (zerop col)
4577 (beginning-of-line)
095f9ae4 4578 (move-to-column col))
af894fc9
RS
4579
4580 (when (and line-move-ignore-invisible
c65e6942 4581 (not (bolp)) (invisible-p (1- (point))))
af894fc9
RS
4582 (let ((normal-location (point))
4583 (normal-column (current-column)))
4584 ;; If the following character is currently invisible,
4585 ;; skip all characters with that same `invisible' property value.
4586 (while (and (not (eobp))
c65e6942 4587 (invisible-p (point)))
af894fc9
RS
4588 (goto-char (next-char-property-change (point))))
4589 ;; Have we advanced to a larger column position?
4590 (if (> (current-column) normal-column)
4591 ;; We have made some progress towards the desired column.
4592 ;; See if we can make any further progress.
4593 (line-move-to-column (+ (current-column) (- col normal-column)))
4594 ;; Otherwise, go to the place we originally found
4595 ;; and move back over invisible text.
4596 ;; that will get us to the same place on the screen
4597 ;; but with a more reasonable buffer position.
4598 (goto-char normal-location)
5ed619e0 4599 (let ((line-beg (line-beginning-position)))
c65e6942 4600 (while (and (not (bolp)) (invisible-p (1- (point))))
af894fc9
RS
4601 (goto-char (previous-char-property-change (point) line-beg))))))))
4602
bbf41690 4603(defun move-end-of-line (arg)
f00239cf 4604 "Move point to end of current line as displayed.
bbf41690
RS
4605With argument ARG not nil or 1, move forward ARG - 1 lines first.
4606If point reaches the beginning or end of buffer, it stops there.
fdb77e6f
CY
4607
4608To ignore the effects of the `intangible' text or overlay
4609property, bind `inhibit-point-motion-hooks' to t.
4610If there is an image in the current line, this function
4611disregards newlines that are part of the text on which the image
4612rests."
109cfe4e 4613 (interactive "^p")
bbf41690
RS
4614 (or arg (setq arg 1))
4615 (let (done)
4616 (while (not done)
4617 (let ((newpos
4618 (save-excursion
4efebb82
CY
4619 (let ((goal-column 0)
4620 (line-move-visual nil))
bbf41690 4621 (and (line-move arg t)
3f2e7735
EZ
4622 ;; With bidi reordering, we may not be at bol,
4623 ;; so make sure we are.
4624 (skip-chars-backward "^\n")
bbf41690
RS
4625 (not (bobp))
4626 (progn
c65e6942 4627 (while (and (not (bobp)) (invisible-p (1- (point))))
3137dda8
SM
4628 (goto-char (previous-single-char-property-change
4629 (point) 'invisible)))
bbf41690
RS
4630 (backward-char 1)))
4631 (point)))))
4632 (goto-char newpos)
4633 (if (and (> (point) newpos)
4634 (eq (preceding-char) ?\n))
4635 (backward-char 1)
4636 (if (and (> (point) newpos) (not (eobp))
4637 (not (eq (following-char) ?\n)))
4efebb82
CY
4638 ;; If we skipped something intangible and now we're not
4639 ;; really at eol, keep going.
bbf41690
RS
4640 (setq arg 1)
4641 (setq done t)))))))
4642
0cbb497c 4643(defun move-beginning-of-line (arg)
f00239cf
RS
4644 "Move point to beginning of current line as displayed.
4645\(If there's an image in the line, this disregards newlines
4646which are part of the text that the image rests on.)
4647
0cbb497c
KS
4648With argument ARG not nil or 1, move forward ARG - 1 lines first.
4649If point reaches the beginning or end of buffer, it stops there.
f00239cf 4650To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
109cfe4e 4651 (interactive "^p")
0cbb497c 4652 (or arg (setq arg 1))
398c9ffb 4653
ad47c4a0 4654 (let ((orig (point))
3137dda8 4655 first-vis first-vis-field-value)
1fffd65f
RS
4656
4657 ;; Move by lines, if ARG is not 1 (the default).
4658 (if (/= arg 1)
4efebb82
CY
4659 (let ((line-move-visual nil))
4660 (line-move (1- arg) t)))
1fffd65f
RS
4661
4662 ;; Move to beginning-of-line, ignoring fields and invisibles.
4663 (skip-chars-backward "^\n")
c65e6942 4664 (while (and (not (bobp)) (invisible-p (1- (point))))
621a4cc8 4665 (goto-char (previous-char-property-change (point)))
1fffd65f 4666 (skip-chars-backward "^\n"))
ad47c4a0
RS
4667
4668 ;; Now find first visible char in the line
c65e6942 4669 (while (and (not (eobp)) (invisible-p (point)))
ad47c4a0
RS
4670 (goto-char (next-char-property-change (point))))
4671 (setq first-vis (point))
4672
4673 ;; See if fields would stop us from reaching FIRST-VIS.
4674 (setq first-vis-field-value
4675 (constrain-to-field first-vis orig (/= arg 1) t nil))
4676
4677 (goto-char (if (/= first-vis-field-value first-vis)
4678 ;; If yes, obey them.
4679 first-vis-field-value
4680 ;; Otherwise, move to START with attention to fields.
4681 ;; (It is possible that fields never matter in this case.)
4682 (constrain-to-field (point) orig
4683 (/= arg 1) t nil)))))
0cbb497c
KS
4684
4685
85be9ec4
SM
4686;; Many people have said they rarely use this feature, and often type
4687;; it by accident. Maybe it shouldn't even be on a key.
d5ab2033 4688(put 'set-goal-column 'disabled t)
2076c87c
JB
4689
4690(defun set-goal-column (arg)
4691 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
4692Those commands will move to this position in the line moved to
4693rather than trying to keep the same horizontal position.
5626c14e 4694With a non-nil argument ARG, clears out the goal column
912c6728
RS
4695so that \\[next-line] and \\[previous-line] resume vertical motion.
4696The goal column is stored in the variable `goal-column'."
2076c87c
JB
4697 (interactive "P")
4698 (if arg
4699 (progn
4700 (setq goal-column nil)
4701 (message "No goal column"))
4702 (setq goal-column (current-column))
8a26c165
DG
4703 ;; The older method below can be erroneous if `set-goal-column' is bound
4704 ;; to a sequence containing %
4705 ;;(message (substitute-command-keys
4706 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
4707 ;;goal-column)
4708 (message "%s"
63219d53 4709 (concat
8a26c165
DG
4710 (format "Goal column %d " goal-column)
4711 (substitute-command-keys
4712 "(use \\[set-goal-column] with an arg to unset it)")))
63219d53 4713
8a26c165 4714 )
2076c87c 4715 nil)
2d88b556 4716\f
a2cf21a2
CY
4717;;; Editing based on visual lines, as opposed to logical lines.
4718
4719(defun end-of-visual-line (&optional n)
4720 "Move point to end of current visual line.
4721With argument N not nil or 1, move forward N - 1 visual lines first.
4722If point reaches the beginning or end of buffer, it stops there.
4723To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4724 (interactive "^p")
4725 (or n (setq n 1))
4726 (if (/= n 1)
4727 (let ((line-move-visual t))
4728 (line-move (1- n) t)))
ef187c24
CY
4729 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
4730 ;; constrain to field boundaries, so we don't either.
a2cf21a2
CY
4731 (vertical-motion (cons (window-width) 0)))
4732
4733(defun beginning-of-visual-line (&optional n)
4734 "Move point to beginning of current visual line.
4735With argument N not nil or 1, move forward N - 1 visual lines first.
4736If point reaches the beginning or end of buffer, it stops there.
4737To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4738 (interactive "^p")
4739 (or n (setq n 1))
ef187c24
CY
4740 (let ((opoint (point)))
4741 (if (/= n 1)
4742 (let ((line-move-visual t))
4743 (line-move (1- n) t)))
4744 (vertical-motion 0)
4745 ;; Constrain to field boundaries, like `move-beginning-of-line'.
4746 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
a2cf21a2
CY
4747
4748(defun kill-visual-line (&optional arg)
4749 "Kill the rest of the visual line.
ad4c1f62
CY
4750With prefix argument ARG, kill that many visual lines from point.
4751If ARG is negative, kill visual lines backward.
4752If ARG is zero, kill the text before point on the current visual
4753line.
a2cf21a2
CY
4754
4755If you want to append the killed line to the last killed text,
4756use \\[append-next-kill] before \\[kill-line].
4757
4758If the buffer is read-only, Emacs will beep and refrain from deleting
4759the line, but put the line in the kill ring anyway. This means that
4760you can use this command to copy text from a read-only buffer.
4761\(If the variable `kill-read-only-ok' is non-nil, then this won't
4762even beep.)"
4763 (interactive "P")
ad4c1f62
CY
4764 ;; Like in `kill-line', it's better to move point to the other end
4765 ;; of the kill before killing.
2066b4fe
CY
4766 (let ((opoint (point))
4767 (kill-whole-line (and kill-whole-line (bolp))))
a2cf21a2
CY
4768 (if arg
4769 (vertical-motion (prefix-numeric-value arg))
ad4c1f62
CY
4770 (end-of-visual-line 1)
4771 (if (= (point) opoint)
4772 (vertical-motion 1)
4773 ;; Skip any trailing whitespace at the end of the visual line.
4774 ;; We used to do this only if `show-trailing-whitespace' is
4775 ;; nil, but that's wrong; the correct thing would be to check
4776 ;; whether the trailing whitespace is highlighted. But, it's
4777 ;; OK to just do this unconditionally.
4778 (skip-chars-forward " \t")))
2066b4fe
CY
4779 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
4780 (1+ (point))
4781 (point)))))
a2cf21a2
CY
4782
4783(defun next-logical-line (&optional arg try-vscroll)
4784 "Move cursor vertically down ARG lines.
1d2b0303 4785This is identical to `next-line', except that it always moves
a2cf21a2
CY
4786by logical lines instead of visual lines, ignoring the value of
4787the variable `line-move-visual'."
4788 (interactive "^p\np")
4789 (let ((line-move-visual nil))
4790 (with-no-warnings
4791 (next-line arg try-vscroll))))
4792
4793(defun previous-logical-line (&optional arg try-vscroll)
4794 "Move cursor vertically up ARG lines.
4795This is identical to `previous-line', except that it always moves
4796by logical lines instead of visual lines, ignoring the value of
4797the variable `line-move-visual'."
4798 (interactive "^p\np")
4799 (let ((line-move-visual nil))
4800 (with-no-warnings
4801 (previous-line arg try-vscroll))))
4802
4dec5cff
CY
4803(defgroup visual-line nil
4804 "Editing based on visual lines."
4805 :group 'convenience
4806 :version "23.1")
4807
a2cf21a2
CY
4808(defvar visual-line-mode-map
4809 (let ((map (make-sparse-keymap)))
4810 (define-key map [remap kill-line] 'kill-visual-line)
4811 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
4812 (define-key map [remap move-end-of-line] 'end-of-visual-line)
b316b2b8
CY
4813 ;; These keybindings interfere with xterm function keys. Are
4814 ;; there any other suitable bindings?
4815 ;; (define-key map "\M-[" 'previous-logical-line)
4816 ;; (define-key map "\M-]" 'next-logical-line)
a2cf21a2
CY
4817 map))
4818
4dec5cff
CY
4819(defcustom visual-line-fringe-indicators '(nil nil)
4820 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
4821The value should be a list of the form (LEFT RIGHT), where LEFT
4822and RIGHT are symbols representing the bitmaps to display, to
4823indicate wrapped lines, in the left and right fringes respectively.
4824See also `fringe-indicator-alist'.
4825The default is not to display fringe indicators for wrapped lines.
4826This variable does not affect fringe indicators displayed for
4827other purposes."
4828 :type '(list (choice (const :tag "Hide left indicator" nil)
4829 (const :tag "Left curly arrow" left-curly-arrow)
4830 (symbol :tag "Other bitmap"))
4831 (choice (const :tag "Hide right indicator" nil)
4832 (const :tag "Right curly arrow" right-curly-arrow)
4833 (symbol :tag "Other bitmap")))
4834 :set (lambda (symbol value)
4835 (dolist (buf (buffer-list))
4836 (with-current-buffer buf
4837 (when (and (boundp 'visual-line-mode)
4838 (symbol-value 'visual-line-mode))
4839 (setq fringe-indicator-alist
4840 (cons (cons 'continuation value)
4841 (assq-delete-all
4842 'continuation
4843 (copy-tree fringe-indicator-alist)))))))
4844 (set-default symbol value)))
4845
748e001a
CY
4846(defvar visual-line--saved-state nil)
4847
a2cf21a2 4848(define-minor-mode visual-line-mode
b677cb96
CY
4849 "Redefine simple editing commands to act on visual lines, not logical lines.
4850This also turns on `word-wrap' in the buffer."
a2cf21a2 4851 :keymap visual-line-mode-map
4dec5cff 4852 :group 'visual-line
ea92f9f3 4853 :lighter " Wrap"
a2cf21a2
CY
4854 (if visual-line-mode
4855 (progn
748e001a
CY
4856 (set (make-local-variable 'visual-line--saved-state) nil)
4857 ;; Save the local values of some variables, to be restored if
4858 ;; visual-line-mode is turned off.
4859 (dolist (var '(line-move-visual truncate-lines
4860 truncate-partial-width-windows
4861 word-wrap fringe-indicator-alist))
4862 (if (local-variable-p var)
37820ea9 4863 (push (cons var (symbol-value var))
748e001a 4864 visual-line--saved-state)))
a2cf21a2 4865 (set (make-local-variable 'line-move-visual) t)
c58140f4
CY
4866 (set (make-local-variable 'truncate-partial-width-windows) nil)
4867 (setq truncate-lines nil
4868 word-wrap t
4869 fringe-indicator-alist
4dec5cff
CY
4870 (cons (cons 'continuation visual-line-fringe-indicators)
4871 fringe-indicator-alist)))
a2cf21a2 4872 (kill-local-variable 'line-move-visual)
4dec5cff 4873 (kill-local-variable 'word-wrap)
c58140f4
CY
4874 (kill-local-variable 'truncate-lines)
4875 (kill-local-variable 'truncate-partial-width-windows)
748e001a
CY
4876 (kill-local-variable 'fringe-indicator-alist)
4877 (dolist (saved visual-line--saved-state)
4878 (set (make-local-variable (car saved)) (cdr saved)))
4879 (kill-local-variable 'visual-line--saved-state)))
a2cf21a2
CY
4880
4881(defun turn-on-visual-line-mode ()
4882 (visual-line-mode 1))
4883
4884(define-globalized-minor-mode global-visual-line-mode
4885 visual-line-mode turn-on-visual-line-mode
4886 :lighter " vl")
5a97d2da 4887
2d88b556 4888\f
2076c87c
JB
4889(defun transpose-chars (arg)
4890 "Interchange characters around point, moving forward one character.
4891With prefix arg ARG, effect is to take character before point
4892and drag it forward past ARG other characters (backward if ARG negative).
4893If no argument and at end of line, the previous two chars are exchanged."
4894 (interactive "*P")
4895 (and (null arg) (eolp) (forward-char -1))
4896 (transpose-subr 'forward-char (prefix-numeric-value arg)))
4897
4898(defun transpose-words (arg)
4899 "Interchange words around point, leaving point at end of them.
4900With prefix arg ARG, effect is to take word before or around point
4901and drag it forward past ARG other words (backward if ARG negative).
4902If ARG is zero, the words around or after point and around or after mark
4903are interchanged."
41d22ee0 4904 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
2076c87c
JB
4905 (interactive "*p")
4906 (transpose-subr 'forward-word arg))
4907
4908(defun transpose-sexps (arg)
4909 "Like \\[transpose-words] but applies to sexps.
4910Does not work on a sexp that point is in the middle of
4911if it is a list or string."
4912 (interactive "*p")
41d22ee0
SM
4913 (transpose-subr
4914 (lambda (arg)
4915 ;; Here we should try to simulate the behavior of
4916 ;; (cons (progn (forward-sexp x) (point))
4917 ;; (progn (forward-sexp (- x)) (point)))
4918 ;; Except that we don't want to rely on the second forward-sexp
4919 ;; putting us back to where we want to be, since forward-sexp-function
4920 ;; might do funny things like infix-precedence.
4921 (if (if (> arg 0)
4922 (looking-at "\\sw\\|\\s_")
4923 (and (not (bobp))
4924 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
4925 ;; Jumping over a symbol. We might be inside it, mind you.
4926 (progn (funcall (if (> arg 0)
4927 'skip-syntax-backward 'skip-syntax-forward)
4928 "w_")
4929 (cons (save-excursion (forward-sexp arg) (point)) (point)))
4930 ;; Otherwise, we're between sexps. Take a step back before jumping
4931 ;; to make sure we'll obey the same precedence no matter which direction
4932 ;; we're going.
4933 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
4934 (cons (save-excursion (forward-sexp arg) (point))
4935 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
4936 (not (zerop (funcall (if (> arg 0)
4937 'skip-syntax-forward
4938 'skip-syntax-backward)
4939 ".")))))
4940 (point)))))
4941 arg 'special))
2076c87c
JB
4942
4943(defun transpose-lines (arg)
4944 "Exchange current line and previous line, leaving point after both.
4945With argument ARG, takes previous line and moves it past ARG lines.
4946With argument 0, interchanges line point is in with line mark is in."
4947 (interactive "*p")
4948 (transpose-subr (function
4949 (lambda (arg)
d3f4ef3f 4950 (if (> arg 0)
2076c87c 4951 (progn
d3f4ef3f
AS
4952 ;; Move forward over ARG lines,
4953 ;; but create newlines if necessary.
4954 (setq arg (forward-line arg))
4955 (if (/= (preceding-char) ?\n)
4956 (setq arg (1+ arg)))
4957 (if (> arg 0)
4958 (newline arg)))
2076c87c
JB
4959 (forward-line arg))))
4960 arg))
4961
36020642
GM
4962;; FIXME seems to leave point BEFORE the current object when ARG = 0,
4963;; which seems inconsistent with the ARG /= 0 case.
4964;; FIXME document SPECIAL.
e1e04350 4965(defun transpose-subr (mover arg &optional special)
36020642
GM
4966 "Subroutine to do the work of transposing objects.
4967Works for lines, sentences, paragraphs, etc. MOVER is a function that
4968moves forward by units of the given object (e.g. forward-sentence,
4969forward-paragraph). If ARG is zero, exchanges the current object
4970with the one containing mark. If ARG is an integer, moves the
4971current object past ARG following (if ARG is positive) or
4972preceding (if ARG is negative) objects, leaving point after the
4973current object."
e1e04350
SM
4974 (let ((aux (if special mover
4975 (lambda (x)
4976 (cons (progn (funcall mover x) (point))
4977 (progn (funcall mover (- x)) (point))))))
4978 pos1 pos2)
4979 (cond
4980 ((= arg 0)
4981 (save-excursion
4982 (setq pos1 (funcall aux 1))
41849bf9 4983 (goto-char (or (mark) (error "No mark set in this buffer")))
e1e04350
SM
4984 (setq pos2 (funcall aux 1))
4985 (transpose-subr-1 pos1 pos2))
4986 (exchange-point-and-mark))
4987 ((> arg 0)
4988 (setq pos1 (funcall aux -1))
4989 (setq pos2 (funcall aux arg))
4990 (transpose-subr-1 pos1 pos2)
4991 (goto-char (car pos2)))
4992 (t
4993 (setq pos1 (funcall aux -1))
4994 (goto-char (car pos1))
4995 (setq pos2 (funcall aux arg))
4996 (transpose-subr-1 pos1 pos2)))))
4997
4998(defun transpose-subr-1 (pos1 pos2)
4999 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
5000 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
5001 (when (> (car pos1) (car pos2))
5002 (let ((swap pos1))
5003 (setq pos1 pos2 pos2 swap)))
5004 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
dc7d7552
RS
5005 (atomic-change-group
5006 (let (word2)
1e96c007
SM
5007 ;; FIXME: We first delete the two pieces of text, so markers that
5008 ;; used to point to after the text end up pointing to before it :-(
dc7d7552
RS
5009 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
5010 (goto-char (car pos2))
5011 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
5012 (goto-char (car pos1))
5013 (insert word2))))
2d88b556 5014\f
6b61353c 5015(defun backward-word (&optional arg)
b7e91b0c 5016 "Move backward until encountering the beginning of a word.
5626c14e 5017With argument ARG, do this that many times."
109cfe4e 5018 (interactive "^p")
6b61353c 5019 (forward-word (- (or arg 1))))
2076c87c 5020
a1a801de 5021(defun mark-word (&optional arg allow-extend)
705a5933
JL
5022 "Set mark ARG words away from point.
5023The place mark goes is the same place \\[forward-word] would
5024move to with the same argument.
a1a801de 5025Interactively, if this command is repeated
771069f8 5026or (in Transient Mark mode) if the mark is active,
705a5933 5027it marks the next ARG words after the ones already marked."
a1a801de
RS
5028 (interactive "P\np")
5029 (cond ((and allow-extend
5030 (or (and (eq last-command this-command) (mark t))
d34c311a 5031 (region-active-p)))
705a5933
JL
5032 (setq arg (if arg (prefix-numeric-value arg)
5033 (if (< (mark) (point)) -1 1)))
cad113ae
KG
5034 (set-mark
5035 (save-excursion
5036 (goto-char (mark))
5037 (forward-word arg)
5038 (point))))
5039 (t
5040 (push-mark
5041 (save-excursion
705a5933 5042 (forward-word (prefix-numeric-value arg))
cad113ae
KG
5043 (point))
5044 nil t))))
2076c87c
JB
5045
5046(defun kill-word (arg)
5047 "Kill characters forward until encountering the end of a word.
5626c14e 5048With argument ARG, do this that many times."
e761e42c 5049 (interactive "p")
89ee2bf6 5050 (kill-region (point) (progn (forward-word arg) (point))))
2076c87c
JB
5051
5052(defun backward-kill-word (arg)
654ec269 5053 "Kill characters backward until encountering the beginning of a word.
5626c14e 5054With argument ARG, do this that many times."
e761e42c 5055 (interactive "p")
2076c87c 5056 (kill-word (- arg)))
d7c64071 5057
0f7df535
RS
5058(defun current-word (&optional strict really-word)
5059 "Return the symbol or word that point is on (or a nearby one) as a string.
5060The return value includes no text properties.
1e8c5ac4 5061If optional arg STRICT is non-nil, return nil unless point is within
0fa19a57
RS
5062or adjacent to a symbol or word. In all cases the value can be nil
5063if there is no word nearby.
0f7df535
RS
5064The function, belying its name, normally finds a symbol.
5065If optional arg REALLY-WORD is non-nil, it finds just a word."
d7c64071 5066 (save-excursion
0f7df535 5067 (let* ((oldpoint (point)) (start (point)) (end (point))
81d17173 5068 (syntaxes (if really-word "w" "w_"))
0f7df535
RS
5069 (not-syntaxes (concat "^" syntaxes)))
5070 (skip-syntax-backward syntaxes) (setq start (point))
d7c64071 5071 (goto-char oldpoint)
0f7df535
RS
5072 (skip-syntax-forward syntaxes) (setq end (point))
5073 (when (and (eq start oldpoint) (eq end oldpoint)
5074 ;; Point is neither within nor adjacent to a word.
5075 (not strict))
5076 ;; Look for preceding word in same line.
9b026d9f 5077 (skip-syntax-backward not-syntaxes (line-beginning-position))
0f7df535
RS
5078 (if (bolp)
5079 ;; No preceding word in same line.
5080 ;; Look for following word in same line.
5081 (progn
9b026d9f 5082 (skip-syntax-forward not-syntaxes (line-end-position))
0f7df535
RS
5083 (setq start (point))
5084 (skip-syntax-forward syntaxes)
5085 (setq end (point)))
5086 (setq end (point))
5087 (skip-syntax-backward syntaxes)
5088 (setq start (point))))
5089 ;; If we found something nonempty, return it as a string.
5090 (unless (= start end)
020db25f 5091 (buffer-substring-no-properties start end)))))
2d88b556 5092\f
69c1dd37 5093(defcustom fill-prefix nil
1d2b0303 5094 "String for filling to insert at front of new line, or nil for none."
69c1dd37
RS
5095 :type '(choice (const :tag "None" nil)
5096 string)
5097 :group 'fill)
2076c87c 5098(make-variable-buffer-local 'fill-prefix)
f31b1257 5099(put 'fill-prefix 'safe-local-variable 'string-or-null-p)
2076c87c 5100
69c1dd37 5101(defcustom auto-fill-inhibit-regexp nil
1d2b0303 5102 "Regexp to match lines which should not be auto-filled."
69c1dd37
RS
5103 :type '(choice (const :tag "None" nil)
5104 regexp)
5105 :group 'fill)
2076c87c
JB
5106
5107(defun do-auto-fill ()
ce558208
GM
5108 "The default value for `normal-auto-fill-function'.
5109This is the default auto-fill function, some major modes use a different one.
5110Returns t if it really did any work."
621a3f62 5111 (let (fc justify give-up
a0170800 5112 (fill-prefix fill-prefix))
c18465c4 5113 (if (or (not (setq justify (current-justification)))
8f066a20
RS
5114 (null (setq fc (current-fill-column)))
5115 (and (eq justify 'left)
5116 (<= (current-column) fc))
621a3f62
SM
5117 (and auto-fill-inhibit-regexp
5118 (save-excursion (beginning-of-line)
eed5698b
RS
5119 (looking-at auto-fill-inhibit-regexp))))
5120 nil ;; Auto-filling not required
3db1e3b5
BG
5121 (if (memq justify '(full center right))
5122 (save-excursion (unjustify-current-line)))
a0170800
RS
5123
5124 ;; Choose a fill-prefix automatically.
e1e04350
SM
5125 (when (and adaptive-fill-mode
5126 (or (null fill-prefix) (string= fill-prefix "")))
5127 (let ((prefix
5128 (fill-context-prefix
5129 (save-excursion (backward-paragraph 1) (point))
5130 (save-excursion (forward-paragraph 1) (point)))))
5131 (and prefix (not (equal prefix ""))
5132 ;; Use auto-indentation rather than a guessed empty prefix.
0e53a373 5133 (not (and fill-indent-according-to-mode
d99f8496 5134 (string-match "\\`[ \t]*\\'" prefix)))
e1e04350 5135 (setq fill-prefix prefix))))
f1180544 5136
eed5698b 5137 (while (and (not give-up) (> (current-column) fc))
e47d38f6 5138 ;; Determine where to split the line.
db893d00
RS
5139 (let* (after-prefix
5140 (fill-point
621a3f62
SM
5141 (save-excursion
5142 (beginning-of-line)
5143 (setq after-prefix (point))
5144 (and fill-prefix
5145 (looking-at (regexp-quote fill-prefix))
5146 (setq after-prefix (match-end 0)))
5147 (move-to-column (1+ fc))
5148 (fill-move-to-break-point after-prefix)
5149 (point))))
db893d00
RS
5150
5151 ;; See whether the place we found is any good.
e47d38f6
RS
5152 (if (save-excursion
5153 (goto-char fill-point)
41d22ee0
SM
5154 (or (bolp)
5155 ;; There is no use breaking at end of line.
5156 (save-excursion (skip-chars-forward " ") (eolp))
5157 ;; It is futile to split at the end of the prefix
5158 ;; since we would just insert the prefix again.
5159 (and after-prefix (<= (point) after-prefix))
5160 ;; Don't split right after a comment starter
5161 ;; since we would just make another comment starter.
5162 (and comment-start-skip
5163 (let ((limit (point)))
5164 (beginning-of-line)
5165 (and (re-search-forward comment-start-skip
5166 limit t)
5167 (eq (point) limit))))))
5168 ;; No good place to break => stop trying.
5169 (setq give-up t)
5170 ;; Ok, we have a useful place to break the line. Do it.
5171 (let ((prev-column (current-column)))
5172 ;; If point is at the fill-point, do not `save-excursion'.
5173 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
5174 ;; point will end up before it rather than after it.
5175 (if (save-excursion
5176 (skip-chars-backward " \t")
5177 (= (point) fill-point))
0b727f9d 5178 (default-indent-new-line t)
41d22ee0
SM
5179 (save-excursion
5180 (goto-char fill-point)
0b727f9d 5181 (default-indent-new-line t)))
41d22ee0
SM
5182 ;; Now do justification, if required
5183 (if (not (eq justify 'left))
e47d38f6 5184 (save-excursion
e1e04350
SM
5185 (end-of-line 0)
5186 (justify-current-line justify nil t)))
41d22ee0
SM
5187 ;; If making the new line didn't reduce the hpos of
5188 ;; the end of the line, then give up now;
5189 ;; trying again will not help.
5190 (if (>= (current-column) prev-column)
5191 (setq give-up t))))))
24ebf92e 5192 ;; Justify last line.
e2504204 5193 (justify-current-line justify t t)
1e722f9f 5194 t)))
2076c87c 5195
0b727f9d
RS
5196(defvar comment-line-break-function 'comment-indent-new-line
5197 "*Mode-specific function which line breaks and continues a comment.
5198This function is called during auto-filling when a comment syntax
5199is defined.
5200The function should take a single optional argument, which is a flag
5201indicating whether it should use soft newlines.")
5202
5203(defun default-indent-new-line (&optional soft)
5204 "Break line at point and indent.
5205If a comment syntax is defined, call `comment-indent-new-line'.
5206
5207The inserted newline is marked hard if variable `use-hard-newlines' is true,
5208unless optional argument SOFT is non-nil."
5209 (interactive)
5210 (if comment-start
5211 (funcall comment-line-break-function soft)
5212 ;; Insert the newline before removing empty space so that markers
5213 ;; get preserved better.
5214 (if soft (insert-and-inherit ?\n) (newline 1))
5215 (save-excursion (forward-char -1) (delete-horizontal-space))
5216 (delete-horizontal-space)
5217
5218 (if (and fill-prefix (not adaptive-fill-mode))
5219 ;; Blindly trust a non-adaptive fill-prefix.
5220 (progn
5221 (indent-to-left-margin)
5222 (insert-before-markers-and-inherit fill-prefix))
5223
5224 (cond
5225 ;; If there's an adaptive prefix, use it unless we're inside
5226 ;; a comment and the prefix is not a comment starter.
5227 (fill-prefix
5228 (indent-to-left-margin)
5229 (insert-and-inherit fill-prefix))
5230 ;; If we're not inside a comment, just try to indent.
5231 (t (indent-according-to-mode))))))
5232
24ebf92e
RS
5233(defvar normal-auto-fill-function 'do-auto-fill
5234 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
5235Some major modes set this.")
5236
c75505b4 5237(put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
74ab01ff
SM
5238;; `functions' and `hooks' are usually unsafe to set, but setting
5239;; auto-fill-function to nil in a file-local setting is safe and
5240;; can be useful to prevent auto-filling.
5241(put 'auto-fill-function 'safe-local-variable 'null)
d99f8496
SM
5242;; FIXME: turn into a proper minor mode.
5243;; Add a global minor mode version of it.
80ac5d4d 5244(define-minor-mode auto-fill-mode
24ebf92e 5245 "Toggle Auto Fill mode.
1d2b0303 5246With ARG, turn Auto Fill mode on if and only if ARG is positive.
24ebf92e
RS
5247In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
5248automatically breaks the line at a previous space.
5249
5250The value of `normal-auto-fill-function' specifies the function to use
5251for `auto-fill-function' when turning Auto Fill mode on."
80ac5d4d 5252 :variable (eq auto-fill-function normal-auto-fill-function))
d7465b15
RS
5253
5254;; This holds a document string used to document auto-fill-mode.
5255(defun auto-fill-function ()
5256 "Automatically break line at a previous space, in insertion of text."
5257 nil)
5258
5259(defun turn-on-auto-fill ()
5260 "Unconditionally turn on Auto Fill mode."
5261 (auto-fill-mode 1))
3a99c819
GM
5262
5263(defun turn-off-auto-fill ()
5264 "Unconditionally turn off Auto Fill mode."
5265 (auto-fill-mode -1))
5266
7cbf1dc1 5267(custom-add-option 'text-mode-hook 'turn-on-auto-fill)
d7465b15
RS
5268
5269(defun set-fill-column (arg)
4cc0ea11 5270 "Set `fill-column' to specified argument.
923efb99 5271Use \\[universal-argument] followed by a number to specify a column.
4cc0ea11 5272Just \\[universal-argument] as argument means to use the current column."
7c373357
SM
5273 (interactive
5274 (list (or current-prefix-arg
5275 ;; We used to use current-column silently, but C-x f is too easily
5276 ;; typed as a typo for C-x C-f, so we turned it into an error and
5277 ;; now an interactive prompt.
5278 (read-number "Set fill-column to: " (current-column)))))
f4520363
RS
5279 (if (consp arg)
5280 (setq arg (current-column)))
5281 (if (not (integerp arg))
5282 ;; Disallow missing argument; it's probably a typo for C-x C-f.
f33321ad 5283 (error "set-fill-column requires an explicit argument")
f4520363
RS
5284 (message "Fill column set to %d (was %d)" arg fill-column)
5285 (setq fill-column arg)))
2d88b556 5286\f
2076c87c 5287(defun set-selective-display (arg)
ff1fbe3e
RS
5288 "Set `selective-display' to ARG; clear it if no arg.
5289When the value of `selective-display' is a number > 0,
5290lines whose indentation is >= that value are not displayed.
5291The variable `selective-display' has a separate value for each buffer."
2076c87c
JB
5292 (interactive "P")
5293 (if (eq selective-display t)
5294 (error "selective-display already in use for marked lines"))
c88ab9ce
ER
5295 (let ((current-vpos
5296 (save-restriction
5297 (narrow-to-region (point-min) (point))
5298 (goto-char (window-start))
5299 (vertical-motion (window-height)))))
5300 (setq selective-display
5301 (and arg (prefix-numeric-value arg)))
5302 (recenter current-vpos))
2076c87c
JB
5303 (set-window-start (selected-window) (window-start (selected-window)))
5304 (princ "selective-display set to " t)
5305 (prin1 selective-display t)
5306 (princ "." t))
5307
40a64816 5308(defvaralias 'indicate-unused-lines 'indicate-empty-lines)
40a64816 5309
b3228584 5310(defun toggle-truncate-lines (&optional arg)
215f50ce 5311 "Toggle whether to fold or truncate long lines for the current buffer.
4837b516 5312With prefix argument ARG, truncate long lines if ARG is positive,
1d2b0303
JB
5313otherwise don't truncate them. Note that in side-by-side windows,
5314this command has no effect if `truncate-partial-width-windows'
627bb5dc 5315is non-nil."
0bb64d76
PA
5316 (interactive "P")
5317 (setq truncate-lines
5318 (if (null arg)
5319 (not truncate-lines)
46cdfe8f
RS
5320 (> (prefix-numeric-value arg) 0)))
5321 (force-mode-line-update)
4f017185
RS
5322 (unless truncate-lines
5323 (let ((buffer (current-buffer)))
5324 (walk-windows (lambda (window)
5325 (if (eq buffer (window-buffer window))
5326 (set-window-hscroll window 0)))
5327 nil t)))
46cdfe8f
RS
5328 (message "Truncate long lines %s"
5329 (if truncate-lines "enabled" "disabled")))
0bb64d76 5330
c899b3db
JL
5331(defun toggle-word-wrap (&optional arg)
5332 "Toggle whether to use word-wrapping for continuation lines.
5333With prefix argument ARG, wrap continuation lines at word boundaries
5334if ARG is positive, otherwise wrap them at the right screen edge.
5335This command toggles the value of `word-wrap'. It has no effect
5336if long lines are truncated."
5337 (interactive "P")
5338 (setq word-wrap
5339 (if (null arg)
5340 (not word-wrap)
5341 (> (prefix-numeric-value arg) 0)))
5342 (force-mode-line-update)
5343 (message "Word wrapping %s"
5344 (if word-wrap "enabled" "disabled")))
5345
ca0a881a 5346(defvar overwrite-mode-textual (purecopy " Ovwrt")
b6a22db0 5347 "The string displayed in the mode line when in overwrite mode.")
ca0a881a 5348(defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
b6a22db0
JB
5349 "The string displayed in the mode line when in binary overwrite mode.")
5350
80ac5d4d 5351(define-minor-mode overwrite-mode
2076c87c 5352 "Toggle overwrite mode.
4837b516
GM
5353With prefix argument ARG, turn overwrite mode on if ARG is positive,
5354otherwise turn it off. In overwrite mode, printing characters typed
5355in replace existing text on a one-for-one basis, rather than pushing
5356it to the right. At the end of a line, such characters extend the line.
5357Before a tab, such characters insert until the tab is filled in.
b6a22db0
JB
5358\\[quoted-insert] still inserts characters in overwrite mode; this
5359is supposed to make it easier to insert characters when necessary."
80ac5d4d 5360 :variable (eq overwrite-mode 'overwrite-mode-textual))
b6a22db0 5361
80ac5d4d 5362(define-minor-mode binary-overwrite-mode
b6a22db0 5363 "Toggle binary overwrite mode.
4837b516
GM
5364With prefix argument ARG, turn binary overwrite mode on if ARG is
5365positive, otherwise turn it off. In binary overwrite mode, printing
5366characters typed in replace existing text. Newlines are not treated
5367specially, so typing at the end of a line joins the line to the next,
5368with the typed character between them. Typing before a tab character
5369simply replaces the tab with the character typed. \\[quoted-insert]
5370replaces the text at the cursor, just as ordinary typing characters do.
b6a22db0
JB
5371
5372Note that binary overwrite mode is not its own minor mode; it is a
f33321ad 5373specialization of overwrite mode, entered by setting the
b6a22db0 5374`overwrite-mode' variable to `overwrite-mode-binary'."
80ac5d4d 5375 :variable (eq overwrite-mode 'overwrite-mode-binary))
eaae8106 5376
6710df48 5377(define-minor-mode line-number-mode
a61099dd 5378 "Toggle Line Number mode.
1d2b0303 5379With ARG, turn Line Number mode on if ARG is positive, otherwise
4837b516
GM
5380turn it off. When Line Number mode is enabled, the line number
5381appears in the mode line.
8dc9e2ef 5382
32f2f98e
EZ
5383Line numbers do not appear for very large buffers and buffers
5384with very long lines; see variables `line-number-display-limit'
5385and `line-number-display-limit-width'."
efeb22bf 5386 :init-value t :global t :group 'mode-line)
bcad4985 5387
6710df48 5388(define-minor-mode column-number-mode
bcad4985 5389 "Toggle Column Number mode.
1d2b0303 5390With ARG, turn Column Number mode on if ARG is positive,
4837b516
GM
5391otherwise turn it off. When Column Number mode is enabled, the
5392column number appears in the mode line."
efeb22bf 5393 :global t :group 'mode-line)
6b61353c
KH
5394
5395(define-minor-mode size-indication-mode
5396 "Toggle Size Indication mode.
1d2b0303 5397With ARG, turn Size Indication mode on if ARG is positive,
4837b516
GM
5398otherwise turn it off. When Size Indication mode is enabled, the
5399size of the accessible part of the buffer appears in the mode line."
efeb22bf 5400 :global t :group 'mode-line)
f3ee9200
SM
5401
5402(define-minor-mode auto-save-mode
5403 "Toggle auto-saving of contents of current buffer.
5404With prefix argument ARG, turn auto-saving on if positive, else off."
5405 :variable ((and buffer-auto-save-file-name
5406 ;; If auto-save is off because buffer has shrunk,
5407 ;; then toggling should turn it on.
5408 (>= buffer-saved-size 0))
5409 . (lambda (val)
5410 (setq buffer-auto-save-file-name
5411 (cond
5412 ((null val) nil)
5413 ((and buffer-file-name auto-save-visited-file-name
5414 (not buffer-read-only))
5415 buffer-file-name)
5416 (t (make-auto-save-file-name))))))
5417 ;; If -1 was stored here, to temporarily turn off saving,
5418 ;; turn it back on.
5419 (and (< buffer-saved-size 0)
5420 (setq buffer-saved-size 0)))
2d88b556 5421\f
4b384a8f 5422(defgroup paren-blinking nil
020db25f 5423 "Blinking matching of parens and expressions."
4b384a8f
SM
5424 :prefix "blink-matching-"
5425 :group 'paren-matching)
5426
69c1dd37 5427(defcustom blink-matching-paren t
1d2b0303 5428 "Non-nil means show matching open-paren when close-paren is inserted."
69c1dd37 5429 :type 'boolean
4b384a8f 5430 :group 'paren-blinking)
2076c87c 5431
69c1dd37 5432(defcustom blink-matching-paren-on-screen t
1d2b0303 5433 "Non-nil means show matching open-paren when it is on screen.
1c2ba4e7 5434If nil, don't show it (but the open-paren can still be shown
92aa8a33
LT
5435when it is off screen).
5436
9cb370a9 5437This variable has no effect if `blink-matching-paren' is nil.
a9f72e5f 5438\(In that case, the open-paren is never shown.)
9cb370a9 5439It is also ignored if `show-paren-mode' is enabled."
69c1dd37 5440 :type 'boolean
4b384a8f 5441 :group 'paren-blinking)
29fc44dd 5442
fd413a37 5443(defcustom blink-matching-paren-distance (* 100 1024)
1d2b0303 5444 "If non-nil, maximum distance to search backwards for matching open-paren.
66d44a36 5445If nil, search stops at the beginning of the accessible portion of the buffer."
fd413a37 5446 :version "23.2" ; 25->100k
66d44a36 5447 :type '(choice (const nil) integer)
4b384a8f 5448 :group 'paren-blinking)
2076c87c 5449
69c1dd37 5450(defcustom blink-matching-delay 1
1d2b0303 5451 "Time in seconds to delay after showing a matching paren."
4b384a8f
SM
5452 :type 'number
5453 :group 'paren-blinking)
72dddf8b 5454
69c1dd37 5455(defcustom blink-matching-paren-dont-ignore-comments nil
1d2b0303 5456 "If nil, `blink-matching-paren' ignores comments.
ab6b3b16
RS
5457More precisely, when looking for the matching parenthesis,
5458it skips the contents of comments that end before point."
69c1dd37 5459 :type 'boolean
4b384a8f 5460 :group 'paren-blinking)
903b7f65 5461
b13ebb5c
SM
5462(defun blink-matching-check-mismatch (start end)
5463 "Return whether or not START...END are matching parens.
5464END is the current point and START is the blink position.
5465START might be nil if no matching starter was found.
5466Returns non-nil if we find there is a mismatch."
5467 (let* ((end-syntax (syntax-after (1- end)))
5468 (matching-paren (and (consp end-syntax)
5469 (eq (syntax-class end-syntax) 5)
5470 (cdr end-syntax))))
5471 ;; For self-matched chars like " and $, we can't know when they're
5472 ;; mismatched or unmatched, so we can only do it for parens.
5473 (when matching-paren
5474 (not (and start
5475 (or
5476 (eq (char-after start) matching-paren)
5477 ;; The cdr might hold a new paren-class info rather than
5478 ;; a matching-char info, in which case the two CDRs
5479 ;; should match.
5480 (eq matching-paren (cdr-safe (syntax-after start)))))))))
5481
5482(defvar blink-matching-check-function #'blink-matching-check-mismatch
5483 "Function to check parentheses mismatches.
5484The function takes two arguments (START and END) where START is the
5485position just before the opening token and END is the position right after.
5486START can be nil, if it was not found.
5487The function should return non-nil if the two tokens do not match.")
5488
2076c87c
JB
5489(defun blink-matching-open ()
5490 "Move cursor momentarily to the beginning of the sexp before point."
5491 (interactive)
b13ebb5c
SM
5492 (when (and (not (bobp))
5493 blink-matching-paren)
1d0e3fc8 5494 (let* ((oldpos (point))
b13ebb5c 5495 (message-log-max nil) ; Don't log messages about paren matching.
3137dda8
SM
5496 (blinkpos
5497 (save-excursion
5498 (save-restriction
5499 (if blink-matching-paren-distance
5500 (narrow-to-region
5501 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
5502 (- (point) blink-matching-paren-distance))
5503 oldpos))
5504 (let ((parse-sexp-ignore-comments
5505 (and parse-sexp-ignore-comments
5506 (not blink-matching-paren-dont-ignore-comments))))
5507 (condition-case ()
4b9c0a49
SM
5508 (progn
5509 (forward-sexp -1)
b13ebb5c
SM
5510 ;; backward-sexp skips backward over prefix chars,
5511 ;; so move back to the matching paren.
5512 (while (and (< (point) (1- oldpos))
984edd22
SM
5513 (let ((code (syntax-after (point))))
5514 (or (eq (syntax-class code) 6)
5515 (eq (logand 1048576 (car code))
5516 1048576))))
b13ebb5c 5517 (forward-char 1))
4b9c0a49 5518 (point))
3137dda8 5519 (error nil))))))
b13ebb5c 5520 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
3137dda8 5521 (cond
b13ebb5c
SM
5522 (mismatch
5523 (if blinkpos
28e271f0 5524 (if (minibufferp)
b13ebb5c
SM
5525 (minibuffer-message " [Mismatched parentheses]")
5526 (message "Mismatched parentheses"))
5527 (if (minibufferp)
5528 (minibuffer-message " [Unmatched parenthesis]")
5529 (message "Unmatched parenthesis"))))
c34a9669 5530 ((not blinkpos) nil)
3137dda8
SM
5531 ((pos-visible-in-window-p blinkpos)
5532 ;; Matching open within window, temporarily move to blinkpos but only
5533 ;; if `blink-matching-paren-on-screen' is non-nil.
5534 (and blink-matching-paren-on-screen
5535 (not show-paren-mode)
5536 (save-excursion
5537 (goto-char blinkpos)
5538 (sit-for blink-matching-delay))))
5539 (t
5540 (save-excursion
5541 (goto-char blinkpos)
5542 (let ((open-paren-line-string
5543 ;; Show what precedes the open in its line, if anything.
5544 (cond
5545 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
5546 (buffer-substring (line-beginning-position)
5547 (1+ blinkpos)))
5548 ;; Show what follows the open in its line, if anything.
5549 ((save-excursion
5550 (forward-char 1)
5551 (skip-chars-forward " \t")
5552 (not (eolp)))
5553 (buffer-substring blinkpos
5554 (line-end-position)))
5555 ;; Otherwise show the previous nonblank line,
5556 ;; if there is one.
5557 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
5558 (concat
5559 (buffer-substring (progn
5560 (skip-chars-backward "\n \t")
5561 (line-beginning-position))
5562 (progn (end-of-line)
5563 (skip-chars-backward " \t")
5564 (point)))
5565 ;; Replace the newline and other whitespace with `...'.
5566 "..."
5567 (buffer-substring blinkpos (1+ blinkpos))))
5568 ;; There is nothing to show except the char itself.
5569 (t (buffer-substring blinkpos (1+ blinkpos))))))
5570 (message "Matches %s"
5571 (substring-no-properties open-paren-line-string)))))))))
5572
8f4e9110
SM
5573(defvar blink-paren-function 'blink-matching-open
5574 "Function called, if non-nil, whenever a close parenthesis is inserted.
5575More precisely, a char with closeparen syntax is self-inserted.")
5576
5577(defun blink-paren-post-self-insert-function ()
5578 (when (and (eq (char-before) last-command-event) ; Sanity check.
5579 (memq (char-syntax last-command-event) '(?\) ?\$))
5580 blink-paren-function
5581 (not executing-kbd-macro)
b13ebb5c
SM
5582 (not noninteractive)
5583 ;; Verify an even number of quoting characters precede the close.
5584 (= 1 (logand 1 (- (point)
5585 (save-excursion
5586 (forward-char -1)
5587 (skip-syntax-backward "/\\")
5588 (point))))))
8f4e9110
SM
5589 (funcall blink-paren-function)))
5590
5591(add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
5592 ;; Most likely, this hook is nil, so this arg doesn't matter,
5593 ;; but I use it as a reminder that this function usually
5594 ;; likes to be run after others since it does `sit-for'.
5595 'append)
2d88b556 5596\f
9a1277dd
RS
5597;; This executes C-g typed while Emacs is waiting for a command.
5598;; Quitting out of a program does not go through here;
5599;; that happens in the QUIT macro at the C code level.
2076c87c 5600(defun keyboard-quit ()
d5dae4e1 5601 "Signal a `quit' condition.
af39530e
RS
5602During execution of Lisp code, this character causes a quit directly.
5603At top-level, as an editor command, this simply beeps."
2076c87c 5604 (interactive)
9852377f
CY
5605 ;; Avoid adding the region to the window selection.
5606 (setq saved-region-selection nil)
5607 (let (select-active-regions)
5608 (deactivate-mark))
8a7644e9
KS
5609 (if (fboundp 'kmacro-keyboard-quit)
5610 (kmacro-keyboard-quit))
f5e13057 5611 (setq defining-kbd-macro nil)
2076c87c
JB
5612 (signal 'quit nil))
5613
1c6c6fde
RS
5614(defvar buffer-quit-function nil
5615 "Function to call to \"quit\" the current buffer, or nil if none.
5616\\[keyboard-escape-quit] calls this function when its more local actions
5617\(such as cancelling a prefix argument, minibuffer or region) do not apply.")
5618
c66587fe
RS
5619(defun keyboard-escape-quit ()
5620 "Exit the current \"mode\" (in a generalized sense of the word).
5621This command can exit an interactive command such as `query-replace',
5622can clear out a prefix argument or a region,
5623can get out of the minibuffer or other recursive edit,
1c6c6fde
RS
5624cancel the use of the current buffer (for special-purpose buffers),
5625or go back to just one window (by deleting all but the selected window)."
c66587fe
RS
5626 (interactive)
5627 (cond ((eq last-command 'mode-exited) nil)
67189e62
JL
5628 ((region-active-p)
5629 (deactivate-mark))
c66587fe
RS
5630 ((> (minibuffer-depth) 0)
5631 (abort-recursive-edit))
5632 (current-prefix-arg
5633 nil)
1b657835
RS
5634 ((> (recursion-depth) 0)
5635 (exit-recursive-edit))
1c6c6fde
RS
5636 (buffer-quit-function
5637 (funcall buffer-quit-function))
c66587fe 5638 ((not (one-window-p t))
1b657835
RS
5639 (delete-other-windows))
5640 ((string-match "^ \\*" (buffer-name (current-buffer)))
5641 (bury-buffer))))
c66587fe 5642
2d88b556
RS
5643(defun play-sound-file (file &optional volume device)
5644 "Play sound stored in FILE.
5645VOLUME and DEVICE correspond to the keywords of the sound
5646specification for `play-sound'."
5647 (interactive "fPlay sound file: ")
5648 (let ((sound (list :file file)))
5649 (if volume
5650 (plist-put sound :volume volume))
5651 (if device
5652 (plist-put sound :device device))
5653 (push 'sound sound)
5654 (play-sound sound)))
5655
56abefac 5656\f
7683b5c2 5657(defcustom read-mail-command 'rmail
1d2b0303 5658 "Your preference for a mail reading package.
9023837e
DL
5659This is used by some keybindings which support reading mail.
5660See also `mail-user-agent' concerning sending mail."
f6714ede
GM
5661 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
5662 (function-item :tag "Gnus" :format "%t\n" gnus)
5663 (function-item :tag "Emacs interface to MH"
5664 :format "%t\n" mh-rmail)
5665 (function :tag "Other"))
7683b5c2
DL
5666 :version "21.1"
5667 :group 'mail)
5668
cbd61418 5669(defcustom mail-user-agent 'message-user-agent
1d2b0303 5670 "Your preference for a mail composition package.
9023837e 5671Various Emacs Lisp packages (e.g. Reporter) require you to compose an
a31ca314
RS
5672outgoing email message. This variable lets you specify which
5673mail-sending package you prefer.
5674
5675Valid values include:
5676
cfc47664
GM
5677 `message-user-agent' -- use the Message package.
5678 See Info node `(message)'.
5679 `sendmail-user-agent' -- use the Mail package.
9023837e
DL
5680 See Info node `(emacs)Sending Mail'.
5681 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
5682 See Info node `(mh-e)'.
9023837e
DL
5683 `gnus-user-agent' -- like `message-user-agent', but with Gnus
5684 paraphernalia, particularly the Gcc: header for
5685 archiving.
a31ca314
RS
5686
5687Additional valid symbols may be available; check with the author of
15d0c9b1
DL
5688your package for details. The function should return non-nil if it
5689succeeds.
9023837e
DL
5690
5691See also `read-mail-command' concerning reading mail."
cfc47664
GM
5692 :type '(radio (function-item :tag "Message package"
5693 :format "%t\n"
5694 message-user-agent)
5695 (function-item :tag "Mail package"
69c1dd37
RS
5696 :format "%t\n"
5697 sendmail-user-agent)
5698 (function-item :tag "Emacs interface to MH"
5699 :format "%t\n"
5700 mh-e-user-agent)
cfc47664 5701 (function-item :tag "Message with full Gnus features"
9023837e
DL
5702 :format "%t\n"
5703 gnus-user-agent)
69c1dd37 5704 (function :tag "Other"))
cfc47664 5705 :version "23.2" ; sendmail->message
69c1dd37 5706 :group 'mail)
a31ca314 5707
3d68fa99
CY
5708(defcustom compose-mail-user-agent-warnings t
5709 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
5710If the value of `mail-user-agent' is the default, and the user
5711appears to have customizations applying to the old default,
5712`compose-mail' issues a warning."
5713 :type 'boolean
5714 :version "23.2"
5715 :group 'mail)
5716
360b5483
RS
5717(defun rfc822-goto-eoh ()
5718 ;; Go to header delimiter line in a mail message, following RFC822 rules
5719 (goto-char (point-min))
e1e04350
SM
5720 (when (re-search-forward
5721 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
5722 (goto-char (match-beginning 0))))
360b5483 5723
d0008a00 5724(defun compose-mail (&optional to subject other-headers continue
25ca2e61
CY
5725 switch-function yank-action send-actions
5726 return-action)
d0008a00
RS
5727 "Start composing a mail message to send.
5728This uses the user's chosen mail composition package
5729as selected with the variable `mail-user-agent'.
5730The optional arguments TO and SUBJECT specify recipients
5731and the initial Subject field, respectively.
5732
5733OTHER-HEADERS is an alist specifying additional
5734header fields. Elements look like (HEADER . VALUE) where both
5735HEADER and VALUE are strings.
5736
5737CONTINUE, if non-nil, says to continue editing a message already
9dda5b0e 5738being composed. Interactively, CONTINUE is the prefix argument.
d0008a00
RS
5739
5740SWITCH-FUNCTION, if non-nil, is a function to use to
5741switch to and display the buffer used for mail composition.
5742
5743YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
06720de2
RS
5744to insert the raw text of the message being replied to.
5745It has the form (FUNCTION . ARGS). The user agent will apply
5746FUNCTION to ARGS, to insert the raw text of the original message.
5747\(The user agent will also run `mail-citation-hook', *after* the
5748original text has been inserted in this way.)
d0008a00
RS
5749
5750SEND-ACTIONS is a list of actions to call when the message is sent.
25ca2e61
CY
5751Each action has the form (FUNCTION . ARGS).
5752
5753RETURN-ACTION, if non-nil, is an action for returning to the
5754caller. It has the form (FUNCTION . ARGS). The function is
5755called after the mail has been sent or put aside, and the mail
5756buffer buried."
b5f019be
RS
5757 (interactive
5758 (list nil nil nil current-prefix-arg))
3d68fa99
CY
5759
5760 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
5761 ;; from sendmail-user-agent to message-user-agent. Some users may
5762 ;; encounter incompatibilities. This hack tries to detect problems
5763 ;; and warn about them.
5764 (and compose-mail-user-agent-warnings
5765 (eq mail-user-agent 'message-user-agent)
5766 (let (warn-vars)
5767 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
5768 mail-yank-hooks mail-archive-file-name
5769 mail-default-reply-to mail-mailing-lists
5e1d4968 5770 mail-self-blind))
3d68fa99
CY
5771 (and (boundp var)
5772 (symbol-value var)
5773 (push var warn-vars)))
5774 (when warn-vars
5775 (display-warning 'mail
5776 (format "\
5777The default mail mode is now Message mode.
5778You have the following Mail mode variable%s customized:
5779\n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
7f0b7b3e 5780To disable this warning, set `compose-mail-user-agent-warnings' to nil."
3d68fa99
CY
5781 (if (> (length warn-vars) 1) "s" "")
5782 (mapconcat 'symbol-name
5783 warn-vars " "))))))
5784
676b1a74 5785 (let ((function (get mail-user-agent 'composefunc)))
25ca2e61
CY
5786 (funcall function to subject other-headers continue switch-function
5787 yank-action send-actions return-action)))
b5f019be
RS
5788
5789(defun compose-mail-other-window (&optional to subject other-headers continue
25ca2e61
CY
5790 yank-action send-actions
5791 return-action)
b5f019be 5792 "Like \\[compose-mail], but edit the outgoing message in another window."
25ca2e61 5793 (interactive (list nil nil nil current-prefix-arg))
b5f019be 5794 (compose-mail to subject other-headers continue
25ca2e61
CY
5795 'switch-to-buffer-other-window yank-action send-actions
5796 return-action))
b5f019be
RS
5797
5798(defun compose-mail-other-frame (&optional to subject other-headers continue
25ca2e61
CY
5799 yank-action send-actions
5800 return-action)
b5f019be 5801 "Like \\[compose-mail], but edit the outgoing message in another frame."
25ca2e61 5802 (interactive (list nil nil nil current-prefix-arg))
b5f019be 5803 (compose-mail to subject other-headers continue
25ca2e61
CY
5804 'switch-to-buffer-other-frame yank-action send-actions
5805 return-action))
5806
56abefac 5807\f
610c1c68 5808(defvar set-variable-value-history nil
987ec16d
EZ
5809 "History of values entered with `set-variable'.
5810
5811Maximum length of the history list is determined by the value
5812of `history-length', which see.")
610c1c68 5813
d6281b4e 5814(defun set-variable (variable value &optional make-local)
610c1c68 5815 "Set VARIABLE to VALUE. VALUE is a Lisp object.
d6281b4e
RS
5816VARIABLE should be a user option variable name, a Lisp variable
5817meant to be customized by users. You should enter VALUE in Lisp syntax,
5818so if you want VALUE to be a string, you must surround it with doublequotes.
610c1c68
RS
5819VALUE is used literally, not evaluated.
5820
5821If VARIABLE has a `variable-interactive' property, that is used as if
5822it were the arg to `interactive' (which see) to interactively read VALUE.
5823
5824If VARIABLE has been defined with `defcustom', then the type information
16236388
RS
5825in the definition is used to check that VALUE is valid.
5826
5827With a prefix argument, set VARIABLE to VALUE buffer-locally."
e9dfb72e
RS
5828 (interactive
5829 (let* ((default-var (variable-at-point))
7fd0ef0d
JL
5830 (var (if (user-variable-p default-var)
5831 (read-variable (format "Set variable (default %s): " default-var)
5832 default-var)
5833 (read-variable "Set variable: ")))
6b61353c
KH
5834 (minibuffer-help-form '(describe-variable var))
5835 (prop (get var 'variable-interactive))
0684376b
JB
5836 (obsolete (car (get var 'byte-obsolete-variable)))
5837 (prompt (format "Set %s %s to value: " var
6b61353c 5838 (cond ((local-variable-p var)
0684376b 5839 "(buffer-local)")
6b61353c
KH
5840 ((or current-prefix-arg
5841 (local-variable-if-set-p var))
0684376b
JB
5842 "buffer-locally")
5843 (t "globally"))))
5844 (val (progn
5845 (when obsolete
5846 (message (concat "`%S' is obsolete; "
5847 (if (symbolp obsolete) "use `%S' instead" "%s"))
5848 var obsolete)
5849 (sit-for 3))
5850 (if prop
5851 ;; Use VAR's `variable-interactive' property
5852 ;; as an interactive spec for prompting.
5853 (call-interactively `(lambda (arg)
5854 (interactive ,prop)
5855 arg))
5856 (read
5857 (read-string prompt nil
7fd0ef0d
JL
5858 'set-variable-value-history
5859 (format "%S" (symbol-value var))))))))
6b61353c 5860 (list var val current-prefix-arg)))
610c1c68 5861
d6281b4e
RS
5862 (and (custom-variable-p variable)
5863 (not (get variable 'custom-type))
5864 (custom-load-symbol variable))
5865 (let ((type (get variable 'custom-type)))
610c1c68
RS
5866 (when type
5867 ;; Match with custom type.
36755dd9 5868 (require 'cus-edit)
610c1c68 5869 (setq type (widget-convert type))
d6281b4e 5870 (unless (widget-apply type :match value)
1e722f9f 5871 (error "Value `%S' does not match type %S of %S"
d6281b4e 5872 value (car type) variable))))
16236388
RS
5873
5874 (if make-local
d6281b4e 5875 (make-local-variable variable))
f1180544 5876
d6281b4e 5877 (set variable value)
a2aef080
GM
5878
5879 ;; Force a thorough redisplay for the case that the variable
5880 ;; has an effect on the display, like `tab-width' has.
5881 (force-mode-line-update))
56abefac 5882\f
e8a700bf
RS
5883;; Define the major mode for lists of completions.
5884
e2947429
SM
5885(defvar completion-list-mode-map
5886 (let ((map (make-sparse-keymap)))
5887 (define-key map [mouse-2] 'mouse-choose-completion)
5888 (define-key map [follow-link] 'mouse-face)
5889 (define-key map [down-mouse-2] nil)
5890 (define-key map "\C-m" 'choose-completion)
5891 (define-key map "\e\e\e" 'delete-completion-window)
5892 (define-key map [left] 'previous-completion)
5893 (define-key map [right] 'next-completion)
45f8cb0c 5894 (define-key map "q" 'quit-window)
abef340a 5895 (define-key map "z" 'kill-this-buffer)
e2947429 5896 map)
98b45886 5897 "Local map for completion list buffers.")
e8a700bf
RS
5898
5899;; Completion mode is suitable only for specially formatted data.
ac29eb79 5900(put 'completion-list-mode 'mode-class 'special)
e8a700bf 5901
98b45886
RS
5902(defvar completion-reference-buffer nil
5903 "Record the buffer that was current when the completion list was requested.
5904This is a local variable in the completion list buffer.
ec39964e 5905Initial value is nil to avoid some compiler warnings.")
3819736b 5906
83434bda
RS
5907(defvar completion-no-auto-exit nil
5908 "Non-nil means `choose-completion-string' should never exit the minibuffer.
f6714ede 5909This also applies to other functions such as `choose-completion'.")
83434bda 5910
d5e63715
SM
5911(defvar completion-base-position nil
5912 "Position of the base of the text corresponding to the shown completions.
5913This variable is used in the *Completions* buffers.
5914Its value is a list of the form (START END) where START is the place
5915where the completion should be inserted and END (if non-nil) is the end
5916of the text to replace. If END is nil, point is used instead.")
5917
98b45886 5918(defvar completion-base-size nil
3c59150d
CY
5919 "Number of chars before point not involved in completion.
5920This is a local variable in the completion list buffer.
5921It refers to the chars in the minibuffer if completing in the
5922minibuffer, or in `completion-reference-buffer' otherwise.
5923Only characters in the field at point are included.
5924
5925If nil, Emacs determines which part of the tail end of the
5926buffer's text is involved in completion by comparing the text
5927directly.")
d5e63715 5928(make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
f6b293e3 5929
1c6c6fde
RS
5930(defun delete-completion-window ()
5931 "Delete the completion list window.
5932Go to the window from which completion was requested."
5933 (interactive)
5934 (let ((buf completion-reference-buffer))
ddb2b181
RS
5935 (if (one-window-p t)
5936 (if (window-dedicated-p (selected-window))
5937 (delete-frame (selected-frame)))
5938 (delete-window (selected-window))
5939 (if (get-buffer-window buf)
5940 (select-window (get-buffer-window buf))))))
1c6c6fde 5941
dde69dbe
RS
5942(defun previous-completion (n)
5943 "Move to the previous item in the completion list."
5944 (interactive "p")
5945 (next-completion (- n)))
5946
5947(defun next-completion (n)
5948 "Move to the next item in the completion list.
1f238ac2 5949With prefix argument N, move N items (negative N means move backward)."
dde69dbe 5950 (interactive "p")
58dd38f1
SM
5951 (let ((beg (point-min)) (end (point-max)))
5952 (while (and (> n 0) (not (eobp)))
dde69dbe 5953 ;; If in a completion, move to the end of it.
58dd38f1
SM
5954 (when (get-text-property (point) 'mouse-face)
5955 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
dde69dbe 5956 ;; Move to start of next one.
58dd38f1
SM
5957 (unless (get-text-property (point) 'mouse-face)
5958 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5959 (setq n (1- n)))
5960 (while (and (< n 0) (not (bobp)))
5961 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
5962 ;; If in a completion, move to the start of it.
5963 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
b61a81c2 5964 (goto-char (previous-single-property-change
58dd38f1
SM
5965 (point) 'mouse-face nil beg)))
5966 ;; Move to end of the previous completion.
5967 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
5968 (goto-char (previous-single-property-change
5969 (point) 'mouse-face nil beg)))
5970 ;; Move to the start of that one.
5971 (goto-char (previous-single-property-change
5972 (point) 'mouse-face nil beg))
5973 (setq n (1+ n))))))
dde69dbe 5974
d5e63715
SM
5975(defun choose-completion (&optional event)
5976 "Choose the completion at point."
5977 (interactive (list last-nonmenu-event))
5978 ;; In case this is run via the mouse, give temporary modes such as
5979 ;; isearch a chance to turn off.
5980 (run-hooks 'mouse-leave-buffer-hook)
5981 (let (buffer base-size base-position choice)
5982 (with-current-buffer (window-buffer (posn-window (event-start event)))
5983 (setq buffer completion-reference-buffer)
5984 (setq base-size completion-base-size)
5985 (setq base-position completion-base-position)
5986 (save-excursion
5987 (goto-char (posn-point (event-start event)))
5988 (let (beg end)
5989 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
5990 (setq end (point) beg (1+ (point))))
5991 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
5992 (setq end (1- (point)) beg (point)))
5993 (if (null beg)
5994 (error "No completion here"))
5995 (setq beg (previous-single-property-change beg 'mouse-face))
5996 (setq end (or (next-single-property-change end 'mouse-face)
5997 (point-max)))
5998 (setq choice (buffer-substring-no-properties beg end)))))
5999
ab63960f 6000 (let ((owindow (selected-window)))
d5e63715 6001 (select-window (posn-window (event-start event)))
ab63960f 6002 (if (and (one-window-p t 'selected-frame)
d5e63715 6003 (window-dedicated-p (selected-window)))
ab63960f
RS
6004 ;; This is a special buffer's frame
6005 (iconify-frame (selected-frame))
6006 (or (window-dedicated-p (selected-window))
6007 (bury-buffer)))
8a7daef5
CY
6008 (select-window
6009 (or (and (buffer-live-p buffer)
d5e63715 6010 (get-buffer-window buffer 0))
8a7daef5 6011 owindow)))
f6714ede 6012
d5e63715
SM
6013 (choose-completion-string
6014 choice buffer
6015 (or base-position
6016 (when base-size
6017 ;; Someone's using old completion code that doesn't know
6018 ;; about base-position yet.
6019 (list (+ base-size (with-current-buffer buffer (field-beginning)))))
6020 ;; If all else fails, just guess.
6021 (with-current-buffer buffer
6022 (list (choose-completion-guess-base-position choice)))))))
80298193
RS
6023
6024;; Delete the longest partial match for STRING
6025;; that can be found before POINT.
d5e63715
SM
6026(defun choose-completion-guess-base-position (string)
6027 (save-excursion
6028 (let ((opoint (point))
6029 len)
6030 ;; Try moving back by the length of the string.
6031 (goto-char (max (- (point) (length string))
6032 (minibuffer-prompt-end)))
6033 ;; See how far back we were actually able to move. That is the
6034 ;; upper bound on how much we can match and delete.
6035 (setq len (- opoint (point)))
6036 (if completion-ignore-case
6037 (setq string (downcase string)))
6038 (while (and (> len 0)
6039 (let ((tail (buffer-substring (point) opoint)))
6040 (if completion-ignore-case
6041 (setq tail (downcase tail)))
6042 (not (string= tail (substring string 0 len)))))
6043 (setq len (1- len))
6044 (forward-char 1))
6045 (point))))
6046
80298193 6047(defun choose-completion-delete-max-match (string)
d5e63715
SM
6048 (delete-region (choose-completion-guess-base-position string) (point)))
6049(make-obsolete 'choose-completion-delete-max-match
6050 'choose-completion-guess-base-position "23.2")
80298193 6051
ba36181b 6052(defvar choose-completion-string-functions nil
bbbbb15b
KS
6053 "Functions that may override the normal insertion of a completion choice.
6054These functions are called in order with four arguments:
6055CHOICE - the string to insert in the buffer,
6056BUFFER - the buffer in which the choice should be inserted,
4837b516 6057MINI-P - non-nil if BUFFER is a minibuffer, and
12829a07
RS
6058BASE-SIZE - the number of characters in BUFFER before
6059the string being completed.
6060
bbbbb15b
KS
6061If a function in the list returns non-nil, that function is supposed
6062to have inserted the CHOICE in the BUFFER, and possibly exited
12829a07 6063the minibuffer; no further functions will be called.
ba36181b 6064
12829a07
RS
6065If all functions in the list return nil, that means to use
6066the default method of inserting the completion in BUFFER.")
74d0290b 6067
d5e63715 6068(defun choose-completion-string (choice &optional buffer base-position)
12829a07 6069 "Switch to BUFFER and insert the completion choice CHOICE.
d5e63715 6070BASE-POSITION, says where to insert the completion."
12829a07
RS
6071
6072 ;; If BUFFER is the minibuffer, exit the minibuffer
6073 ;; unless it is reading a file name and CHOICE is a directory,
6074 ;; or completion-no-auto-exit is non-nil.
6075
d5e63715
SM
6076 ;; Some older code may call us passing `base-size' instead of
6077 ;; `base-position'. It's difficult to make any use of `base-size',
6078 ;; so we just ignore it.
6079 (unless (consp base-position)
6080 (message "Obsolete `base-size' passed to choose-completion-string")
6081 (setq base-position nil))
6082
1a0d0b6a
JPW
6083 (let* ((buffer (or buffer completion-reference-buffer))
6084 (mini-p (minibufferp buffer)))
cf52ad58
RS
6085 ;; If BUFFER is a minibuffer, barf unless it's the currently
6086 ;; active minibuffer.
f436a90a 6087 (if (and mini-p
45486731
RS
6088 (or (not (active-minibuffer-window))
6089 (not (equal buffer
6090 (window-buffer (active-minibuffer-window))))))
cf52ad58 6091 (error "Minibuffer is not active for completion")
17aa3385
KS
6092 ;; Set buffer so buffer-local choose-completion-string-functions works.
6093 (set-buffer buffer)
f1180544 6094 (unless (run-hook-with-args-until-success
d99f8496 6095 'choose-completion-string-functions
d5e63715
SM
6096 ;; The fourth arg used to be `mini-p' but was useless
6097 ;; (since minibufferp can be used on the `buffer' arg)
6098 ;; and indeed unused. The last used to be `base-size', so we
6099 ;; keep it to try and avoid breaking old code.
6100 choice buffer base-position nil)
d99f8496 6101 ;; Insert the completion into the buffer where it was requested.
d5e63715
SM
6102 (delete-region (or (car base-position) (point))
6103 (or (cadr base-position) (point)))
bbbbb15b
KS
6104 (insert choice)
6105 (remove-text-properties (- (point) (length choice)) (point)
6106 '(mouse-face nil))
6107 ;; Update point in the window that BUFFER is showing in.
6108 (let ((window (get-buffer-window buffer t)))
6109 (set-window-point window (point)))
6110 ;; If completing for the minibuffer, exit it with this choice.
6111 (and (not completion-no-auto-exit)
6138158d 6112 (minibufferp buffer)
bbbbb15b
KS
6113 minibuffer-completion-table
6114 ;; If this is reading a file name, and the file name chosen
6115 ;; is a directory, don't exit the minibuffer.
85be9ec4
SM
6116 (let* ((result (buffer-substring (field-beginning) (point)))
6117 (bounds
6118 (completion-boundaries result minibuffer-completion-table
6119 minibuffer-completion-predicate
6120 "")))
6121 (if (eq (car bounds) (length result))
6122 ;; The completion chosen leads to a new set of completions
6123 ;; (e.g. it's a directory): don't exit the minibuffer yet.
6124 (let ((mini (active-minibuffer-window)))
6125 (select-window mini)
6126 (when minibuffer-auto-raise
6127 (raise-frame (window-frame mini))))
6128 (exit-minibuffer))))))))
80298193 6129
e2947429 6130(define-derived-mode completion-list-mode nil "Completion List"
e8a700bf 6131 "Major mode for buffers showing lists of possible completions.
80298193
RS
6132Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
6133 to select the completion near point.
6134Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
3a77346c
GM
6135 with the mouse.
6136
6137\\{completion-list-mode-map}"
e2947429 6138 (set (make-local-variable 'completion-base-size) nil))
e8a700bf 6139
c8d6d636
GM
6140(defun completion-list-mode-finish ()
6141 "Finish setup of the completions buffer.
6142Called from `temp-buffer-show-hook'."
6143 (when (eq major-mode 'completion-list-mode)
6144 (toggle-read-only 1)))
6145
6146(add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
6147
f5fab556
MY
6148
6149;; Variables and faces used in `completion-setup-function'.
747a0e2f 6150
d0fd0916
JPW
6151(defcustom completion-show-help t
6152 "Non-nil means show help message in *Completions* buffer."
6153 :type 'boolean
6154 :version "22.1"
6155 :group 'completion)
6156
f5fab556
MY
6157;; This function goes in completion-setup-hook, so that it is called
6158;; after the text of the completion list buffer is written.
e8a700bf 6159(defun completion-setup-function ()
1b5fd09e 6160 (let* ((mainbuf (current-buffer))
a9e3ff69
SM
6161 (base-dir
6162 ;; When reading a file name in the minibuffer,
6163 ;; try and find the right default-directory to set in the
6164 ;; completion list buffer.
6165 ;; FIXME: Why do we do that, actually? --Stef
6166 (if minibuffer-completing-file-name
6167 (file-name-as-directory
6168 (expand-file-name
6169 (substring (minibuffer-completion-contents)
6170 0 (or completion-base-size 0)))))))
621a3f62 6171 (with-current-buffer standard-output
d5e63715
SM
6172 (let ((base-size completion-base-size) ;Read before killing localvars.
6173 (base-position completion-base-position))
e2947429 6174 (completion-list-mode)
d5e63715
SM
6175 (set (make-local-variable 'completion-base-size) base-size)
6176 (set (make-local-variable 'completion-base-position) base-position))
1b5fd09e 6177 (set (make-local-variable 'completion-reference-buffer) mainbuf)
a9e3ff69 6178 (if base-dir (setq default-directory base-dir))
d0fd0916
JPW
6179 ;; Maybe insert help string.
6180 (when completion-show-help
6181 (goto-char (point-min))
6182 (if (display-mouse-p)
6183 (insert (substitute-command-keys
6184 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
6185 (insert (substitute-command-keys
6186 "In this buffer, type \\[choose-completion] to \
6187select the completion near point.\n\n"))))))
c88ab9ce 6188
e8a700bf 6189(add-hook 'completion-setup-hook 'completion-setup-function)
dde69dbe 6190
1b5fd09e
SM
6191(define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
6192(define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
dde69dbe
RS
6193
6194(defun switch-to-completions ()
6195 "Select the completion list window."
6196 (interactive)
ab14d7d5 6197 (let ((window (or (get-buffer-window "*Completions*" 0)
042b7cc6 6198 ;; Make sure we have a completions window.
ab14d7d5
SM
6199 (progn (minibuffer-completion-help)
6200 (get-buffer-window "*Completions*" 0)))))
fdbd7c4d
KH
6201 (when window
6202 (select-window window)
042b7cc6
JL
6203 ;; In the new buffer, go to the first completion.
6204 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
6205 (when (bobp)
6206 (next-completion 1)))))
f6039de6
JL
6207\f
6208;;; Support keyboard commands to turn on various modifiers.
82072f33
RS
6209
6210;; These functions -- which are not commands -- each add one modifier
6211;; to the following event.
6212
6213(defun event-apply-alt-modifier (ignore-prompt)
1e96c007 6214 "\\<function-key-map>Add the Alt modifier to the following event.
70cf9f08 6215For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
82072f33
RS
6216 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
6217(defun event-apply-super-modifier (ignore-prompt)
1e96c007 6218 "\\<function-key-map>Add the Super modifier to the following event.
70cf9f08 6219For example, type \\[event-apply-super-modifier] & to enter Super-&."
82072f33
RS
6220 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
6221(defun event-apply-hyper-modifier (ignore-prompt)
1e96c007 6222 "\\<function-key-map>Add the Hyper modifier to the following event.
70cf9f08 6223For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
82072f33
RS
6224 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
6225(defun event-apply-shift-modifier (ignore-prompt)
1e96c007 6226 "\\<function-key-map>Add the Shift modifier to the following event.
70cf9f08 6227For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
82072f33
RS
6228 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
6229(defun event-apply-control-modifier (ignore-prompt)
1e96c007 6230 "\\<function-key-map>Add the Ctrl modifier to the following event.
70cf9f08 6231For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
82072f33
RS
6232 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
6233(defun event-apply-meta-modifier (ignore-prompt)
1e96c007 6234 "\\<function-key-map>Add the Meta modifier to the following event.
70cf9f08 6235For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
82072f33
RS
6236 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
6237
6238(defun event-apply-modifier (event symbol lshiftby prefix)
6239 "Apply a modifier flag to event EVENT.
6240SYMBOL is the name of this modifier, as a symbol.
6241LSHIFTBY is the numeric value of this modifier, in keyboard events.
6242PREFIX is the string that represents this modifier in an event type symbol."
6243 (if (numberp event)
6244 (cond ((eq symbol 'control)
90bebcb0
KH
6245 (if (and (<= (downcase event) ?z)
6246 (>= (downcase event) ?a))
82072f33 6247 (- (downcase event) ?a -1)
90bebcb0
KH
6248 (if (and (<= (downcase event) ?Z)
6249 (>= (downcase event) ?A))
82072f33
RS
6250 (- (downcase event) ?A -1)
6251 (logior (lsh 1 lshiftby) event))))
6252 ((eq symbol 'shift)
6253 (if (and (<= (downcase event) ?z)
6254 (>= (downcase event) ?a))
6255 (upcase event)
6256 (logior (lsh 1 lshiftby) event)))
6257 (t
6258 (logior (lsh 1 lshiftby) event)))
6259 (if (memq symbol (event-modifiers event))
6260 event
6261 (let ((event-type (if (symbolp event) event (car event))))
6262 (setq event-type (intern (concat prefix (symbol-name event-type))))
6263 (if (symbolp event)
6264 event-type
6265 (cons event-type (cdr event)))))))
6266
e5fff738
KH
6267(define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
6268(define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
6269(define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
6270(define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
6271(define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
6272(define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
f6039de6 6273\f
a3d1480b
JB
6274;;;; Keypad support.
6275
9b77469a
SM
6276;; Make the keypad keys act like ordinary typing keys. If people add
6277;; bindings for the function key symbols, then those bindings will
6278;; override these, so this shouldn't interfere with any existing
6279;; bindings.
a3d1480b 6280
0d173134 6281;; Also tell read-char how to handle these keys.
e1e04350 6282(mapc
a3d1480b
JB
6283 (lambda (keypad-normal)
6284 (let ((keypad (nth 0 keypad-normal))
6285 (normal (nth 1 keypad-normal)))
0d173134 6286 (put keypad 'ascii-character normal)
a3d1480b
JB
6287 (define-key function-key-map (vector keypad) (vector normal))))
6288 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
6289 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
f33321ad 6290 (kp-space ?\s)
a3d1480b
JB
6291 (kp-tab ?\t)
6292 (kp-enter ?\r)
6293 (kp-multiply ?*)
6294 (kp-add ?+)
6295 (kp-separator ?,)
6296 (kp-subtract ?-)
6297 (kp-decimal ?.)
6298 (kp-divide ?/)
31cd2dd4
SM
6299 (kp-equal ?=)
6300 ;; Do the same for various keys that are represented as symbols under
6301 ;; GUIs but naturally correspond to characters.
6302 (backspace 127)
6303 (delete 127)
6304 (tab ?\t)
6305 (linefeed ?\n)
6306 (clear ?\C-l)
6307 (return ?\C-m)
6308 (escape ?\e)
6309 ))
f54b0d85 6310\f
1e722f9f 6311;;;;
b005abd5 6312;;;; forking a twin copy of a buffer.
1e722f9f 6313;;;;
b005abd5
SM
6314
6315(defvar clone-buffer-hook nil
6316 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
6317
64663f06
SM
6318(defvar clone-indirect-buffer-hook nil
6319 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
6320
b005abd5
SM
6321(defun clone-process (process &optional newname)
6322 "Create a twin copy of PROCESS.
6323If NEWNAME is nil, it defaults to PROCESS' name;
6324NEWNAME is modified by adding or incrementing <N> at the end as necessary.
6325If PROCESS is associated with a buffer, the new process will be associated
6326 with the current buffer instead.
6327Returns nil if PROCESS has already terminated."
6328 (setq newname (or newname (process-name process)))
6329 (if (string-match "<[0-9]+>\\'" newname)
6330 (setq newname (substring newname 0 (match-beginning 0))))
6331 (when (memq (process-status process) '(run stop open))
6332 (let* ((process-connection-type (process-tty-name process))
b005abd5
SM
6333 (new-process
6334 (if (memq (process-status process) '(open))
ed7069af
KS
6335 (let ((args (process-contact process t)))
6336 (setq args (plist-put args :name newname))
6337 (setq args (plist-put args :buffer
403ca8d9
KS
6338 (if (process-buffer process)
6339 (current-buffer))))
ed7069af 6340 (apply 'make-network-process args))
b005abd5
SM
6341 (apply 'start-process newname
6342 (if (process-buffer process) (current-buffer))
6343 (process-command process)))))
ed7069af
KS
6344 (set-process-query-on-exit-flag
6345 new-process (process-query-on-exit-flag process))
b005abd5
SM
6346 (set-process-inherit-coding-system-flag
6347 new-process (process-inherit-coding-system-flag process))
6348 (set-process-filter new-process (process-filter process))
6349 (set-process-sentinel new-process (process-sentinel process))
403ca8d9 6350 (set-process-plist new-process (copy-sequence (process-plist process)))
b005abd5
SM
6351 new-process)))
6352
b75b82ab 6353;; things to maybe add (currently partly covered by `funcall mode'):
b005abd5
SM
6354;; - syntax-table
6355;; - overlays
6356(defun clone-buffer (&optional newname display-flag)
6b61353c
KH
6357 "Create and return a twin copy of the current buffer.
6358Unlike an indirect buffer, the new buffer can be edited
6359independently of the old one (if it is not read-only).
6360NEWNAME is the name of the new buffer. It may be modified by
6361adding or incrementing <N> at the end as necessary to create a
6362unique buffer name. If nil, it defaults to the name of the
6363current buffer, with the proper suffix. If DISPLAY-FLAG is
6364non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
6365clone a file-visiting buffer, or a buffer whose major mode symbol
6366has a non-nil `no-clone' property, results in an error.
6367
6368Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
6369current buffer with appropriate suffix. However, if a prefix
6370argument is given, then the command prompts for NEWNAME in the
6371minibuffer.
b005abd5 6372
b005abd5
SM
6373This runs the normal hook `clone-buffer-hook' in the new buffer
6374after it has been set up properly in other respects."
61acfe7f
RS
6375 (interactive
6376 (progn
6377 (if buffer-file-name
6378 (error "Cannot clone a file-visiting buffer"))
6379 (if (get major-mode 'no-clone)
6380 (error "Cannot clone a buffer in %s mode" mode-name))
f6039de6
JL
6381 (list (if current-prefix-arg
6382 (read-buffer "Name of new cloned buffer: " (current-buffer)))
61acfe7f 6383 t)))
b005abd5
SM
6384 (if buffer-file-name
6385 (error "Cannot clone a file-visiting buffer"))
6386 (if (get major-mode 'no-clone)
6387 (error "Cannot clone a buffer in %s mode" mode-name))
6388 (setq newname (or newname (buffer-name)))
6389 (if (string-match "<[0-9]+>\\'" newname)
6390 (setq newname (substring newname 0 (match-beginning 0))))
6391 (let ((buf (current-buffer))
6392 (ptmin (point-min))
6393 (ptmax (point-max))
6394 (pt (point))
6395 (mk (if mark-active (mark t)))
6396 (modified (buffer-modified-p))
6397 (mode major-mode)
6398 (lvars (buffer-local-variables))
6399 (process (get-buffer-process (current-buffer)))
6400 (new (generate-new-buffer (or newname (buffer-name)))))
6401 (save-restriction
6402 (widen)
6403 (with-current-buffer new
6404 (insert-buffer-substring buf)))
6405 (with-current-buffer new
6406 (narrow-to-region ptmin ptmax)
6407 (goto-char pt)
6408 (if mk (set-mark mk))
6409 (set-buffer-modified-p modified)
6410
6411 ;; Clone the old buffer's process, if any.
6412 (when process (clone-process process))
6413
6414 ;; Now set up the major mode.
6415 (funcall mode)
6416
6417 ;; Set up other local variables.
9ca2204b
JB
6418 (mapc (lambda (v)
6419 (condition-case () ;in case var is read-only
6420 (if (symbolp v)
6421 (makunbound v)
6422 (set (make-local-variable (car v)) (cdr v)))
6423 (error nil)))
6424 lvars)
b005abd5
SM
6425
6426 ;; Run any hooks (typically set up by the major mode
6427 ;; for cloning to work properly).
6428 (run-hooks 'clone-buffer-hook))
0a487199
SM
6429 (if display-flag
6430 ;; Presumably the current buffer is shown in the selected frame, so
6431 ;; we want to display the clone elsewhere.
6432 (let ((same-window-regexps nil)
6433 (same-window-buffer-names))
6434 (pop-to-buffer new)))
b005abd5
SM
6435 new))
6436
fa65f20b 6437
7e3afb04 6438(defun clone-indirect-buffer (newname display-flag &optional norecord)
fa65f20b
GM
6439 "Create an indirect buffer that is a twin copy of the current buffer.
6440
01ba9662 6441Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
fa65f20b
GM
6442from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
6443or if not called with a prefix arg, NEWNAME defaults to the current
6444buffer's name. The name is modified by adding a `<N>' suffix to it
1d2b0303
JB
6445or by incrementing the N in an existing suffix. Trying to clone a
6446buffer whose major mode symbol has a non-nil `no-clone-indirect'
6447property results in an error.
fa65f20b
GM
6448
6449DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7e3afb04
GM
6450This is always done when called interactively.
6451
f33321ad 6452Optional third arg NORECORD non-nil means do not put this buffer at the
7e3afb04 6453front of the list of recently selected ones."
61acfe7f
RS
6454 (interactive
6455 (progn
6456 (if (get major-mode 'no-clone-indirect)
6457 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6458 (list (if current-prefix-arg
f6039de6 6459 (read-buffer "Name of indirect buffer: " (current-buffer)))
61acfe7f
RS
6460 t)))
6461 (if (get major-mode 'no-clone-indirect)
6462 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
fa65f20b
GM
6463 (setq newname (or newname (buffer-name)))
6464 (if (string-match "<[0-9]+>\\'" newname)
6465 (setq newname (substring newname 0 (match-beginning 0))))
6466 (let* ((name (generate-new-buffer-name newname))
6467 (buffer (make-indirect-buffer (current-buffer) name t)))
64663f06
SM
6468 (with-current-buffer buffer
6469 (run-hooks 'clone-indirect-buffer-hook))
fa65f20b 6470 (when display-flag
58dd38f1 6471 (pop-to-buffer buffer norecord))
fa65f20b
GM
6472 buffer))
6473
6474
1fffd65f
RS
6475(defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
6476 "Like `clone-indirect-buffer' but display in another window."
2ef0a47e
RS
6477 (interactive
6478 (progn
6479 (if (get major-mode 'no-clone-indirect)
6480 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6481 (list (if current-prefix-arg
f6039de6 6482 (read-buffer "Name of indirect buffer: " (current-buffer)))
2ef0a47e 6483 t)))
acd39eb6 6484 (let ((pop-up-windows t))
1fffd65f 6485 (clone-indirect-buffer newname display-flag norecord)))
7e3afb04 6486
f54b0d85 6487\f
1d4b11bf
GM
6488;;; Handling of Backspace and Delete keys.
6489
30a2fded 6490(defcustom normal-erase-is-backspace 'maybe
3784ec80 6491 "Set the default behavior of the Delete and Backspace keys.
30a2fded
KL
6492
6493If set to t, Delete key deletes forward and Backspace key deletes
6494backward.
6495
6496If set to nil, both Delete and Backspace keys delete backward.
6497
6498If set to 'maybe (which is the default), Emacs automatically
3784ec80 6499selects a behavior. On window systems, the behavior depends on
30a2fded
KL
6500the keyboard used. If the keyboard has both a Backspace key and
6501a Delete key, and both are mapped to their usual meanings, the
6502option's default value is set to t, so that Backspace can be used
6503to delete backward, and Delete can be used to delete forward.
6504
6505If not running under a window system, customizing this option
6506accomplishes a similar effect by mapping C-h, which is usually
6507generated by the Backspace key, to DEL, and by mapping DEL to C-d
6508via `keyboard-translate'. The former functionality of C-h is
6509available on the F1 key. You should probably not use this
6510setting if you don't have both Backspace, Delete and F1 keys.
f060b834
GM
6511
6512Setting this variable with setq doesn't take effect. Programmatically,
7f62656b 6513call `normal-erase-is-backspace-mode' (which see) instead."
30a2fded
KL
6514 :type '(choice (const :tag "Off" nil)
6515 (const :tag "Maybe" maybe)
6516 (other :tag "On" t))
1d4b11bf
GM
6517 :group 'editing-basics
6518 :version "21.1"
6519 :set (lambda (symbol value)
6520 ;; The fboundp is because of a problem with :set when
6521 ;; dumping Emacs. It doesn't really matter.
7f62656b
EZ
6522 (if (fboundp 'normal-erase-is-backspace-mode)
6523 (normal-erase-is-backspace-mode (or value 0))
1d4b11bf
GM
6524 (set-default symbol value))))
6525
30a2fded
KL
6526(defun normal-erase-is-backspace-setup-frame (&optional frame)
6527 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
6528 (unless frame (setq frame (selected-frame)))
6529 (with-selected-frame frame
ed8dad6b 6530 (unless (terminal-parameter nil 'normal-erase-is-backspace)
08ea6d2f
SM
6531 (normal-erase-is-backspace-mode
6532 (if (if (eq normal-erase-is-backspace 'maybe)
6533 (and (not noninteractive)
6534 (or (memq system-type '(ms-dos windows-nt))
79cb9c05 6535 (memq window-system '(ns))
08ea6d2f
SM
6536 (and (memq window-system '(x))
6537 (fboundp 'x-backspace-delete-keys-p)
6538 (x-backspace-delete-keys-p))
6539 ;; If the terminal Emacs is running on has erase char
6540 ;; set to ^H, use the Backspace key for deleting
6541 ;; backward, and the Delete key for deleting forward.
6542 (and (null window-system)
6543 (eq tty-erase-char ?\^H))))
6544 normal-erase-is-backspace)
6545 1 0)))))
1d4b11bf 6546
80ac5d4d 6547(define-minor-mode normal-erase-is-backspace-mode
7f62656b
EZ
6548 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
6549
1d2b0303 6550With numeric ARG, turn the mode on if and only if ARG is positive.
7f62656b 6551
30a2fded
KL
6552On window systems, when this mode is on, Delete is mapped to C-d
6553and Backspace is mapped to DEL; when this mode is off, both
6554Delete and Backspace are mapped to DEL. (The remapping goes via
6555`local-function-key-map', so binding Delete or Backspace in the
6556global or local keymap will override that.)
7f62656b
EZ
6557
6558In addition, on window systems, the bindings of C-Delete, M-Delete,
6559C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
6560the global keymap in accordance with the functionality of Delete and
6561Backspace. For example, if Delete is remapped to C-d, which deletes
6562forward, C-Delete is bound to `kill-word', but if Delete is remapped
6563to DEL, which deletes backward, C-Delete is bound to
6564`backward-kill-word'.
6565
6566If not running on a window system, a similar effect is accomplished by
6567remapping C-h (normally produced by the Backspace key) and DEL via
6568`keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
6569to C-d; if it's off, the keys are not remapped.
6570
6571When not running on a window system, and this mode is turned on, the
6572former functionality of C-h is available on the F1 key. You should
6573probably not turn on this mode on a text-only terminal if you don't
6574have both Backspace, Delete and F1 keys.
6575
6576See also `normal-erase-is-backspace'."
80ac5d4d
SM
6577 :variable (eq (terminal-parameter
6578 nil 'normal-erase-is-backspace) 1)
6579 (let ((enabled (eq 1 (terminal-parameter
6580 nil 'normal-erase-is-backspace))))
0103b7c9 6581
9e2a2647 6582 (cond ((or (memq window-system '(x w32 ns pc))
0103b7c9
KL
6583 (memq system-type '(ms-dos windows-nt)))
6584 (let* ((bindings
411c0104 6585 `(([M-delete] [M-backspace])
0103b7c9 6586 ([C-M-delete] [C-M-backspace])
28a90c44 6587 ([?\e C-delete] [?\e C-backspace])))
0103b7c9
KL
6588 (old-state (lookup-key local-function-key-map [delete])))
6589
6590 (if enabled
6591 (progn
b8a47412 6592 (define-key local-function-key-map [delete] [deletechar])
0103b7c9 6593 (define-key local-function-key-map [kp-delete] [?\C-d])
28a90c44
SM
6594 (define-key local-function-key-map [backspace] [?\C-?])
6595 (dolist (b bindings)
6596 ;; Not sure if input-decode-map is really right, but
6597 ;; keyboard-translate-table (used below) only works
6598 ;; for integer events, and key-translation-table is
6599 ;; global (like the global-map, used earlier).
6600 (define-key input-decode-map (car b) nil)
6601 (define-key input-decode-map (cadr b) nil)))
0103b7c9
KL
6602 (define-key local-function-key-map [delete] [?\C-?])
6603 (define-key local-function-key-map [kp-delete] [?\C-?])
28a90c44
SM
6604 (define-key local-function-key-map [backspace] [?\C-?])
6605 (dolist (b bindings)
6606 (define-key input-decode-map (car b) (cadr b))
6607 (define-key input-decode-map (cadr b) (car b))))))
0103b7c9
KL
6608 (t
6609 (if enabled
ec9f4754 6610 (progn
0103b7c9
KL
6611 (keyboard-translate ?\C-h ?\C-?)
6612 (keyboard-translate ?\C-? ?\C-d))
6613 (keyboard-translate ?\C-h ?\C-h)
6614 (keyboard-translate ?\C-? ?\C-?))))
6615
32226619 6616 (if (called-interactively-p 'interactive)
0103b7c9 6617 (message "Delete key deletes %s"
b08016f2 6618 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
0103b7c9 6619 "forward" "backward")))))
ea82f0df 6620\f
aca8bee5 6621(defvar vis-mode-saved-buffer-invisibility-spec nil
0f7df535 6622 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
7f62656b 6623
0f7df535
RS
6624(define-minor-mode visible-mode
6625 "Toggle Visible mode.
4837b516
GM
6626With argument ARG turn Visible mode on if ARG is positive, otherwise
6627turn it off.
1d4b11bf 6628
0f7df535 6629Enabling Visible mode makes all invisible text temporarily visible.
1d2b0303
JB
6630Disabling Visible mode turns off that effect. Visible mode works by
6631saving the value of `buffer-invisibility-spec' and setting it to nil."
4e57881d 6632 :lighter " Vis"
ab77efd0 6633 :group 'editing-basics
aca8bee5
SM
6634 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
6635 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
6636 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
0f7df535 6637 (when visible-mode
aca8bee5
SM
6638 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
6639 buffer-invisibility-spec)
6640 (setq buffer-invisibility-spec nil)))
4e57881d 6641\f
30ee26a9 6642;; Partial application of functions (similar to "currying").
a185548b 6643;; This function is here rather than in subr.el because it uses CL.
30ee26a9
EZ
6644(defun apply-partially (fun &rest args)
6645 "Return a function that is a partial application of FUN to ARGS.
6646ARGS is a list of the first N arguments to pass to FUN.
6647The result is a new function which does the same as FUN, except that
6648the first N arguments are fixed at the values with which this function
6649was called."
6650 (lexical-let ((fun fun) (args1 args))
6651 (lambda (&rest args2) (apply fun (append args1 args2)))))
6652\f
e1e04350 6653;; Minibuffer prompt stuff.
9b350152 6654
49c14a05
GM
6655;(defun minibuffer-prompt-modification (start end)
6656; (error "You cannot modify the prompt"))
6657;
6658;
6659;(defun minibuffer-prompt-insertion (start end)
6660; (let ((inhibit-modification-hooks t))
6661; (delete-region start end)
6662; ;; Discard undo information for the text insertion itself
6663; ;; and for the text deletion.above.
6664; (when (consp buffer-undo-list)
6665; (setq buffer-undo-list (cddr buffer-undo-list)))
6666; (message "You cannot modify the prompt")))
6667;
6668;
f1180544 6669;(setq minibuffer-prompt-properties
49c14a05
GM
6670; (list 'modification-hooks '(minibuffer-prompt-modification)
6671; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
f1180544 6672;
9b350152 6673
a2603048
GM
6674\f
6675;;;; Problematic external packages.
6676
6677;; rms says this should be done by specifying symbols that define
6678;; versions together with bad values. This is therefore not as
6679;; flexible as it could be. See the thread:
6680;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
6681(defconst bad-packages-alist
6682 ;; Not sure exactly which semantic versions have problems.
6683 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
7796ee61 6684 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
a2603048 6685 "The version of `semantic' loaded does not work in Emacs 22.
72d595b5
GM
6686It can cause constant high CPU load.
6687Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
a2603048
GM
6688 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
6689 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
6690 ;; provided the `CUA-mode' feature. Since this is no longer true,
6691 ;; we can warn the user if the `CUA-mode' feature is ever provided.
6692 (CUA-mode t nil
6693"CUA-mode is now part of the standard GNU Emacs distribution,
6694so you can now enable CUA via the Options menu or by customizing `cua-mode'.
6695
6696You have loaded an older version of CUA-mode which does not work
6697correctly with this version of Emacs. You should remove the old
6698version and use the one distributed with Emacs."))
6699 "Alist of packages known to cause problems in this version of Emacs.
6700Each element has the form (PACKAGE SYMBOL REGEXP STRING).
6701PACKAGE is either a regular expression to match file names, or a
6702symbol (a feature name); see the documentation of
6703`after-load-alist', to which this variable adds functions.
6704SYMBOL is either the name of a string variable, or `t'. Upon
6705loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
6706warning using STRING as the message.")
6707
6708(defun bad-package-check (package)
6709 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
6710 (condition-case nil
6711 (let* ((list (assoc package bad-packages-alist))
6712 (symbol (nth 1 list)))
6713 (and list
6714 (boundp symbol)
6715 (or (eq symbol t)
6716 (and (stringp (setq symbol (eval symbol)))
9bc505ab
JB
6717 (string-match-p (nth 2 list) symbol)))
6718 (display-warning package (nth 3 list) :warning)))
a2603048
GM
6719 (error nil)))
6720
6721(mapc (lambda (elem)
6722 (eval-after-load (car elem) `(bad-package-check ',(car elem))))
6723 bad-packages-alist)
6724
6725
00398e3b 6726(provide 'simple)
6b61353c 6727
c88ab9ce 6728;;; simple.el ends here