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