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