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