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