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