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