*** empty log message ***
[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
151that would normally be considered usable. if it returns nil,
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
172The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffers
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.
2767\(This is meant to make C-x z 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.
22c8bff1
KS
3436 (if (and (not (integerp selective-display))
3437 (not (line-move-invisible-p (point))))
e9ab825f
RS
3438 ;; We avoid vertical-motion when possible
3439 ;; because that has to fontify.
3440 (if (eobp)
22c8bff1
KS
3441 (if (not noerror)
3442 (signal 'end-of-buffer nil)
3443 (setq done t))
e9ab825f
RS
3444 (forward-line 1))
3445 ;; Otherwise move a more sophisticated way.
3446 ;; (What's the logic behind this code?)
3447 (and (zerop (vertical-motion 1))
3448 (if (not noerror)
3449 (signal 'end-of-buffer nil)
3450 (setq done t))))
bbf41690
RS
3451 (unless done
3452 (setq arg (1- arg))))
22c8bff1 3453 ;; The logic of this is the same as the loop above,
e9ab825f 3454 ;; it just goes in the other direction.
bbf41690
RS
3455 (while (and (< arg 0) (not done))
3456 (beginning-of-line)
22c8bff1
KS
3457 (if (or (bobp)
3458 (and (not (integerp selective-display))
3459 (not (line-move-invisible-p (1- (point))))))
e9ab825f 3460 (if (bobp)
f33ae5d0
RS
3461 (if (not noerror)
3462 (signal 'beginning-of-buffer nil)
3463 (setq done t))
e9ab825f
RS
3464 (forward-line -1))
3465 (if (zerop (vertical-motion -1))
3466 (if (not noerror)
3467 (signal 'beginning-of-buffer nil)
3468 (setq done t))))
bbf41690
RS
3469 (unless done
3470 (setq arg (1+ arg))
3471 (while (and ;; Don't move over previous invis lines
3472 ;; if our target is the middle of this line.
3473 (or (zerop (or goal-column temporary-goal-column))
3474 (< arg 0))
3475 (not (bobp)) (line-move-invisible-p (1- (point))))
3476 (goto-char (previous-char-property-change (point))))))))
3477 ;; This is the value the function returns.
3478 (= arg 0))
af894fc9 3479
e9cd25fe
RS
3480 (cond ((> arg 0)
3481 ;; If we did not move down as far as desired,
3482 ;; at least go to end of line.
3483 (end-of-line))
3484 ((< arg 0)
3485 ;; If we did not move down as far as desired,
3486 ;; at least go to end of line.
3487 (beginning-of-line))
3488 (t
20782abb
RS
3489 (line-move-finish (or goal-column temporary-goal-column)
3490 opoint forward))))))
2076c87c 3491
20782abb 3492(defun line-move-finish (column opoint forward)
af894fc9
RS
3493 (let ((repeat t))
3494 (while repeat
3495 ;; Set REPEAT to t to repeat the whole thing.
3496 (setq repeat nil)
3497
1f980920 3498 (let (new
af894fc9 3499 (line-beg (save-excursion (beginning-of-line) (point)))
1f980920
RS
3500 (line-end
3501 ;; Compute the end of the line
20782abb 3502 ;; ignoring effectively invisible newlines.
bbf41690 3503 (save-excursion
20782abb
RS
3504 (end-of-line)
3505 (while (and (not (eobp)) (line-move-invisible-p (point)))
3506 (goto-char (next-char-property-change (point)))
bbf41690
RS
3507 (end-of-line))
3508 (point))))
1f980920
RS
3509
3510 ;; Move to the desired column.
3511 (line-move-to-column column)
3512 (setq new (point))
af894fc9
RS
3513
3514 ;; Process intangibility within a line.
3515 ;; Move to the chosen destination position from above,
3516 ;; with intangibility processing enabled.
3517
3518 (goto-char (point-min))
3519 (let ((inhibit-point-motion-hooks nil))
3520 (goto-char new)
3521
3522 ;; If intangibility moves us to a different (later) place
3523 ;; in the same line, use that as the destination.
3524 (if (<= (point) line-end)
1f980920
RS
3525 (setq new (point))
3526 ;; If that position is "too late",
3527 ;; try the previous allowable position.
3528 ;; See if it is ok.
3529 (backward-char)
20782abb
RS
3530 (if (if forward
3531 ;; If going forward, don't accept the previous
3532 ;; allowable position if it is before the target line.
f1e2a033 3533 (< line-beg (point))
20782abb
RS
3534 ;; If going backward, don't accept the previous
3535 ;; allowable position if it is still after the target line.
3536 (<= (point) line-end))
1f980920
RS
3537 (setq new (point))
3538 ;; As a last resort, use the end of the line.
3539 (setq new line-end))))
af894fc9
RS
3540
3541 ;; Now move to the updated destination, processing fields
3542 ;; as well as intangibility.
3543 (goto-char opoint)
3544 (let ((inhibit-point-motion-hooks nil))
3545 (goto-char
3546 (constrain-to-field new opoint nil t
3547 'inhibit-line-move-field-capture)))
3548
1f980920 3549 ;; If all this moved us to a different line,
af894fc9
RS
3550 ;; retry everything within that new line.
3551 (when (or (< (point) line-beg) (> (point) line-end))
3552 ;; Repeat the intangibility and field processing.
3553 (setq repeat t))))))
3554
3555(defun line-move-to-column (col)
3556 "Try to find column COL, considering invisibility.
3557This function works only in certain cases,
3558because what we really need is for `move-to-column'
3559and `current-column' to be able to ignore invisible text."
a615252b
RS
3560 (if (zerop col)
3561 (beginning-of-line)
3562 (move-to-column col))
af894fc9
RS
3563
3564 (when (and line-move-ignore-invisible
bbf41690 3565 (not (bolp)) (line-move-invisible-p (1- (point))))
af894fc9
RS
3566 (let ((normal-location (point))
3567 (normal-column (current-column)))
3568 ;; If the following character is currently invisible,
3569 ;; skip all characters with that same `invisible' property value.
3570 (while (and (not (eobp))
bbf41690 3571 (line-move-invisible-p (point)))
af894fc9
RS
3572 (goto-char (next-char-property-change (point))))
3573 ;; Have we advanced to a larger column position?
3574 (if (> (current-column) normal-column)
3575 ;; We have made some progress towards the desired column.
3576 ;; See if we can make any further progress.
3577 (line-move-to-column (+ (current-column) (- col normal-column)))
3578 ;; Otherwise, go to the place we originally found
3579 ;; and move back over invisible text.
3580 ;; that will get us to the same place on the screen
3581 ;; but with a more reasonable buffer position.
3582 (goto-char normal-location)
3583 (let ((line-beg (save-excursion (beginning-of-line) (point))))
bbf41690 3584 (while (and (not (bolp)) (line-move-invisible-p (1- (point))))
af894fc9
RS
3585 (goto-char (previous-char-property-change (point) line-beg))))))))
3586
bbf41690
RS
3587(defun move-end-of-line (arg)
3588 "Move point to end of current line.
3589With argument ARG not nil or 1, move forward ARG - 1 lines first.
3590If point reaches the beginning or end of buffer, it stops there.
3591To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
3592
3593This command does not move point across a field boundary unless doing so
3594would move beyond there to a different line; if ARG is nil or 1, and
3595point starts at a field boundary, point does not move. To ignore field
3596boundaries bind `inhibit-field-text-motion' to t."
3597 (interactive "p")
3598 (or arg (setq arg 1))
3599 (let (done)
3600 (while (not done)
3601 (let ((newpos
3602 (save-excursion
3603 (let ((goal-column 0))
3604 (and (line-move arg t)
3605 (not (bobp))
3606 (progn
3607 (while (and (not (bobp)) (line-move-invisible-p (1- (point))))
3608 (goto-char (previous-char-property-change (point))))
3609 (backward-char 1)))
3610 (point)))))
3611 (goto-char newpos)
3612 (if (and (> (point) newpos)
3613 (eq (preceding-char) ?\n))
3614 (backward-char 1)
3615 (if (and (> (point) newpos) (not (eobp))
3616 (not (eq (following-char) ?\n)))
3617 ;; If we skipped something intangible
3618 ;; and now we're not really at eol,
3619 ;; keep going.
3620 (setq arg 1)
3621 (setq done t)))))))
3622
0cbb497c
KS
3623(defun move-beginning-of-line (arg)
3624 "Move point to beginning of current display line.
3625With argument ARG not nil or 1, move forward ARG - 1 lines first.
3626If point reaches the beginning or end of buffer, it stops there.
3627To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
3628
3629This command does not move point across a field boundary unless doing so
3630would move beyond there to a different line; if ARG is nil or 1, and
3631point starts at a field boundary, point does not move. To ignore field
3632boundaries bind `inhibit-field-text-motion' to t."
3633 (interactive "p")
3634 (or arg (setq arg 1))
3635 (if (/= arg 1)
3636 (line-move (1- arg) t))
bfb1a447 3637 (beginning-of-line 1)
89767eec
KS
3638 (let ((orig (point)))
3639 (vertical-motion 0)
bfb1a447
KS
3640 (if (/= orig (point))
3641 (goto-char (constrain-to-field (point) orig (/= arg 1) t nil)))))
0cbb497c
KS
3642
3643
d5ab2033
JB
3644;;; Many people have said they rarely use this feature, and often type
3645;;; it by accident. Maybe it shouldn't even be on a key.
3646(put 'set-goal-column 'disabled t)
2076c87c
JB
3647
3648(defun set-goal-column (arg)
3649 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
3650Those commands will move to this position in the line moved to
3651rather than trying to keep the same horizontal position.
3652With a non-nil argument, clears out the goal column
912c6728
RS
3653so that \\[next-line] and \\[previous-line] resume vertical motion.
3654The goal column is stored in the variable `goal-column'."
2076c87c
JB
3655 (interactive "P")
3656 (if arg
3657 (progn
3658 (setq goal-column nil)
3659 (message "No goal column"))
3660 (setq goal-column (current-column))
3661 (message (substitute-command-keys
3662 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
3663 goal-column))
3664 nil)
2d88b556 3665\f
7492f5a6
RS
3666
3667(defun scroll-other-window-down (lines)
e47d38f6
RS
3668 "Scroll the \"other window\" down.
3669For more details, see the documentation for `scroll-other-window'."
7492f5a6
RS
3670 (interactive "P")
3671 (scroll-other-window
3672 ;; Just invert the argument's meaning.
3673 ;; We can do that without knowing which window it will be.
3674 (if (eq lines '-) nil
3675 (if (null lines) '-
3676 (- (prefix-numeric-value lines))))))
3aef9604
RS
3677
3678(defun beginning-of-buffer-other-window (arg)
3679 "Move point to the beginning of the buffer in the other window.
3680Leave mark at previous position.
3681With arg N, put point N/10 of the way from the true beginning."
3682 (interactive "P")
3683 (let ((orig-window (selected-window))
3684 (window (other-window-for-scrolling)))
3685 ;; We use unwind-protect rather than save-window-excursion
3686 ;; because the latter would preserve the things we want to change.
3687 (unwind-protect
3688 (progn
3689 (select-window window)
3690 ;; Set point and mark in that window's buffer.
bbf41690
RS
3691 (with-no-warnings
3692 (beginning-of-buffer arg))
3aef9604
RS
3693 ;; Set point accordingly.
3694 (recenter '(t)))
3695 (select-window orig-window))))
3696
3697(defun end-of-buffer-other-window (arg)
3698 "Move point to the end of the buffer in the other window.
3699Leave mark at previous position.
3700With arg N, put point N/10 of the way from the true end."
3701 (interactive "P")
3702 ;; See beginning-of-buffer-other-window for comments.
3703 (let ((orig-window (selected-window))
3704 (window (other-window-for-scrolling)))
3705 (unwind-protect
3706 (progn
3707 (select-window window)
bbf41690
RS
3708 (with-no-warnings
3709 (end-of-buffer arg))
3aef9604
RS
3710 (recenter '(t)))
3711 (select-window orig-window))))
2d88b556 3712\f
2076c87c
JB
3713(defun transpose-chars (arg)
3714 "Interchange characters around point, moving forward one character.
3715With prefix arg ARG, effect is to take character before point
3716and drag it forward past ARG other characters (backward if ARG negative).
3717If no argument and at end of line, the previous two chars are exchanged."
3718 (interactive "*P")
3719 (and (null arg) (eolp) (forward-char -1))
3720 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3721
3722(defun transpose-words (arg)
3723 "Interchange words around point, leaving point at end of them.
3724With prefix arg ARG, effect is to take word before or around point
3725and drag it forward past ARG other words (backward if ARG negative).
3726If ARG is zero, the words around or after point and around or after mark
3727are interchanged."
41d22ee0 3728 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
2076c87c
JB
3729 (interactive "*p")
3730 (transpose-subr 'forward-word arg))
3731
3732(defun transpose-sexps (arg)
3733 "Like \\[transpose-words] but applies to sexps.
3734Does not work on a sexp that point is in the middle of
3735if it is a list or string."
3736 (interactive "*p")
41d22ee0
SM
3737 (transpose-subr
3738 (lambda (arg)
3739 ;; Here we should try to simulate the behavior of
3740 ;; (cons (progn (forward-sexp x) (point))
3741 ;; (progn (forward-sexp (- x)) (point)))
3742 ;; Except that we don't want to rely on the second forward-sexp
3743 ;; putting us back to where we want to be, since forward-sexp-function
3744 ;; might do funny things like infix-precedence.
3745 (if (if (> arg 0)
3746 (looking-at "\\sw\\|\\s_")
3747 (and (not (bobp))
3748 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
3749 ;; Jumping over a symbol. We might be inside it, mind you.
3750 (progn (funcall (if (> arg 0)
3751 'skip-syntax-backward 'skip-syntax-forward)
3752 "w_")
3753 (cons (save-excursion (forward-sexp arg) (point)) (point)))
3754 ;; Otherwise, we're between sexps. Take a step back before jumping
3755 ;; to make sure we'll obey the same precedence no matter which direction
3756 ;; we're going.
3757 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
3758 (cons (save-excursion (forward-sexp arg) (point))
3759 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
3760 (not (zerop (funcall (if (> arg 0)
3761 'skip-syntax-forward
3762 'skip-syntax-backward)
3763 ".")))))
3764 (point)))))
3765 arg 'special))
2076c87c
JB
3766
3767(defun transpose-lines (arg)
3768 "Exchange current line and previous line, leaving point after both.
3769With argument ARG, takes previous line and moves it past ARG lines.
3770With argument 0, interchanges line point is in with line mark is in."
3771 (interactive "*p")
3772 (transpose-subr (function
3773 (lambda (arg)
d3f4ef3f 3774 (if (> arg 0)
2076c87c 3775 (progn
d3f4ef3f
AS
3776 ;; Move forward over ARG lines,
3777 ;; but create newlines if necessary.
3778 (setq arg (forward-line arg))
3779 (if (/= (preceding-char) ?\n)
3780 (setq arg (1+ arg)))
3781 (if (> arg 0)
3782 (newline arg)))
2076c87c
JB
3783 (forward-line arg))))
3784 arg))
3785
e1e04350
SM
3786(defun transpose-subr (mover arg &optional special)
3787 (let ((aux (if special mover
3788 (lambda (x)
3789 (cons (progn (funcall mover x) (point))
3790 (progn (funcall mover (- x)) (point))))))
3791 pos1 pos2)
3792 (cond
3793 ((= arg 0)
3794 (save-excursion
3795 (setq pos1 (funcall aux 1))
3796 (goto-char (mark))
3797 (setq pos2 (funcall aux 1))
3798 (transpose-subr-1 pos1 pos2))
3799 (exchange-point-and-mark))
3800 ((> arg 0)
3801 (setq pos1 (funcall aux -1))
3802 (setq pos2 (funcall aux arg))
3803 (transpose-subr-1 pos1 pos2)
3804 (goto-char (car pos2)))
3805 (t
3806 (setq pos1 (funcall aux -1))
3807 (goto-char (car pos1))
3808 (setq pos2 (funcall aux arg))
3809 (transpose-subr-1 pos1 pos2)))))
3810
3811(defun transpose-subr-1 (pos1 pos2)
3812 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
3813 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
3814 (when (> (car pos1) (car pos2))
3815 (let ((swap pos1))
3816 (setq pos1 pos2 pos2 swap)))
3817 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
dc7d7552
RS
3818 (atomic-change-group
3819 (let (word2)
1e96c007
SM
3820 ;; FIXME: We first delete the two pieces of text, so markers that
3821 ;; used to point to after the text end up pointing to before it :-(
dc7d7552
RS
3822 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
3823 (goto-char (car pos2))
3824 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
3825 (goto-char (car pos1))
3826 (insert word2))))
2d88b556 3827\f
b82d844f 3828(defun backward-word (&optional arg)
b7e91b0c 3829 "Move backward until encountering the beginning of a word.
20ecc110 3830With argument, do this that many times."
9e50756b 3831 (interactive "p")
b82d844f 3832 (forward-word (- (or arg 1))))
2076c87c 3833
a1a801de 3834(defun mark-word (&optional arg allow-extend)
705a5933
JL
3835 "Set mark ARG words away from point.
3836The place mark goes is the same place \\[forward-word] would
3837move to with the same argument.
a1a801de 3838Interactively, if this command is repeated
771069f8 3839or (in Transient Mark mode) if the mark is active,
705a5933 3840it marks the next ARG words after the ones already marked."
a1a801de
RS
3841 (interactive "P\np")
3842 (cond ((and allow-extend
3843 (or (and (eq last-command this-command) (mark t))
3844 (and transient-mark-mode mark-active)))
705a5933
JL
3845 (setq arg (if arg (prefix-numeric-value arg)
3846 (if (< (mark) (point)) -1 1)))
cad113ae
KG
3847 (set-mark
3848 (save-excursion
3849 (goto-char (mark))
3850 (forward-word arg)
3851 (point))))
3852 (t
3853 (push-mark
3854 (save-excursion
705a5933 3855 (forward-word (prefix-numeric-value arg))
cad113ae
KG
3856 (point))
3857 nil t))))
2076c87c
JB
3858
3859(defun kill-word (arg)
3860 "Kill characters forward until encountering the end of a word.
3861With argument, do this that many times."
e761e42c 3862 (interactive "p")
89ee2bf6 3863 (kill-region (point) (progn (forward-word arg) (point))))
2076c87c
JB
3864
3865(defun backward-kill-word (arg)
3866 "Kill characters backward until encountering the end of a word.
3867With argument, do this that many times."
e761e42c 3868 (interactive "p")
2076c87c 3869 (kill-word (- arg)))
d7c64071 3870
0f7df535
RS
3871(defun current-word (&optional strict really-word)
3872 "Return the symbol or word that point is on (or a nearby one) as a string.
3873The return value includes no text properties.
1e8c5ac4 3874If optional arg STRICT is non-nil, return nil unless point is within
0fa19a57
RS
3875or adjacent to a symbol or word. In all cases the value can be nil
3876if there is no word nearby.
0f7df535
RS
3877The function, belying its name, normally finds a symbol.
3878If optional arg REALLY-WORD is non-nil, it finds just a word."
d7c64071 3879 (save-excursion
0f7df535 3880 (let* ((oldpoint (point)) (start (point)) (end (point))
81d17173 3881 (syntaxes (if really-word "w" "w_"))
0f7df535
RS
3882 (not-syntaxes (concat "^" syntaxes)))
3883 (skip-syntax-backward syntaxes) (setq start (point))
d7c64071 3884 (goto-char oldpoint)
0f7df535
RS
3885 (skip-syntax-forward syntaxes) (setq end (point))
3886 (when (and (eq start oldpoint) (eq end oldpoint)
3887 ;; Point is neither within nor adjacent to a word.
3888 (not strict))
3889 ;; Look for preceding word in same line.
3890 (skip-syntax-backward not-syntaxes
3891 (save-excursion (beginning-of-line)
3892 (point)))
3893 (if (bolp)
3894 ;; No preceding word in same line.
3895 ;; Look for following word in same line.
3896 (progn
3897 (skip-syntax-forward not-syntaxes
3898 (save-excursion (end-of-line)
3899 (point)))
3900 (setq start (point))
3901 (skip-syntax-forward syntaxes)
3902 (setq end (point)))
3903 (setq end (point))
3904 (skip-syntax-backward syntaxes)
3905 (setq start (point))))
3906 ;; If we found something nonempty, return it as a string.
3907 (unless (= start end)
020db25f 3908 (buffer-substring-no-properties start end)))))
2d88b556 3909\f
69c1dd37 3910(defcustom fill-prefix nil
e1e04350 3911 "*String for filling to insert at front of new line, or nil for none."
69c1dd37
RS
3912 :type '(choice (const :tag "None" nil)
3913 string)
3914 :group 'fill)
2076c87c
JB
3915(make-variable-buffer-local 'fill-prefix)
3916
69c1dd37
RS
3917(defcustom auto-fill-inhibit-regexp nil
3918 "*Regexp to match lines which should not be auto-filled."
3919 :type '(choice (const :tag "None" nil)
3920 regexp)
3921 :group 'fill)
2076c87c 3922
58dd38f1 3923(defvar comment-line-break-function 'comment-indent-new-line
b3ac9fa9
RS
3924 "*Mode-specific function which line breaks and continues a comment.
3925
3926This function is only called during auto-filling of a comment section.
3927The function should take a single optional argument, which is a flag
3928indicating whether it should use soft newlines.
3929
3930Setting this variable automatically makes it local to the current buffer.")
3931
dbe524b6 3932;; This function is used as the auto-fill-function of a buffer
e2504204
KH
3933;; when Auto-Fill mode is enabled.
3934;; It returns t if it really did any work.
dbe524b6
RS
3935;; (Actually some major modes use a different auto-fill function,
3936;; but this one is the default one.)
2076c87c 3937(defun do-auto-fill ()
621a3f62 3938 (let (fc justify give-up
a0170800 3939 (fill-prefix fill-prefix))
c18465c4 3940 (if (or (not (setq justify (current-justification)))
8f066a20
RS
3941 (null (setq fc (current-fill-column)))
3942 (and (eq justify 'left)
3943 (<= (current-column) fc))
621a3f62
SM
3944 (and auto-fill-inhibit-regexp
3945 (save-excursion (beginning-of-line)
eed5698b
RS
3946 (looking-at auto-fill-inhibit-regexp))))
3947 nil ;; Auto-filling not required
3db1e3b5
BG
3948 (if (memq justify '(full center right))
3949 (save-excursion (unjustify-current-line)))
a0170800
RS
3950
3951 ;; Choose a fill-prefix automatically.
e1e04350
SM
3952 (when (and adaptive-fill-mode
3953 (or (null fill-prefix) (string= fill-prefix "")))
3954 (let ((prefix
3955 (fill-context-prefix
3956 (save-excursion (backward-paragraph 1) (point))
3957 (save-excursion (forward-paragraph 1) (point)))))
3958 (and prefix (not (equal prefix ""))
3959 ;; Use auto-indentation rather than a guessed empty prefix.
0e53a373 3960 (not (and fill-indent-according-to-mode
d99f8496 3961 (string-match "\\`[ \t]*\\'" prefix)))
e1e04350 3962 (setq fill-prefix prefix))))
f1180544 3963
eed5698b 3964 (while (and (not give-up) (> (current-column) fc))
e47d38f6 3965 ;; Determine where to split the line.
db893d00
RS
3966 (let* (after-prefix
3967 (fill-point
621a3f62
SM
3968 (save-excursion
3969 (beginning-of-line)
3970 (setq after-prefix (point))
3971 (and fill-prefix
3972 (looking-at (regexp-quote fill-prefix))
3973 (setq after-prefix (match-end 0)))
3974 (move-to-column (1+ fc))
3975 (fill-move-to-break-point after-prefix)
3976 (point))))
db893d00
RS
3977
3978 ;; See whether the place we found is any good.
e47d38f6
RS
3979 (if (save-excursion
3980 (goto-char fill-point)
41d22ee0
SM
3981 (or (bolp)
3982 ;; There is no use breaking at end of line.
3983 (save-excursion (skip-chars-forward " ") (eolp))
3984 ;; It is futile to split at the end of the prefix
3985 ;; since we would just insert the prefix again.
3986 (and after-prefix (<= (point) after-prefix))
3987 ;; Don't split right after a comment starter
3988 ;; since we would just make another comment starter.
3989 (and comment-start-skip
3990 (let ((limit (point)))
3991 (beginning-of-line)
3992 (and (re-search-forward comment-start-skip
3993 limit t)
3994 (eq (point) limit))))))
3995 ;; No good place to break => stop trying.
3996 (setq give-up t)
3997 ;; Ok, we have a useful place to break the line. Do it.
3998 (let ((prev-column (current-column)))
3999 ;; If point is at the fill-point, do not `save-excursion'.
4000 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
4001 ;; point will end up before it rather than after it.
4002 (if (save-excursion
4003 (skip-chars-backward " \t")
4004 (= (point) fill-point))
4005 (funcall comment-line-break-function t)
4006 (save-excursion
4007 (goto-char fill-point)
4008 (funcall comment-line-break-function t)))
4009 ;; Now do justification, if required
4010 (if (not (eq justify 'left))
e47d38f6 4011 (save-excursion
e1e04350
SM
4012 (end-of-line 0)
4013 (justify-current-line justify nil t)))
41d22ee0
SM
4014 ;; If making the new line didn't reduce the hpos of
4015 ;; the end of the line, then give up now;
4016 ;; trying again will not help.
4017 (if (>= (current-column) prev-column)
4018 (setq give-up t))))))
24ebf92e 4019 ;; Justify last line.
e2504204 4020 (justify-current-line justify t t)
1e722f9f 4021 t)))
2076c87c 4022
24ebf92e
RS
4023(defvar normal-auto-fill-function 'do-auto-fill
4024 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
4025Some major modes set this.")
4026
c75505b4 4027(put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
d99f8496
SM
4028;; FIXME: turn into a proper minor mode.
4029;; Add a global minor mode version of it.
d7465b15 4030(defun auto-fill-mode (&optional arg)
24ebf92e
RS
4031 "Toggle Auto Fill mode.
4032With arg, turn Auto Fill mode on if and only if arg is positive.
4033In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
4034automatically breaks the line at a previous space.
4035
4036The value of `normal-auto-fill-function' specifies the function to use
4037for `auto-fill-function' when turning Auto Fill mode on."
d7465b15
RS
4038 (interactive "P")
4039 (prog1 (setq auto-fill-function
4040 (if (if (null arg)
4041 (not auto-fill-function)
4042 (> (prefix-numeric-value arg) 0))
24ebf92e 4043 normal-auto-fill-function
d7465b15 4044 nil))
7911ecc8 4045 (force-mode-line-update)))
d7465b15
RS
4046
4047;; This holds a document string used to document auto-fill-mode.
4048(defun auto-fill-function ()
4049 "Automatically break line at a previous space, in insertion of text."
4050 nil)
4051
4052(defun turn-on-auto-fill ()
4053 "Unconditionally turn on Auto Fill mode."
4054 (auto-fill-mode 1))
3a99c819
GM
4055
4056(defun turn-off-auto-fill ()
4057 "Unconditionally turn off Auto Fill mode."
4058 (auto-fill-mode -1))
4059
7cbf1dc1 4060(custom-add-option 'text-mode-hook 'turn-on-auto-fill)
d7465b15
RS
4061
4062(defun set-fill-column (arg)
4cc0ea11 4063 "Set `fill-column' to specified argument.
923efb99 4064Use \\[universal-argument] followed by a number to specify a column.
4cc0ea11 4065Just \\[universal-argument] as argument means to use the current column."
d7465b15 4066 (interactive "P")
f4520363
RS
4067 (if (consp arg)
4068 (setq arg (current-column)))
4069 (if (not (integerp arg))
4070 ;; Disallow missing argument; it's probably a typo for C-x C-f.
6904b34b 4071 (error "Set-fill-column requires an explicit argument")
f4520363
RS
4072 (message "Fill column set to %d (was %d)" arg fill-column)
4073 (setq fill-column arg)))
2d88b556 4074\f
2076c87c 4075(defun set-selective-display (arg)
ff1fbe3e
RS
4076 "Set `selective-display' to ARG; clear it if no arg.
4077When the value of `selective-display' is a number > 0,
4078lines whose indentation is >= that value are not displayed.
4079The variable `selective-display' has a separate value for each buffer."
2076c87c
JB
4080 (interactive "P")
4081 (if (eq selective-display t)
4082 (error "selective-display already in use for marked lines"))
c88ab9ce
ER
4083 (let ((current-vpos
4084 (save-restriction
4085 (narrow-to-region (point-min) (point))
4086 (goto-char (window-start))
4087 (vertical-motion (window-height)))))
4088 (setq selective-display
4089 (and arg (prefix-numeric-value arg)))
4090 (recenter current-vpos))
2076c87c
JB
4091 (set-window-start (selected-window) (window-start (selected-window)))
4092 (princ "selective-display set to " t)
4093 (prin1 selective-display t)
4094 (princ "." t))
4095
40a64816
RS
4096(defvaralias 'indicate-unused-lines 'indicate-empty-lines)
4097(defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
4098
0bb64d76
PA
4099(defun toggle-truncate-lines (arg)
4100 "Toggle whether to fold or truncate long lines on the screen.
46cdfe8f
RS
4101With arg, truncate long lines iff arg is positive.
4102Note that in side-by-side windows, truncation is always enabled."
0bb64d76
PA
4103 (interactive "P")
4104 (setq truncate-lines
4105 (if (null arg)
4106 (not truncate-lines)
46cdfe8f
RS
4107 (> (prefix-numeric-value arg) 0)))
4108 (force-mode-line-update)
4f017185
RS
4109 (unless truncate-lines
4110 (let ((buffer (current-buffer)))
4111 (walk-windows (lambda (window)
4112 (if (eq buffer (window-buffer window))
4113 (set-window-hscroll window 0)))
4114 nil t)))
46cdfe8f
RS
4115 (message "Truncate long lines %s"
4116 (if truncate-lines "enabled" "disabled")))
0bb64d76 4117
4f8f7f9f 4118(defvar overwrite-mode-textual " Ovwrt"
b6a22db0 4119 "The string displayed in the mode line when in overwrite mode.")
4f8f7f9f 4120(defvar overwrite-mode-binary " Bin Ovwrt"
b6a22db0
JB
4121 "The string displayed in the mode line when in binary overwrite mode.")
4122
2076c87c
JB
4123(defun overwrite-mode (arg)
4124 "Toggle overwrite mode.
4125With arg, turn overwrite mode on iff arg is positive.
4126In overwrite mode, printing characters typed in replace existing text
b6a22db0
JB
4127on a one-for-one basis, rather than pushing it to the right. At the
4128end of a line, such characters extend the line. Before a tab,
4129such characters insert until the tab is filled in.
4130\\[quoted-insert] still inserts characters in overwrite mode; this
4131is supposed to make it easier to insert characters when necessary."
4132 (interactive "P")
4133 (setq overwrite-mode
4134 (if (if (null arg) (not overwrite-mode)
4135 (> (prefix-numeric-value arg) 0))
4136 'overwrite-mode-textual))
4137 (force-mode-line-update))
4138
4139(defun binary-overwrite-mode (arg)
4140 "Toggle binary overwrite mode.
4141With arg, turn binary overwrite mode on iff arg is positive.
4142In binary overwrite mode, printing characters typed in replace
4143existing text. Newlines are not treated specially, so typing at the
4144end of a line joins the line to the next, with the typed character
4145between them. Typing before a tab character simply replaces the tab
4146with the character typed.
4147\\[quoted-insert] replaces the text at the cursor, just as ordinary
4148typing characters do.
4149
4150Note that binary overwrite mode is not its own minor mode; it is a
4151specialization of overwrite-mode, entered by setting the
4152`overwrite-mode' variable to `overwrite-mode-binary'."
2076c87c
JB
4153 (interactive "P")
4154 (setq overwrite-mode
b6a22db0 4155 (if (if (null arg)
a61099dd 4156 (not (eq overwrite-mode 'overwrite-mode-binary))
b6a22db0
JB
4157 (> (prefix-numeric-value arg) 0))
4158 'overwrite-mode-binary))
4159 (force-mode-line-update))
eaae8106 4160
6710df48 4161(define-minor-mode line-number-mode
a61099dd
RS
4162 "Toggle Line Number mode.
4163With arg, turn Line Number mode on iff arg is positive.
4164When Line Number mode is enabled, the line number appears
8dc9e2ef
KH
4165in the mode line.
4166
32f2f98e
EZ
4167Line numbers do not appear for very large buffers and buffers
4168with very long lines; see variables `line-number-display-limit'
4169and `line-number-display-limit-width'."
82dc968c 4170 :init-value t :global t :group 'editing-basics :require nil)
bcad4985 4171
6710df48 4172(define-minor-mode column-number-mode
bcad4985
KH
4173 "Toggle Column Number mode.
4174With arg, turn Column Number mode on iff arg is positive.
4175When Column Number mode is enabled, the column number appears
4176in the mode line."
82dc968c 4177 :global t :group 'editing-basics :require nil)
cf045f9a
LK
4178
4179(define-minor-mode size-indication-mode
4180 "Toggle Size Indication mode.
4181With arg, turn Size Indication mode on iff arg is positive. When
4182Size Indication mode is enabled, the size of the accessible part
4183of the buffer appears in the mode line."
4184 :global t :group 'editing-basics :require nil)
2d88b556 4185\f
4b384a8f 4186(defgroup paren-blinking nil
020db25f 4187 "Blinking matching of parens and expressions."
4b384a8f
SM
4188 :prefix "blink-matching-"
4189 :group 'paren-matching)
4190
69c1dd37
RS
4191(defcustom blink-matching-paren t
4192 "*Non-nil means show matching open-paren when close-paren is inserted."
4193 :type 'boolean
4b384a8f 4194 :group 'paren-blinking)
2076c87c 4195
69c1dd37 4196(defcustom blink-matching-paren-on-screen t
29fc44dd 4197 "*Non-nil means show matching open-paren when it is on screen.
4b384a8f
SM
4198If nil, means don't show it (but the open-paren can still be shown
4199when it is off screen)."
69c1dd37 4200 :type 'boolean
4b384a8f 4201 :group 'paren-blinking)
29fc44dd 4202
4b384a8f 4203(defcustom blink-matching-paren-distance (* 25 1024)
69c1dd37
RS
4204 "*If non-nil, is maximum distance to search for matching open-paren."
4205 :type 'integer
4b384a8f 4206 :group 'paren-blinking)
2076c87c 4207
69c1dd37 4208(defcustom blink-matching-delay 1
4b384a8f
SM
4209 "*Time in seconds to delay after showing a matching paren."
4210 :type 'number
4211 :group 'paren-blinking)
72dddf8b 4212
69c1dd37 4213(defcustom blink-matching-paren-dont-ignore-comments nil
4b384a8f 4214 "*Non-nil means `blink-matching-paren' will not ignore comments."
69c1dd37 4215 :type 'boolean
4b384a8f 4216 :group 'paren-blinking)
903b7f65 4217
2076c87c
JB
4218(defun blink-matching-open ()
4219 "Move cursor momentarily to the beginning of the sexp before point."
4220 (interactive)
4221 (and (> (point) (1+ (point-min)))
2076c87c 4222 blink-matching-paren
7e1ddd45
RS
4223 ;; Verify an even number of quoting characters precede the close.
4224 (= 1 (logand 1 (- (point)
4225 (save-excursion
4226 (forward-char -1)
4227 (skip-syntax-backward "/\\")
4228 (point)))))
2076c87c
JB
4229 (let* ((oldpos (point))
4230 (blinkpos)
01ce617a
RS
4231 (mismatch)
4232 matching-paren)
2076c87c
JB
4233 (save-excursion
4234 (save-restriction
4235 (if blink-matching-paren-distance
4236 (narrow-to-region (max (point-min)
4237 (- (point) blink-matching-paren-distance))
4238 oldpos))
4239 (condition-case ()
903b7f65
RS
4240 (let ((parse-sexp-ignore-comments
4241 (and parse-sexp-ignore-comments
4242 (not blink-matching-paren-dont-ignore-comments))))
4243 (setq blinkpos (scan-sexps oldpos -1)))
2076c87c 4244 (error nil)))
903b7f65 4245 (and blinkpos
ac43807d
SM
4246 ;; Not syntax '$'.
4247 (not (eq (syntax-class (syntax-after blinkpos)) 8))
01ce617a 4248 (setq matching-paren
c6db81aa
SM
4249 (let ((syntax (syntax-after blinkpos)))
4250 (and (consp syntax)
98580e20 4251 (eq (syntax-class syntax) 4)
c6db81aa 4252 (cdr syntax)))
01ce617a
RS
4253 mismatch
4254 (or (null matching-paren)
903b7f65 4255 (/= (char-after (1- oldpos))
01ce617a 4256 matching-paren))))
2076c87c
JB
4257 (if mismatch (setq blinkpos nil))
4258 (if blinkpos
a117eaee
KH
4259 ;; Don't log messages about paren matching.
4260 (let (message-log-max)
2076c87c
JB
4261 (goto-char blinkpos)
4262 (if (pos-visible-in-window-p)
29fc44dd
KH
4263 (and blink-matching-paren-on-screen
4264 (sit-for blink-matching-delay))
2076c87c
JB
4265 (goto-char blinkpos)
4266 (message
4267 "Matches %s"
e9f1d66d 4268 ;; Show what precedes the open in its line, if anything.
2076c87c
JB
4269 (if (save-excursion
4270 (skip-chars-backward " \t")
4271 (not (bolp)))
4272 (buffer-substring (progn (beginning-of-line) (point))
4273 (1+ blinkpos))
e9f1d66d
RS
4274 ;; Show what follows the open in its line, if anything.
4275 (if (save-excursion
4276 (forward-char 1)
4277 (skip-chars-forward " \t")
4278 (not (eolp)))
4279 (buffer-substring blinkpos
4280 (progn (end-of-line) (point)))
267935b9
RS
4281 ;; Otherwise show the previous nonblank line,
4282 ;; if there is one.
4283 (if (save-excursion
4284 (skip-chars-backward "\n \t")
4285 (not (bobp)))
4286 (concat
4287 (buffer-substring (progn
4288 (skip-chars-backward "\n \t")
4289 (beginning-of-line)
4290 (point))
4291 (progn (end-of-line)
4292 (skip-chars-backward " \t")
4293 (point)))
4294 ;; Replace the newline and other whitespace with `...'.
4295 "..."
4296 (buffer-substring blinkpos (1+ blinkpos)))
4297 ;; There is nothing to show except the char itself.
4298 (buffer-substring blinkpos (1+ blinkpos))))))))
2076c87c
JB
4299 (cond (mismatch
4300 (message "Mismatched parentheses"))
4301 ((not blink-matching-paren-distance)
4302 (message "Unmatched parenthesis"))))))))
4303
4304;Turned off because it makes dbx bomb out.
4305(setq blink-paren-function 'blink-matching-open)
2d88b556 4306\f
9a1277dd
RS
4307;; This executes C-g typed while Emacs is waiting for a command.
4308;; Quitting out of a program does not go through here;
4309;; that happens in the QUIT macro at the C code level.
2076c87c 4310(defun keyboard-quit ()
d5dae4e1 4311 "Signal a `quit' condition.
af39530e
RS
4312During execution of Lisp code, this character causes a quit directly.
4313At top-level, as an editor command, this simply beeps."
2076c87c 4314 (interactive)
19d35374 4315 (deactivate-mark)
8a7644e9
KS
4316 (if (fboundp 'kmacro-keyboard-quit)
4317 (kmacro-keyboard-quit))
f5e13057 4318 (setq defining-kbd-macro nil)
2076c87c
JB
4319 (signal 'quit nil))
4320
1c6c6fde
RS
4321(defvar buffer-quit-function nil
4322 "Function to call to \"quit\" the current buffer, or nil if none.
4323\\[keyboard-escape-quit] calls this function when its more local actions
4324\(such as cancelling a prefix argument, minibuffer or region) do not apply.")
4325
c66587fe
RS
4326(defun keyboard-escape-quit ()
4327 "Exit the current \"mode\" (in a generalized sense of the word).
4328This command can exit an interactive command such as `query-replace',
4329can clear out a prefix argument or a region,
4330can get out of the minibuffer or other recursive edit,
1c6c6fde
RS
4331cancel the use of the current buffer (for special-purpose buffers),
4332or go back to just one window (by deleting all but the selected window)."
c66587fe
RS
4333 (interactive)
4334 (cond ((eq last-command 'mode-exited) nil)
4335 ((> (minibuffer-depth) 0)
4336 (abort-recursive-edit))
4337 (current-prefix-arg
4338 nil)
705a5933 4339 ((and transient-mark-mode mark-active)
c66587fe 4340 (deactivate-mark))
1b657835
RS
4341 ((> (recursion-depth) 0)
4342 (exit-recursive-edit))
1c6c6fde
RS
4343 (buffer-quit-function
4344 (funcall buffer-quit-function))
c66587fe 4345 ((not (one-window-p t))
1b657835
RS
4346 (delete-other-windows))
4347 ((string-match "^ \\*" (buffer-name (current-buffer)))
4348 (bury-buffer))))
c66587fe 4349
2d88b556
RS
4350(defun play-sound-file (file &optional volume device)
4351 "Play sound stored in FILE.
4352VOLUME and DEVICE correspond to the keywords of the sound
4353specification for `play-sound'."
4354 (interactive "fPlay sound file: ")
4355 (let ((sound (list :file file)))
4356 (if volume
4357 (plist-put sound :volume volume))
4358 (if device
4359 (plist-put sound :device device))
4360 (push 'sound sound)
4361 (play-sound sound)))
4362
56abefac 4363\f
7683b5c2
DL
4364(defcustom read-mail-command 'rmail
4365 "*Your preference for a mail reading package.
9023837e
DL
4366This is used by some keybindings which support reading mail.
4367See also `mail-user-agent' concerning sending mail."
7683b5c2
DL
4368 :type '(choice (function-item rmail)
4369 (function-item gnus)
4370 (function-item mh-rmail)
4371 (function :tag "Other"))
4372 :version "21.1"
4373 :group 'mail)
4374
69c1dd37 4375(defcustom mail-user-agent 'sendmail-user-agent
a31ca314 4376 "*Your preference for a mail composition package.
9023837e 4377Various Emacs Lisp packages (e.g. Reporter) require you to compose an
a31ca314
RS
4378outgoing email message. This variable lets you specify which
4379mail-sending package you prefer.
4380
4381Valid values include:
4382
9023837e
DL
4383 `sendmail-user-agent' -- use the default Emacs Mail package.
4384 See Info node `(emacs)Sending Mail'.
4385 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
4386 See Info node `(mh-e)'.
4387 `message-user-agent' -- use the Gnus Message package.
4388 See Info node `(message)'.
4389 `gnus-user-agent' -- like `message-user-agent', but with Gnus
4390 paraphernalia, particularly the Gcc: header for
4391 archiving.
a31ca314
RS
4392
4393Additional valid symbols may be available; check with the author of
15d0c9b1
DL
4394your package for details. The function should return non-nil if it
4395succeeds.
9023837e
DL
4396
4397See also `read-mail-command' concerning reading mail."
69c1dd37
RS
4398 :type '(radio (function-item :tag "Default Emacs mail"
4399 :format "%t\n"
4400 sendmail-user-agent)
4401 (function-item :tag "Emacs interface to MH"
4402 :format "%t\n"
4403 mh-e-user-agent)
9023837e 4404 (function-item :tag "Gnus Message package"
69c1dd37
RS
4405 :format "%t\n"
4406 message-user-agent)
9023837e
DL
4407 (function-item :tag "Gnus Message with full Gnus features"
4408 :format "%t\n"
4409 gnus-user-agent)
69c1dd37
RS
4410 (function :tag "Other"))
4411 :group 'mail)
a31ca314 4412
a31ca314 4413(define-mail-user-agent 'sendmail-user-agent
34fbcdf3 4414 'sendmail-user-agent-compose
a31ca314
RS
4415 'mail-send-and-exit)
4416
360b5483
RS
4417(defun rfc822-goto-eoh ()
4418 ;; Go to header delimiter line in a mail message, following RFC822 rules
4419 (goto-char (point-min))
e1e04350
SM
4420 (when (re-search-forward
4421 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
4422 (goto-char (match-beginning 0))))
360b5483 4423
34fbcdf3
RS
4424(defun sendmail-user-agent-compose (&optional to subject other-headers continue
4425 switch-function yank-action
4426 send-actions)
4427 (if switch-function
4428 (let ((special-display-buffer-names nil)
4429 (special-display-regexps nil)
4430 (same-window-buffer-names nil)
4431 (same-window-regexps nil))
4432 (funcall switch-function "*mail*")))
9462bf2c
RS
4433 (let ((cc (cdr (assoc-string "cc" other-headers t)))
4434 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
4435 (body (cdr (assoc-string "body" other-headers t))))
34fbcdf3
RS
4436 (or (mail continue to subject in-reply-to cc yank-action send-actions)
4437 continue
4438 (error "Message aborted"))
4439 (save-excursion
360b5483 4440 (rfc822-goto-eoh)
34fbcdf3 4441 (while other-headers
0740c738
GM
4442 (unless (member-ignore-case (car (car other-headers))
4443 '("in-reply-to" "cc" "body"))
34fbcdf3
RS
4444 (insert (car (car other-headers)) ": "
4445 (cdr (car other-headers)) "\n"))
4446 (setq other-headers (cdr other-headers)))
0740c738
GM
4447 (when body
4448 (forward-line 1)
4449 (insert body))
34fbcdf3
RS
4450 t)))
4451
a31ca314
RS
4452(define-mail-user-agent 'mh-e-user-agent
4453 'mh-smail-batch 'mh-send-letter 'mh-fully-kill-draft
4454 'mh-before-send-letter-hook)
d0008a00
RS
4455
4456(defun compose-mail (&optional to subject other-headers continue
4457 switch-function yank-action send-actions)
4458 "Start composing a mail message to send.
4459This uses the user's chosen mail composition package
4460as selected with the variable `mail-user-agent'.
4461The optional arguments TO and SUBJECT specify recipients
4462and the initial Subject field, respectively.
4463
4464OTHER-HEADERS is an alist specifying additional
4465header fields. Elements look like (HEADER . VALUE) where both
4466HEADER and VALUE are strings.
4467
4468CONTINUE, if non-nil, says to continue editing a message already
4469being composed.
4470
4471SWITCH-FUNCTION, if non-nil, is a function to use to
4472switch to and display the buffer used for mail composition.
4473
4474YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
06720de2
RS
4475to insert the raw text of the message being replied to.
4476It has the form (FUNCTION . ARGS). The user agent will apply
4477FUNCTION to ARGS, to insert the raw text of the original message.
4478\(The user agent will also run `mail-citation-hook', *after* the
4479original text has been inserted in this way.)
d0008a00
RS
4480
4481SEND-ACTIONS is a list of actions to call when the message is sent.
4482Each action has the form (FUNCTION . ARGS)."
b5f019be
RS
4483 (interactive
4484 (list nil nil nil current-prefix-arg))
d0008a00
RS
4485 (let ((function (get mail-user-agent 'composefunc)))
4486 (funcall function to subject other-headers continue
4487 switch-function yank-action send-actions)))
b5f019be
RS
4488
4489(defun compose-mail-other-window (&optional to subject other-headers continue
4490 yank-action send-actions)
4491 "Like \\[compose-mail], but edit the outgoing message in another window."
4492 (interactive
4493 (list nil nil nil current-prefix-arg))
4494 (compose-mail to subject other-headers continue
4495 'switch-to-buffer-other-window yank-action send-actions))
4496
4497
4498(defun compose-mail-other-frame (&optional to subject other-headers continue
4499 yank-action send-actions)
4500 "Like \\[compose-mail], but edit the outgoing message in another frame."
4501 (interactive
4502 (list nil nil nil current-prefix-arg))
4503 (compose-mail to subject other-headers continue
4504 'switch-to-buffer-other-frame yank-action send-actions))
56abefac 4505\f
610c1c68
RS
4506(defvar set-variable-value-history nil
4507 "History of values entered with `set-variable'.")
4508
16236388 4509(defun set-variable (var val &optional make-local)
610c1c68
RS
4510 "Set VARIABLE to VALUE. VALUE is a Lisp object.
4511When using this interactively, enter a Lisp object for VALUE.
4512If you want VALUE to be a string, you must surround it with doublequotes.
4513VALUE is used literally, not evaluated.
4514
4515If VARIABLE has a `variable-interactive' property, that is used as if
4516it were the arg to `interactive' (which see) to interactively read VALUE.
4517
4518If VARIABLE has been defined with `defcustom', then the type information
16236388
RS
4519in the definition is used to check that VALUE is valid.
4520
4521With a prefix argument, set VARIABLE to VALUE buffer-locally."
e9dfb72e
RS
4522 (interactive
4523 (let* ((default-var (variable-at-point))
4524 (var (if (symbolp default-var)
4525 (read-variable (format "Set variable (default %s): " default-var)
4526 default-var)
4527 (read-variable "Set variable: ")))
7dcd2d16
AS
4528 (minibuffer-help-form '(describe-variable var))
4529 (prop (get var 'variable-interactive))
4530 (prompt (format "Set %s%s to value: " var
4531 (cond ((local-variable-p var)
4532 " (buffer-local)")
4533 ((or current-prefix-arg
4534 (local-variable-if-set-p var))
4535 " buffer-locally")
4536 (t " globally"))))
4537 (val (if prop
4538 ;; Use VAR's `variable-interactive' property
4539 ;; as an interactive spec for prompting.
4540 (call-interactively `(lambda (arg)
4541 (interactive ,prop)
4542 arg))
4543 (read
4544 (read-string prompt nil
4545 'set-variable-value-history)))))
4546 (list var val current-prefix-arg)))
610c1c68 4547
90b4a157
MR
4548 (and (custom-variable-p var)
4549 (not (get var 'custom-type))
4550 (custom-load-symbol var))
f8496faa 4551 (let ((type (get var 'custom-type)))
610c1c68
RS
4552 (when type
4553 ;; Match with custom type.
36755dd9 4554 (require 'cus-edit)
610c1c68
RS
4555 (setq type (widget-convert type))
4556 (unless (widget-apply type :match val)
1e722f9f 4557 (error "Value `%S' does not match type %S of %S"
610c1c68 4558 val (car type) var))))
16236388
RS
4559
4560 (if make-local
4561 (make-local-variable var))
f1180544 4562
a2aef080
GM
4563 (set var val)
4564
4565 ;; Force a thorough redisplay for the case that the variable
4566 ;; has an effect on the display, like `tab-width' has.
4567 (force-mode-line-update))
56abefac 4568\f
e8a700bf
RS
4569;; Define the major mode for lists of completions.
4570
98b45886
RS
4571(defvar completion-list-mode-map nil
4572 "Local map for completion list buffers.")
ac29eb79 4573(or completion-list-mode-map
e8a700bf
RS
4574 (let ((map (make-sparse-keymap)))
4575 (define-key map [mouse-2] 'mouse-choose-completion)
771069f8 4576 (define-key map [follow-link] 'mouse-face)
eaf76065 4577 (define-key map [down-mouse-2] nil)
80298193 4578 (define-key map "\C-m" 'choose-completion)
1c6c6fde 4579 (define-key map "\e\e\e" 'delete-completion-window)
dde69dbe
RS
4580 (define-key map [left] 'previous-completion)
4581 (define-key map [right] 'next-completion)
ac29eb79 4582 (setq completion-list-mode-map map)))
e8a700bf
RS
4583
4584;; Completion mode is suitable only for specially formatted data.
ac29eb79 4585(put 'completion-list-mode 'mode-class 'special)
e8a700bf 4586
98b45886
RS
4587(defvar completion-reference-buffer nil
4588 "Record the buffer that was current when the completion list was requested.
4589This is a local variable in the completion list buffer.
ec39964e 4590Initial value is nil to avoid some compiler warnings.")
3819736b 4591
83434bda
RS
4592(defvar completion-no-auto-exit nil
4593 "Non-nil means `choose-completion-string' should never exit the minibuffer.
4594This also applies to other functions such as `choose-completion'
4595and `mouse-choose-completion'.")
4596
98b45886
RS
4597(defvar completion-base-size nil
4598 "Number of chars at beginning of minibuffer not involved in completion.
4599This is a local variable in the completion list buffer
4600but it talks about the buffer in `completion-reference-buffer'.
4601If this is nil, it means to compare text to determine which part
4602of the tail end of the buffer's text is involved in completion.")
f6b293e3 4603
1c6c6fde
RS
4604(defun delete-completion-window ()
4605 "Delete the completion list window.
4606Go to the window from which completion was requested."
4607 (interactive)
4608 (let ((buf completion-reference-buffer))
ddb2b181
RS
4609 (if (one-window-p t)
4610 (if (window-dedicated-p (selected-window))
4611 (delete-frame (selected-frame)))
4612 (delete-window (selected-window))
4613 (if (get-buffer-window buf)
4614 (select-window (get-buffer-window buf))))))
1c6c6fde 4615
dde69dbe
RS
4616(defun previous-completion (n)
4617 "Move to the previous item in the completion list."
4618 (interactive "p")
4619 (next-completion (- n)))
4620
4621(defun next-completion (n)
4622 "Move to the next item in the completion list.
1f238ac2 4623With prefix argument N, move N items (negative N means move backward)."
dde69dbe 4624 (interactive "p")
58dd38f1
SM
4625 (let ((beg (point-min)) (end (point-max)))
4626 (while (and (> n 0) (not (eobp)))
dde69dbe 4627 ;; If in a completion, move to the end of it.
58dd38f1
SM
4628 (when (get-text-property (point) 'mouse-face)
4629 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
dde69dbe 4630 ;; Move to start of next one.
58dd38f1
SM
4631 (unless (get-text-property (point) 'mouse-face)
4632 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4633 (setq n (1- n)))
4634 (while (and (< n 0) (not (bobp)))
4635 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
4636 ;; If in a completion, move to the start of it.
4637 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
b61a81c2 4638 (goto-char (previous-single-property-change
58dd38f1
SM
4639 (point) 'mouse-face nil beg)))
4640 ;; Move to end of the previous completion.
4641 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
4642 (goto-char (previous-single-property-change
4643 (point) 'mouse-face nil beg)))
4644 ;; Move to the start of that one.
4645 (goto-char (previous-single-property-change
4646 (point) 'mouse-face nil beg))
4647 (setq n (1+ n))))))
dde69dbe 4648
80298193
RS
4649(defun choose-completion ()
4650 "Choose the completion that point is in or next to."
4651 (interactive)
f6b293e3
RS
4652 (let (beg end completion (buffer completion-reference-buffer)
4653 (base-size completion-base-size))
6096f362
RS
4654 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
4655 (setq end (point) beg (1+ (point))))
4656 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
3f299281 4657 (setq end (1- (point)) beg (point)))
6096f362
RS
4658 (if (null beg)
4659 (error "No completion here"))
4660 (setq beg (previous-single-property-change beg 'mouse-face))
88dd3c24 4661 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
ab63960f
RS
4662 (setq completion (buffer-substring beg end))
4663 (let ((owindow (selected-window)))
4664 (if (and (one-window-p t 'selected-frame)
4665 (window-dedicated-p (selected-window)))
4666 ;; This is a special buffer's frame
4667 (iconify-frame (selected-frame))
4668 (or (window-dedicated-p (selected-window))
4669 (bury-buffer)))
4670 (select-window owindow))
f6b293e3 4671 (choose-completion-string completion buffer base-size)))
80298193
RS
4672
4673;; Delete the longest partial match for STRING
4674;; that can be found before POINT.
4675(defun choose-completion-delete-max-match (string)
4676 (let ((opoint (point))
f0bfada7
RS
4677 len)
4678 ;; Try moving back by the length of the string.
4679 (goto-char (max (- (point) (length string))
4680 (minibuffer-prompt-end)))
4681 ;; See how far back we were actually able to move. That is the
4682 ;; upper bound on how much we can match and delete.
4683 (setq len (- opoint (point)))
61bbf6fe
RS
4684 (if completion-ignore-case
4685 (setq string (downcase string)))
80298193 4686 (while (and (> len 0)
f0bfada7 4687 (let ((tail (buffer-substring (point) opoint)))
61bbf6fe
RS
4688 (if completion-ignore-case
4689 (setq tail (downcase tail)))
80298193
RS
4690 (not (string= tail (substring string 0 len)))))
4691 (setq len (1- len))
4692 (forward-char 1))
4693 (delete-char len)))
4694
ba36181b 4695(defvar choose-completion-string-functions nil
bbbbb15b
KS
4696 "Functions that may override the normal insertion of a completion choice.
4697These functions are called in order with four arguments:
4698CHOICE - the string to insert in the buffer,
4699BUFFER - the buffer in which the choice should be inserted,
89a6cfe3 4700MINI-P - non-nil iff BUFFER is a minibuffer, and
12829a07
RS
4701BASE-SIZE - the number of characters in BUFFER before
4702the string being completed.
4703
bbbbb15b
KS
4704If a function in the list returns non-nil, that function is supposed
4705to have inserted the CHOICE in the BUFFER, and possibly exited
12829a07 4706the minibuffer; no further functions will be called.
ba36181b 4707
12829a07
RS
4708If all functions in the list return nil, that means to use
4709the default method of inserting the completion in BUFFER.")
74d0290b 4710
f6b293e3 4711(defun choose-completion-string (choice &optional buffer base-size)
12829a07
RS
4712 "Switch to BUFFER and insert the completion choice CHOICE.
4713BASE-SIZE, if non-nil, says how many characters of BUFFER's text
e36aeef9
RS
4714to keep. If it is nil, we call `choose-completion-delete-max-match'
4715to decide what to delete."
12829a07
RS
4716
4717 ;; If BUFFER is the minibuffer, exit the minibuffer
4718 ;; unless it is reading a file name and CHOICE is a directory,
4719 ;; or completion-no-auto-exit is non-nil.
4720
1a0d0b6a
JPW
4721 (let* ((buffer (or buffer completion-reference-buffer))
4722 (mini-p (minibufferp buffer)))
cf52ad58
RS
4723 ;; If BUFFER is a minibuffer, barf unless it's the currently
4724 ;; active minibuffer.
f436a90a 4725 (if (and mini-p
45486731
RS
4726 (or (not (active-minibuffer-window))
4727 (not (equal buffer
4728 (window-buffer (active-minibuffer-window))))))
cf52ad58 4729 (error "Minibuffer is not active for completion")
17aa3385
KS
4730 ;; Set buffer so buffer-local choose-completion-string-functions works.
4731 (set-buffer buffer)
f1180544 4732 (unless (run-hook-with-args-until-success
d99f8496
SM
4733 'choose-completion-string-functions
4734 choice buffer mini-p base-size)
4735 ;; Insert the completion into the buffer where it was requested.
bbbbb15b
KS
4736 (if base-size
4737 (delete-region (+ base-size (if mini-p
4738 (minibuffer-prompt-end)
4739 (point-min)))
4740 (point))
4741 (choose-completion-delete-max-match choice))
4742 (insert choice)
4743 (remove-text-properties (- (point) (length choice)) (point)
4744 '(mouse-face nil))
4745 ;; Update point in the window that BUFFER is showing in.
4746 (let ((window (get-buffer-window buffer t)))
4747 (set-window-point window (point)))
4748 ;; If completing for the minibuffer, exit it with this choice.
4749 (and (not completion-no-auto-exit)
4750 (equal buffer (window-buffer (minibuffer-window)))
4751 minibuffer-completion-table
4752 ;; If this is reading a file name, and the file name chosen
4753 ;; is a directory, don't exit the minibuffer.
4754 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
4755 (file-directory-p (field-string (point-max))))
4756 (let ((mini (active-minibuffer-window)))
4757 (select-window mini)
4758 (when minibuffer-auto-raise
4759 (raise-frame (window-frame mini))))
4760 (exit-minibuffer)))))))
80298193 4761
ac29eb79 4762(defun completion-list-mode ()
e8a700bf 4763 "Major mode for buffers showing lists of possible completions.
80298193
RS
4764Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
4765 to select the completion near point.
4766Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
4767 with the mouse."
e8a700bf
RS
4768 (interactive)
4769 (kill-all-local-variables)
ac29eb79
RS
4770 (use-local-map completion-list-mode-map)
4771 (setq mode-name "Completion List")
4772 (setq major-mode 'completion-list-mode)
f6b293e3
RS
4773 (make-local-variable 'completion-base-size)
4774 (setq completion-base-size nil)
b2777913 4775 (run-mode-hooks 'completion-list-mode-hook))
e8a700bf 4776
c8d6d636
GM
4777(defun completion-list-mode-finish ()
4778 "Finish setup of the completions buffer.
4779Called from `temp-buffer-show-hook'."
4780 (when (eq major-mode 'completion-list-mode)
4781 (toggle-read-only 1)))
4782
4783(add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
4784
747a0e2f
RS
4785(defvar completion-setup-hook nil
4786 "Normal hook run at the end of setting up a completion list buffer.
4787When this hook is run, the current buffer is the one in which the
4788command to display the completion list buffer was run.
4789The completion list buffer is available as the value of `standard-output'.")
4790
98b45886
RS
4791;; This function goes in completion-setup-hook, so that it is called
4792;; after the text of the completion list buffer is written.
6a4940b2 4793(defface completions-first-difference
abcdd45a
MY
4794 '((t (:inherit bold)))
4795 "Face put on the first uncommon character in completions in *Completions* buffer."
4796 :group 'completion)
4797
6a4940b2 4798(defface completions-common-part
abcdd45a 4799 '((t (:inherit default)))
e4ef3e92
JL
4800 "Face put on the common prefix substring in completions in *Completions* buffer.
4801The idea of `completions-common-part' is that you can use it to
4802make the common parts less visible than normal, so that the rest
4803of the differing parts is, by contrast, slightly highlighted."
abcdd45a 4804 :group 'completion)
6096f362 4805
abaf2e77
EZ
4806;; This is for packages that need to bind it to a non-default regexp
4807;; in order to make the first-differing character highlight work
4808;; to their liking
4809(defvar completion-root-regexp "^/"
4810 "Regexp to use in `completion-setup-function' to find the root directory.")
4811
e8a700bf 4812(defun completion-setup-function ()
621a3f62
SM
4813 (let ((mainbuf (current-buffer))
4814 (mbuf-contents (minibuffer-contents)))
4815 ;; When reading a file name in the minibuffer,
4816 ;; set default-directory in the minibuffer
4817 ;; so it will get copied into the completion list buffer.
4818 (if minibuffer-completing-file-name
4819 (with-current-buffer mainbuf
4820 (setq default-directory (file-name-directory mbuf-contents))))
55c4a67c
EZ
4821 ;; If partial-completion-mode is on, point might not be after the
4822 ;; last character in the minibuffer.
4823 ;; FIXME: This still doesn't work if the text to be completed
4824 ;; starts with a `-'.
4825 (when (and partial-completion-mode (not (eobp)))
4826 (setq mbuf-contents
4827 (substring mbuf-contents 0 (- (point) (point-max)))))
621a3f62 4828 (with-current-buffer standard-output
3819736b
RS
4829 (completion-list-mode)
4830 (make-local-variable 'completion-reference-buffer)
4831 (setq completion-reference-buffer mainbuf)
2d64b6f6 4832 (if minibuffer-completing-file-name
50be475d
RS
4833 ;; For file name completion,
4834 ;; use the number of chars before the start of the
4835 ;; last file name component.
4836 (setq completion-base-size
621a3f62
SM
4837 (with-current-buffer mainbuf
4838 (save-excursion
4839 (goto-char (point-max))
abaf2e77 4840 (skip-chars-backward completion-root-regexp)
621a3f62 4841 (- (point) (minibuffer-prompt-end)))))
19183a29 4842 ;; Otherwise, in minibuffer, the whole input is being completed.
621a3f62 4843 (if (minibufferp mainbuf)
77da2107
RS
4844 (if (and (symbolp minibuffer-completion-table)
4845 (get minibuffer-completion-table 'completion-base-size-function))
52167727 4846 (setq completion-base-size
77da2107
RS
4847 (funcall (get minibuffer-completion-table 'completion-base-size-function)))
4848 (setq completion-base-size 0))))
621a3f62 4849 ;; Put faces on first uncommon characters and common parts.
abcdd45a 4850 (when completion-base-size
621a3f62
SM
4851 (let* ((common-string-length
4852 (- (length mbuf-contents) completion-base-size))
9a1120ea
MY
4853 (element-start (next-single-property-change
4854 (point-min)
4855 'mouse-face))
621a3f62 4856 (element-common-end
9bb25ed3
RS
4857 (and element-start
4858 (+ (or element-start nil) common-string-length)))
9a1120ea
MY
4859 (maxp (point-max)))
4860 (while (and element-start (< element-common-end maxp))
abcdd45a
MY
4861 (when (and (get-char-property element-start 'mouse-face)
4862 (get-char-property element-common-end 'mouse-face))
4863 (put-text-property element-start element-common-end
6a4940b2 4864 'font-lock-face 'completions-common-part)
abcdd45a 4865 (put-text-property element-common-end (1+ element-common-end)
6a4940b2 4866 'font-lock-face 'completions-first-difference))
9a1120ea 4867 (setq element-start (next-single-property-change
abcdd45a 4868 element-start
9a1120ea
MY
4869 'mouse-face))
4870 (if element-start
4871 (setq element-common-end (+ element-start common-string-length))))))
abcdd45a 4872 ;; Insert help string.
3819736b 4873 (goto-char (point-min))
0d6e23cf 4874 (if (display-mouse-p)
3819736b 4875 (insert (substitute-command-keys
80298193
RS
4876 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
4877 (insert (substitute-command-keys
4878 "In this buffer, type \\[choose-completion] to \
7d22ed15 4879select the completion near point.\n\n")))))
c88ab9ce 4880
e8a700bf 4881(add-hook 'completion-setup-hook 'completion-setup-function)
dde69dbe
RS
4882
4883(define-key minibuffer-local-completion-map [prior]
4884 'switch-to-completions)
4885(define-key minibuffer-local-must-match-map [prior]
4886 'switch-to-completions)
4887(define-key minibuffer-local-completion-map "\M-v"
4888 'switch-to-completions)
4889(define-key minibuffer-local-must-match-map "\M-v"
4890 'switch-to-completions)
4891
4892(defun switch-to-completions ()
4893 "Select the completion list window."
4894 (interactive)
9595fbdb
RS
4895 ;; Make sure we have a completions window.
4896 (or (get-buffer-window "*Completions*")
4897 (minibuffer-completion-help))
fdbd7c4d
KH
4898 (let ((window (get-buffer-window "*Completions*")))
4899 (when window
4900 (select-window window)
4901 (goto-char (point-min))
4902 (search-forward "\n\n")
4903 (forward-line 1))))
eaae8106 4904
82072f33
RS
4905;; Support keyboard commands to turn on various modifiers.
4906
4907;; These functions -- which are not commands -- each add one modifier
4908;; to the following event.
4909
4910(defun event-apply-alt-modifier (ignore-prompt)
1e96c007 4911 "\\<function-key-map>Add the Alt modifier to the following event.
70cf9f08 4912For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
82072f33
RS
4913 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
4914(defun event-apply-super-modifier (ignore-prompt)
1e96c007 4915 "\\<function-key-map>Add the Super modifier to the following event.
70cf9f08 4916For example, type \\[event-apply-super-modifier] & to enter Super-&."
82072f33
RS
4917 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
4918(defun event-apply-hyper-modifier (ignore-prompt)
1e96c007 4919 "\\<function-key-map>Add the Hyper modifier to the following event.
70cf9f08 4920For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
82072f33
RS
4921 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
4922(defun event-apply-shift-modifier (ignore-prompt)
1e96c007 4923 "\\<function-key-map>Add the Shift modifier to the following event.
70cf9f08 4924For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
82072f33
RS
4925 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
4926(defun event-apply-control-modifier (ignore-prompt)
1e96c007 4927 "\\<function-key-map>Add the Ctrl modifier to the following event.
70cf9f08 4928For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
82072f33
RS
4929 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
4930(defun event-apply-meta-modifier (ignore-prompt)
1e96c007 4931 "\\<function-key-map>Add the Meta modifier to the following event.
70cf9f08 4932For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
82072f33
RS
4933 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
4934
4935(defun event-apply-modifier (event symbol lshiftby prefix)
4936 "Apply a modifier flag to event EVENT.
4937SYMBOL is the name of this modifier, as a symbol.
4938LSHIFTBY is the numeric value of this modifier, in keyboard events.
4939PREFIX is the string that represents this modifier in an event type symbol."
4940 (if (numberp event)
4941 (cond ((eq symbol 'control)
90bebcb0
KH
4942 (if (and (<= (downcase event) ?z)
4943 (>= (downcase event) ?a))
82072f33 4944 (- (downcase event) ?a -1)
90bebcb0
KH
4945 (if (and (<= (downcase event) ?Z)
4946 (>= (downcase event) ?A))
82072f33
RS
4947 (- (downcase event) ?A -1)
4948 (logior (lsh 1 lshiftby) event))))
4949 ((eq symbol 'shift)
4950 (if (and (<= (downcase event) ?z)
4951 (>= (downcase event) ?a))
4952 (upcase event)
4953 (logior (lsh 1 lshiftby) event)))
4954 (t
4955 (logior (lsh 1 lshiftby) event)))
4956 (if (memq symbol (event-modifiers event))
4957 event
4958 (let ((event-type (if (symbolp event) event (car event))))
4959 (setq event-type (intern (concat prefix (symbol-name event-type))))
4960 (if (symbolp event)
4961 event-type
4962 (cons event-type (cdr event)))))))
4963
e5fff738
KH
4964(define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
4965(define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
4966(define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
4967(define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
4968(define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
4969(define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
eaae8106 4970
a3d1480b
JB
4971;;;; Keypad support.
4972
4973;;; Make the keypad keys act like ordinary typing keys. If people add
4974;;; bindings for the function key symbols, then those bindings will
4975;;; override these, so this shouldn't interfere with any existing
4976;;; bindings.
4977
0d173134 4978;; Also tell read-char how to handle these keys.
e1e04350 4979(mapc
a3d1480b
JB
4980 (lambda (keypad-normal)
4981 (let ((keypad (nth 0 keypad-normal))
4982 (normal (nth 1 keypad-normal)))
0d173134 4983 (put keypad 'ascii-character normal)
a3d1480b
JB
4984 (define-key function-key-map (vector keypad) (vector normal))))
4985 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
4986 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
4987 (kp-space ?\ )
4988 (kp-tab ?\t)
4989 (kp-enter ?\r)
4990 (kp-multiply ?*)
4991 (kp-add ?+)
4992 (kp-separator ?,)
4993 (kp-subtract ?-)
4994 (kp-decimal ?.)
4995 (kp-divide ?/)
4996 (kp-equal ?=)))
f54b0d85 4997\f
1e722f9f 4998;;;;
b005abd5 4999;;;; forking a twin copy of a buffer.
1e722f9f 5000;;;;
b005abd5
SM
5001
5002(defvar clone-buffer-hook nil
5003 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
5004
5005(defun clone-process (process &optional newname)
5006 "Create a twin copy of PROCESS.
5007If NEWNAME is nil, it defaults to PROCESS' name;
5008NEWNAME is modified by adding or incrementing <N> at the end as necessary.
5009If PROCESS is associated with a buffer, the new process will be associated
5010 with the current buffer instead.
5011Returns nil if PROCESS has already terminated."
5012 (setq newname (or newname (process-name process)))
5013 (if (string-match "<[0-9]+>\\'" newname)
5014 (setq newname (substring newname 0 (match-beginning 0))))
5015 (when (memq (process-status process) '(run stop open))
5016 (let* ((process-connection-type (process-tty-name process))
b005abd5
SM
5017 (new-process
5018 (if (memq (process-status process) '(open))
ed7069af
KS
5019 (let ((args (process-contact process t)))
5020 (setq args (plist-put args :name newname))
5021 (setq args (plist-put args :buffer
403ca8d9
KS
5022 (if (process-buffer process)
5023 (current-buffer))))
ed7069af 5024 (apply 'make-network-process args))
b005abd5
SM
5025 (apply 'start-process newname
5026 (if (process-buffer process) (current-buffer))
5027 (process-command process)))))
ed7069af
KS
5028 (set-process-query-on-exit-flag
5029 new-process (process-query-on-exit-flag process))
b005abd5
SM
5030 (set-process-inherit-coding-system-flag
5031 new-process (process-inherit-coding-system-flag process))
5032 (set-process-filter new-process (process-filter process))
5033 (set-process-sentinel new-process (process-sentinel process))
403ca8d9 5034 (set-process-plist new-process (copy-sequence (process-plist process)))
b005abd5
SM
5035 new-process)))
5036
b75b82ab 5037;; things to maybe add (currently partly covered by `funcall mode'):
b005abd5
SM
5038;; - syntax-table
5039;; - overlays
5040(defun clone-buffer (&optional newname display-flag)
186f9ad1
LT
5041 "Create and return a twin copy of the current buffer.
5042Unlike an indirect buffer, the new buffer can be edited
5043independently of the old one (if it is not read-only).
5044NEWNAME is the name of the new buffer. It may be modified by
5045adding or incrementing <N> at the end as necessary to create a
5046unique buffer name. If nil, it defaults to the name of the
5047current buffer, with the proper suffix. If DISPLAY-FLAG is
5048non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
5049clone a file-visiting buffer, or a buffer whose major mode symbol
5050has a non-nil `no-clone' property, results in an error.
5051
5052Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
5053current buffer with appropriate suffix. However, if a prefix
5054argument is given, then the command prompts for NEWNAME in the
5055minibuffer.
b005abd5 5056
b005abd5
SM
5057This runs the normal hook `clone-buffer-hook' in the new buffer
5058after it has been set up properly in other respects."
61acfe7f
RS
5059 (interactive
5060 (progn
5061 (if buffer-file-name
5062 (error "Cannot clone a file-visiting buffer"))
5063 (if (get major-mode 'no-clone)
5064 (error "Cannot clone a buffer in %s mode" mode-name))
5065 (list (if current-prefix-arg (read-string "Name: "))
5066 t)))
b005abd5
SM
5067 (if buffer-file-name
5068 (error "Cannot clone a file-visiting buffer"))
5069 (if (get major-mode 'no-clone)
5070 (error "Cannot clone a buffer in %s mode" mode-name))
5071 (setq newname (or newname (buffer-name)))
5072 (if (string-match "<[0-9]+>\\'" newname)
5073 (setq newname (substring newname 0 (match-beginning 0))))
5074 (let ((buf (current-buffer))
5075 (ptmin (point-min))
5076 (ptmax (point-max))
5077 (pt (point))
5078 (mk (if mark-active (mark t)))
5079 (modified (buffer-modified-p))
5080 (mode major-mode)
5081 (lvars (buffer-local-variables))
5082 (process (get-buffer-process (current-buffer)))
5083 (new (generate-new-buffer (or newname (buffer-name)))))
5084 (save-restriction
5085 (widen)
5086 (with-current-buffer new
5087 (insert-buffer-substring buf)))
5088 (with-current-buffer new
5089 (narrow-to-region ptmin ptmax)
5090 (goto-char pt)
5091 (if mk (set-mark mk))
5092 (set-buffer-modified-p modified)
5093
5094 ;; Clone the old buffer's process, if any.
5095 (when process (clone-process process))
5096
5097 ;; Now set up the major mode.
5098 (funcall mode)
5099
5100 ;; Set up other local variables.
5101 (mapcar (lambda (v)
5102 (condition-case () ;in case var is read-only
5103 (if (symbolp v)
5104 (makunbound v)
5105 (set (make-local-variable (car v)) (cdr v)))
5106 (error nil)))
5107 lvars)
5108
5109 ;; Run any hooks (typically set up by the major mode
5110 ;; for cloning to work properly).
5111 (run-hooks 'clone-buffer-hook))
5112 (if display-flag (pop-to-buffer new))
5113 new))
5114
fa65f20b 5115
7e3afb04 5116(defun clone-indirect-buffer (newname display-flag &optional norecord)
fa65f20b
GM
5117 "Create an indirect buffer that is a twin copy of the current buffer.
5118
5119Give the indirect buffer name NEWNAME. Interactively, read NEW-NAME
5120from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
5121or if not called with a prefix arg, NEWNAME defaults to the current
5122buffer's name. The name is modified by adding a `<N>' suffix to it
5123or by incrementing the N in an existing suffix.
5124
5125DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7e3afb04
GM
5126This is always done when called interactively.
5127
5128Optional last arg NORECORD non-nil means do not put this buffer at the
5129front of the list of recently selected ones."
61acfe7f
RS
5130 (interactive
5131 (progn
5132 (if (get major-mode 'no-clone-indirect)
5133 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5134 (list (if current-prefix-arg
5135 (read-string "BName of indirect buffer: "))
5136 t)))
5137 (if (get major-mode 'no-clone-indirect)
5138 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
fa65f20b
GM
5139 (setq newname (or newname (buffer-name)))
5140 (if (string-match "<[0-9]+>\\'" newname)
5141 (setq newname (substring newname 0 (match-beginning 0))))
5142 (let* ((name (generate-new-buffer-name newname))
5143 (buffer (make-indirect-buffer (current-buffer) name t)))
5144 (when display-flag
58dd38f1 5145 (pop-to-buffer buffer norecord))
fa65f20b
GM
5146 buffer))
5147
5148
7e3afb04
GM
5149(defun clone-indirect-buffer-other-window (buffer &optional norecord)
5150 "Create an indirect buffer that is a twin copy of BUFFER.
5151Select the new buffer in another window.
5152Optional second arg NORECORD non-nil means do not put this buffer at
5153the front of the list of recently selected ones."
5154 (interactive "bClone buffer in other window: ")
acd39eb6 5155 (let ((pop-up-windows t))
7e3afb04
GM
5156 (set-buffer buffer)
5157 (clone-indirect-buffer nil t norecord)))
5158
f54b0d85 5159\f
1d4b11bf
GM
5160;;; Handling of Backspace and Delete keys.
5161
e5212545
SM
5162(defcustom normal-erase-is-backspace
5163 (and (not noninteractive)
5164 (or (memq system-type '(ms-dos windows-nt))
267e1dbe 5165 (eq window-system 'mac)
e5212545
SM
5166 (and (memq window-system '(x))
5167 (fboundp 'x-backspace-delete-keys-p)
5168 (x-backspace-delete-keys-p))
5169 ;; If the terminal Emacs is running on has erase char
5170 ;; set to ^H, use the Backspace key for deleting
5171 ;; backward and, and the Delete key for deleting forward.
5172 (and (null window-system)
5173 (eq tty-erase-char ?\^H))))
7f62656b 5174 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
1d4b11bf
GM
5175
5176On window systems, the default value of this option is chosen
5177according to the keyboard used. If the keyboard has both a Backspace
5178key and a Delete key, and both are mapped to their usual meanings, the
5179option's default value is set to t, so that Backspace can be used to
7f62656b 5180delete backward, and Delete can be used to delete forward.
1d4b11bf 5181
7f62656b 5182If not running under a window system, customizing this option accomplishes
1d4b11bf
GM
5183a similar effect by mapping C-h, which is usually generated by the
5184Backspace key, to DEL, and by mapping DEL to C-d via
5185`keyboard-translate'. The former functionality of C-h is available on
5186the F1 key. You should probably not use this setting if you don't
f060b834
GM
5187have both Backspace, Delete and F1 keys.
5188
5189Setting this variable with setq doesn't take effect. Programmatically,
7f62656b 5190call `normal-erase-is-backspace-mode' (which see) instead."
1d4b11bf
GM
5191 :type 'boolean
5192 :group 'editing-basics
5193 :version "21.1"
5194 :set (lambda (symbol value)
5195 ;; The fboundp is because of a problem with :set when
5196 ;; dumping Emacs. It doesn't really matter.
7f62656b
EZ
5197 (if (fboundp 'normal-erase-is-backspace-mode)
5198 (normal-erase-is-backspace-mode (or value 0))
1d4b11bf
GM
5199 (set-default symbol value))))
5200
5201
7f62656b
EZ
5202(defun normal-erase-is-backspace-mode (&optional arg)
5203 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
5204
e02160a3 5205With numeric arg, turn the mode on if and only if ARG is positive.
7f62656b
EZ
5206
5207On window systems, when this mode is on, Delete is mapped to C-d and
5208Backspace is mapped to DEL; when this mode is off, both Delete and
5209Backspace are mapped to DEL. (The remapping goes via
5210`function-key-map', so binding Delete or Backspace in the global or
5211local keymap will override that.)
5212
5213In addition, on window systems, the bindings of C-Delete, M-Delete,
5214C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
5215the global keymap in accordance with the functionality of Delete and
5216Backspace. For example, if Delete is remapped to C-d, which deletes
5217forward, C-Delete is bound to `kill-word', but if Delete is remapped
5218to DEL, which deletes backward, C-Delete is bound to
5219`backward-kill-word'.
5220
5221If not running on a window system, a similar effect is accomplished by
5222remapping C-h (normally produced by the Backspace key) and DEL via
5223`keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
5224to C-d; if it's off, the keys are not remapped.
5225
5226When not running on a window system, and this mode is turned on, the
5227former functionality of C-h is available on the F1 key. You should
5228probably not turn on this mode on a text-only terminal if you don't
5229have both Backspace, Delete and F1 keys.
5230
5231See also `normal-erase-is-backspace'."
1d4b11bf 5232 (interactive "P")
7f62656b 5233 (setq normal-erase-is-backspace
1d4b11bf
GM
5234 (if arg
5235 (> (prefix-numeric-value arg) 0)
7f62656b 5236 (not normal-erase-is-backspace)))
1d4b11bf 5237
13a9eed7
EZ
5238 (cond ((or (memq window-system '(x w32 mac pc))
5239 (memq system-type '(ms-dos windows-nt)))
7f62656b 5240 (let ((bindings
103db06c
RS
5241 `(([C-delete] [C-backspace])
5242 ([M-delete] [M-backspace])
5243 ([C-M-delete] [C-M-backspace])
ec9f4754 5244 (,esc-map
103db06c
RS
5245 [C-delete] [C-backspace])))
5246 (old-state (lookup-key function-key-map [delete])))
ec9f4754 5247
7f62656b 5248 (if normal-erase-is-backspace
ec9f4754
GM
5249 (progn
5250 (define-key function-key-map [delete] [?\C-d])
be4f1e41 5251 (define-key function-key-map [kp-delete] [?\C-d])
ec9f4754
GM
5252 (define-key function-key-map [backspace] [?\C-?]))
5253 (define-key function-key-map [delete] [?\C-?])
be4f1e41 5254 (define-key function-key-map [kp-delete] [?\C-?])
ec9f4754
GM
5255 (define-key function-key-map [backspace] [?\C-?]))
5256
103db06c
RS
5257 ;; Maybe swap bindings of C-delete and C-backspace, etc.
5258 (unless (equal old-state (lookup-key function-key-map [delete]))
5259 (dolist (binding bindings)
5260 (let ((map global-map))
5261 (when (keymapp (car binding))
5262 (setq map (car binding) binding (cdr binding)))
5263 (let* ((key1 (nth 0 binding))
5264 (key2 (nth 1 binding))
5265 (binding1 (lookup-key map key1))
5266 (binding2 (lookup-key map key2)))
5267 (define-key map key1 binding2)
5268 (define-key map key2 binding1)))))))
1d4b11bf 5269 (t
7f62656b 5270 (if normal-erase-is-backspace
1d4b11bf
GM
5271 (progn
5272 (keyboard-translate ?\C-h ?\C-?)
5273 (keyboard-translate ?\C-? ?\C-d))
5274 (keyboard-translate ?\C-h ?\C-h)
5275 (keyboard-translate ?\C-? ?\C-?))))
5276
7f62656b 5277 (run-hooks 'normal-erase-is-backspace-hook)
1d4b11bf 5278 (if (interactive-p)
7f62656b
EZ
5279 (message "Delete key deletes %s"
5280 (if normal-erase-is-backspace "forward" "backward"))))
ea82f0df 5281\f
aca8bee5 5282(defvar vis-mode-saved-buffer-invisibility-spec nil
0f7df535 5283 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
7f62656b 5284
0f7df535
RS
5285(define-minor-mode visible-mode
5286 "Toggle Visible mode.
5287With argument ARG turn Visible mode on iff ARG is positive.
1d4b11bf 5288
0f7df535
RS
5289Enabling Visible mode makes all invisible text temporarily visible.
5290Disabling Visible mode turns off that effect. Visible mode
5291works by saving the value of `buffer-invisibility-spec' and setting it to nil."
4e57881d 5292 :lighter " Vis"
ab77efd0 5293 :group 'editing-basics
aca8bee5
SM
5294 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
5295 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
5296 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
0f7df535 5297 (when visible-mode
aca8bee5
SM
5298 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
5299 buffer-invisibility-spec)
5300 (setq buffer-invisibility-spec nil)))
4e57881d 5301\f
e1e04350 5302;; Minibuffer prompt stuff.
9b350152 5303
49c14a05
GM
5304;(defun minibuffer-prompt-modification (start end)
5305; (error "You cannot modify the prompt"))
5306;
5307;
5308;(defun minibuffer-prompt-insertion (start end)
5309; (let ((inhibit-modification-hooks t))
5310; (delete-region start end)
5311; ;; Discard undo information for the text insertion itself
5312; ;; and for the text deletion.above.
5313; (when (consp buffer-undo-list)
5314; (setq buffer-undo-list (cddr buffer-undo-list)))
5315; (message "You cannot modify the prompt")))
5316;
5317;
f1180544 5318;(setq minibuffer-prompt-properties
49c14a05
GM
5319; (list 'modification-hooks '(minibuffer-prompt-modification)
5320; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
f1180544 5321;
9b350152 5322
00398e3b 5323(provide 'simple)
ab5796a9 5324
621a3f62 5325;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
c88ab9ce 5326;;; simple.el ends here