import xemacs-21.2.37
[chise/xemacs-chise.git.1] / lisp / simple.el
1 ;;; simple.el --- basic editing commands for XEmacs
2
3 ;; Copyright (C) 1985-7, 1993-5, 1997 Free Software Foundation, Inc.
4 ;; Copyright (C) 1995 Tinker Systems and INS Engineering Corp.
5 ;; Copyright (C) 2000 Ben Wing.
6
7 ;; Maintainer: XEmacs Development Team
8 ;; Keywords: lisp, extensions, internal, dumped
9
10 ;; This file is part of XEmacs.
11
12 ;; XEmacs is free software; you can redistribute it and/or modify it
13 ;; under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; XEmacs is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
24 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
25 ;; 02111-1307, USA.
26
27 ;;; Synched up with: FSF 19.34 [But not very closely].
28
29 ;;; Commentary:
30
31 ;; This file is dumped with XEmacs.
32
33 ;; A grab-bag of basic XEmacs commands not specifically related to some
34 ;; major mode or to file-handling.
35
36 ;; Changes for zmacs-style active-regions:
37 ;;
38 ;; beginning-of-buffer, end-of-buffer, count-lines-region,
39 ;; count-lines-buffer, what-line, what-cursor-position, set-goal-column,
40 ;; set-fill-column, prefix-arg-internal, and line-move (which is used by
41 ;; next-line and previous-line) set zmacs-region-stays to t, so that they
42 ;; don't affect the current region-hilighting state.
43 ;;
44 ;; mark-whole-buffer, mark-word, exchange-point-and-mark, and
45 ;; set-mark-command (without an argument) call zmacs-activate-region.
46 ;;
47 ;; mark takes an optional arg like the new Fmark_marker() does.  When
48 ;; the region is not active, mark returns nil unless the optional arg is true.
49 ;;
50 ;; push-mark, pop-mark, exchange-point-and-mark, and set-marker, and
51 ;; set-mark-command use (mark t) so that they can access the mark whether
52 ;; the region is active or not.
53 ;;
54 ;; shell-command, shell-command-on-region, yank, and yank-pop (which all
55 ;; push a mark) have been altered to call exchange-point-and-mark with an
56 ;; argument, meaning "don't activate the region".  These commands  only use
57 ;; exchange-point-and-mark to position the newly-pushed mark correctly, so
58 ;; this isn't a user-visible change.  These functions have also been altered
59 ;; to use (mark t) for the same reason.
60
61 ;; 97/3/14 Jareth Hein (jhod@po.iijnet.or.jp) added kinsoku processing (support
62 ;; for filling of Asian text) into the fill code. This was ripped bleeding from
63 ;; Mule-2.3, and could probably use some feature additions (like additional wrap
64 ;; styles, etc)
65
66 ;; 97/06/11 Steve Baur (steve@xemacs.org) Convert use of
67 ;;  (preceding|following)-char to char-(after|before).
68
69 ;;; Code:
70
71 (defgroup editing-basics nil
72   "Most basic editing variables."
73   :group 'editing)
74
75 (defgroup killing nil
76   "Killing and yanking commands."
77   :group 'editing)
78
79 (defgroup fill-comments nil
80   "Indenting and filling of comments."
81   :prefix "comment-"
82   :group 'fill)
83
84 (defgroup paren-matching nil
85   "Highlight (un)matching of parens and expressions."
86   :prefix "paren-"
87   :group 'matching)
88
89 (defgroup log-message nil
90   "Messages logging and display customizations."
91   :group 'minibuffer)
92
93 (defgroup warnings nil
94   "Warnings customizations."
95   :group 'minibuffer)
96
97
98 (defcustom search-caps-disable-folding t
99   "*If non-nil, upper case chars disable case fold searching.
100 This does not apply to \"yanked\" strings."
101   :type 'boolean
102   :group 'editing-basics)
103
104 ;; This is stolen (and slightly modified) from FSF emacs's
105 ;; `isearch-no-upper-case-p'.
106 (defun no-upper-case-p (string &optional regexp-flag)
107   "Return t if there are no upper case chars in STRING.
108 If REGEXP-FLAG is non-nil, disregard letters preceded by `\\' (but not `\\\\')
109 since they have special meaning in a regexp."
110   (let ((case-fold-search nil))
111     (not (string-match (if regexp-flag
112                            "\\(^\\|\\\\\\\\\\|[^\\]\\)[A-Z]"
113                          "[A-Z]")
114                        string))
115     ))
116
117 (defmacro with-search-caps-disable-folding (string regexp-flag &rest body) "\
118 Eval BODY with `case-fold-search' let to nil if `search-caps-disable-folding'
119 is non-nil, and if STRING (either a string or a regular expression according
120 to REGEXP-FLAG) contains uppercase letters."
121   `(let ((case-fold-search
122           (if (and case-fold-search search-caps-disable-folding)
123               (no-upper-case-p ,string ,regexp-flag)
124             case-fold-search)))
125      ,@body))
126 (put 'with-search-caps-disable-folding 'lisp-indent-function 2)
127 (put 'with-search-caps-disable-folding 'edebug-form-spec
128      '(sexp sexp &rest form))
129
130 (defmacro with-interactive-search-caps-disable-folding (string regexp-flag
131                                                                &rest body)
132   "Same as `with-search-caps-disable-folding', but only in the case of a
133 function called interactively."
134   `(let ((case-fold-search
135           (if (and (interactive-p)
136                    case-fold-search search-caps-disable-folding)
137               (no-upper-case-p ,string ,regexp-flag)
138             case-fold-search)))
139      ,@body))
140 (put 'with-interactive-search-caps-disable-folding 'lisp-indent-function 2)
141 (put 'with-interactive-search-caps-disable-folding 'edebug-form-spec
142      '(sexp sexp &rest form))
143
144 (defun newline (&optional n)
145   "Insert a newline, and move to left margin of the new line if it's blank.
146 The newline is marked with the text-property `hard'.
147 With optional arg N, insert that many newlines.
148 In Auto Fill mode, if no numeric arg, break the preceding line if it's long."
149   (interactive "*P")
150   (barf-if-buffer-read-only nil (point))
151   ;; Inserting a newline at the end of a line produces better redisplay in
152   ;; try_window_id than inserting at the beginning of a line, and the textual
153   ;; result is the same.  So, if we're at beginning of line, pretend to be at
154   ;; the end of the previous line.
155   ;; #### Does this have any relevance in XEmacs?
156   (let ((flag (and (not (bobp))
157                    (bolp)
158                    ;; Make sure the newline before point isn't intangible.
159                    (not (get-char-property (1- (point)) 'intangible))
160                    ;; Make sure the newline before point isn't read-only.
161                    (not (get-char-property (1- (point)) 'read-only))
162                    ;; Make sure the newline before point isn't invisible.
163                    (not (get-char-property (1- (point)) 'invisible))
164                    ;; This should probably also test for the previous char
165                    ;;  being the *last* character too.
166                    (not (get-char-property (1- (point)) 'end-open))
167                    ;; Make sure the newline before point has the same
168                    ;; properties as the char before it (if any).
169                    (< (or (previous-extent-change (point)) -2)
170                       (- (point) 2))))
171         (was-page-start (and (bolp)
172                              (looking-at page-delimiter)))
173         (beforepos (point)))
174     (if flag (backward-char 1))
175     ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
176     ;; Set last-command-char to tell self-insert what to insert.
177     (let ((last-command-char ?\n)
178           ;; Don't auto-fill if we have a numeric argument.
179           ;; Also not if flag is true (it would fill wrong line);
180           ;; there is no need to since we're at BOL.
181           (auto-fill-function (if (or n flag) nil auto-fill-function)))
182       (unwind-protect
183           (self-insert-command (prefix-numeric-value n))
184         ;; If we get an error in self-insert-command, put point at right place.
185         (if flag (forward-char 1))))
186     ;; If we did *not* get an error, cancel that forward-char.
187     (if flag (backward-char 1))
188     ;; Mark the newline(s) `hard'.
189     (if use-hard-newlines
190         (let* ((from (- (point) (if n (prefix-numeric-value n) 1)))
191                (sticky (get-text-property from 'end-open))) ; XEmacs
192           (put-text-property from (point) 'hard 't)
193           ;; If end-open is not "t", add 'hard to end-open list
194           (if (and (listp sticky) (not (memq 'hard sticky)))
195               (put-text-property from (point) 'end-open ; XEmacs
196                                  (cons 'hard sticky)))))
197     ;; If the newline leaves the previous line blank,
198     ;; and we have a left margin, delete that from the blank line.
199     (or flag
200         (save-excursion
201           (goto-char beforepos)
202           (beginning-of-line)
203           (and (looking-at "[ \t]$")
204                (> (current-left-margin) 0)
205                (delete-region (point) (progn (end-of-line) (point))))))
206     (if flag (forward-char 1))
207     ;; Indent the line after the newline, except in one case:
208     ;; when we added the newline at the beginning of a line
209     ;; which starts a page.
210     (or was-page-start
211         (move-to-left-margin nil t)))
212   nil)
213
214 (defun set-hard-newline-properties (from to)
215   (let ((sticky (get-text-property from 'rear-nonsticky)))
216     (put-text-property from to 'hard 't)
217     ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
218     (if (and (listp sticky) (not (memq 'hard sticky)))
219         (put-text-property from (point) 'rear-nonsticky
220                            (cons 'hard sticky)))))
221
222 (defun open-line (n)
223   "Insert a newline and leave point before it.
224 If there is a fill prefix and/or a left-margin, insert them on the new line
225 if the line would have been blank.
226 With arg N, insert N newlines."
227   (interactive "*p")
228   (let* ((do-fill-prefix (and fill-prefix (bolp)))
229          (do-left-margin (and (bolp) (> (current-left-margin) 0)))
230          (loc (point)))
231     (newline n)
232     (goto-char loc)
233     (while (> n 0)
234       (cond ((bolp)
235              (if do-left-margin (indent-to (current-left-margin)))
236              (if do-fill-prefix (insert fill-prefix))))
237       (forward-line 1)
238       (setq n (1- n)))
239     (goto-char loc)
240     (end-of-line)))
241
242 (defun split-line ()
243   "Split current line, moving portion beyond point vertically down."
244   (interactive "*")
245   (skip-chars-forward " \t")
246   (let ((col (current-column))
247         (pos (point)))
248     (newline 1)
249     (indent-to col 0)
250     (goto-char pos)))
251
252 (defun quoted-insert (arg)
253   "Read next input character and insert it.
254 This is useful for inserting control characters.
255 You may also type up to 3 octal digits, to insert a character with that code.
256
257 In overwrite mode, this function inserts the character anyway, and
258 does not handle octal digits specially.  This means that if you use
259 overwrite as your normal editing mode, you can use this function to
260 insert characters when necessary.
261
262 In binary overwrite mode, this function does overwrite, and octal
263 digits are interpreted as a character code.  This is supposed to make
264 this function useful in editing binary files."
265   (interactive "*p")
266   (let ((char (if (or (not overwrite-mode)
267                       (eq overwrite-mode 'overwrite-mode-binary))
268                   (read-quoted-char)
269                 ;; read-char obeys C-g, so we should protect.  FSF
270                 ;; doesn't have the protection here, but it's a bug in
271                 ;; FSF.
272                 (let ((inhibit-quit t))
273                   (read-char)))))
274     (if (> arg 0)
275         (if (eq overwrite-mode 'overwrite-mode-binary)
276             (delete-char arg)))
277     (while (> arg 0)
278       (insert char)
279       (setq arg (1- arg)))))
280
281 (defun delete-indentation (&optional arg)
282   "Join this line to previous and fix up whitespace at join.
283 If there is a fill prefix, delete it from the beginning of this line.
284 With argument, join this line to following line."
285   (interactive "*P")
286   (beginning-of-line)
287   (if arg (forward-line 1))
288   (if (eq (char-before (point)) ?\n)
289       (progn
290         (delete-region (point) (1- (point)))
291         ;; If the second line started with the fill prefix,
292         ;; delete the prefix.
293         (if (and fill-prefix
294                  (<= (+ (point) (length fill-prefix)) (point-max))
295                  (string= fill-prefix
296                           (buffer-substring (point)
297                                             (+ (point) (length fill-prefix)))))
298             (delete-region (point) (+ (point) (length fill-prefix))))
299         (fixup-whitespace))))
300
301 (defun fixup-whitespace ()
302   "Fixup white space between objects around point.
303 Leave one space or none, according to the context."
304   (interactive "*")
305   (save-excursion
306     (delete-horizontal-space)
307     (if (or (looking-at "^\\|\\s)")
308             (save-excursion (forward-char -1)
309                             (looking-at "$\\|\\s(\\|\\s'")))
310         nil
311       (insert ?\ ))))
312
313 (defun delete-horizontal-space ()
314   "Delete all spaces and tabs around point."
315   (interactive "*")
316   (skip-chars-backward " \t")
317   (delete-region (point) (progn (skip-chars-forward " \t") (point))))
318
319 (defun just-one-space ()
320   "Delete all spaces and tabs around point, leaving one space."
321   (interactive "*")
322   (if abbrev-mode ; XEmacs
323       (expand-abbrev))
324   (skip-chars-backward " \t")
325   (if (eq (char-after (point)) ? ) ; XEmacs
326       (forward-char 1)
327     (insert ? ))
328   (delete-region (point) (progn (skip-chars-forward " \t") (point))))
329
330 (defun delete-blank-lines ()
331   "On blank line, delete all surrounding blank lines, leaving just one.
332 On isolated blank line, delete that one.
333 On nonblank line, delete any immediately following blank lines."
334   (interactive "*")
335   (let (thisblank singleblank)
336     (save-excursion
337       (beginning-of-line)
338       (setq thisblank (looking-at "[ \t]*$"))
339       ;; Set singleblank if there is just one blank line here.
340       (setq singleblank
341             (and thisblank
342                  (not (looking-at "[ \t]*\n[ \t]*$"))
343                  (or (bobp)
344                      (progn (forward-line -1)
345                             (not (looking-at "[ \t]*$")))))))
346     ;; Delete preceding blank lines, and this one too if it's the only one.
347     (if thisblank
348         (progn
349           (beginning-of-line)
350           (if singleblank (forward-line 1))
351           (delete-region (point)
352                          (if (re-search-backward "[^ \t\n]" nil t)
353                              (progn (forward-line 1) (point))
354                            (point-min)))))
355     ;; Delete following blank lines, unless the current line is blank
356     ;; and there are no following blank lines.
357     (if (not (and thisblank singleblank))
358         (save-excursion
359           (end-of-line)
360           (forward-line 1)
361           (delete-region (point)
362                          (if (re-search-forward "[^ \t\n]" nil t)
363                              (progn (beginning-of-line) (point))
364                            (point-max)))))
365     ;; Handle the special case where point is followed by newline and eob.
366     ;; Delete the line, leaving point at eob.
367     (if (looking-at "^[ \t]*\n\\'")
368         (delete-region (point) (point-max)))))
369
370 (defun back-to-indentation ()
371   "Move point to the first non-whitespace character on this line."
372   ;; XEmacs change
373   (interactive "_")
374   (beginning-of-line 1)
375   (skip-chars-forward " \t"))
376
377 (defun newline-and-indent ()
378   "Insert a newline, then indent according to major mode.
379 Indentation is done using the value of `indent-line-function'.
380 In programming language modes, this is the same as TAB.
381 In some text modes, where TAB inserts a tab, this command indents to the
382 column specified by the function `current-left-margin'."
383   (interactive "*")
384   (delete-region (point) (progn (skip-chars-backward " \t") (point)))
385   (newline)
386   (indent-according-to-mode))
387
388 (defun reindent-then-newline-and-indent ()
389   "Reindent current line, insert newline, then indent the new line.
390 Indentation of both lines is done according to the current major mode,
391 which means calling the current value of `indent-line-function'.
392 In programming language modes, this is the same as TAB.
393 In some text modes, where TAB inserts a tab, this indents to the
394 column specified by the function `current-left-margin'."
395   (interactive "*")
396   (save-excursion
397     (delete-region (point) (progn (skip-chars-backward " \t") (point)))
398     (indent-according-to-mode))
399   (newline)
400   (indent-according-to-mode))
401
402 ;; Internal subroutine of delete-char
403 (defun kill-forward-chars (arg)
404   (if (listp arg) (setq arg (car arg)))
405   (if (eq arg '-) (setq arg -1))
406   (kill-region (point) (+ (point) arg)))
407
408 ;; Internal subroutine of backward-delete-char
409 (defun kill-backward-chars (arg)
410   (if (listp arg) (setq arg (car arg)))
411   (if (eq arg '-) (setq arg -1))
412   (kill-region (point) (- (point) arg)))
413
414 (defun backward-delete-char-untabify (arg &optional killp)
415   "Delete characters backward, changing tabs into spaces.
416 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
417 Interactively, ARG is the prefix arg (default 1)
418 and KILLP is t if a prefix arg was specified."
419   (interactive "*p\nP")
420   (let ((count arg))
421     (save-excursion
422       (while (and (> count 0) (not (bobp)))
423         (if (eq (char-before (point)) ?\t) ; XEmacs
424             (let ((col (current-column)))
425               (forward-char -1)
426               (setq col (- col (current-column)))
427               (insert-char ?\ col)
428               (delete-char 1)))
429         (forward-char -1)
430         (setq count (1- count)))))
431   (delete-backward-char arg killp)
432   ;; XEmacs: In overwrite mode, back over columns while clearing them out,
433   ;; unless at end of line.
434   (and overwrite-mode (not (eolp))
435        (save-excursion (insert-char ?\  arg))))
436
437 (defcustom delete-key-deletes-forward t
438   "*If non-nil, the DEL key will erase one character forwards.
439 If nil, the DEL key will erase one character backwards."
440   :type 'boolean
441   :group 'editing-basics)
442
443 (defcustom backward-delete-function 'backward-delete-char
444   "*Function called to delete backwards on a delete keypress.
445 If `delete-key-deletes-forward' is nil, `backward-or-forward-delete-char'
446 calls this function to erase one character backwards.  Default value
447 is 'backward-delete-char, with 'backward-delete-char-untabify being a
448 popular alternate setting."
449   :type 'function
450   :group 'editing-basics)
451
452 ;; Trash me, baby.
453 (defsubst delete-forward-p ()
454   (and delete-key-deletes-forward
455        (or (not (eq (device-type) 'x))
456            (x-keysym-on-keyboard-sans-modifiers-p 'backspace))))
457
458 (defun backward-or-forward-delete-char (arg)
459   "Delete either one character backwards or one character forwards.
460 Controlled by the state of `delete-key-deletes-forward' and whether the
461 BackSpace keysym even exists on your keyboard.  If you don't have a
462 BackSpace keysym, the delete key should always delete one character
463 backwards."
464   (interactive "*p")
465   (if (delete-forward-p)
466       (delete-char arg)
467     (funcall backward-delete-function arg)))
468
469 (defun backward-or-forward-kill-word (arg)
470   "Delete either one word backwards or one word forwards.
471 Controlled by the state of `delete-key-deletes-forward' and whether the
472 BackSpace keysym even exists on your keyboard.  If you don't have a
473 BackSpace keysym, the delete key should always delete one character
474 backwards."
475   (interactive "*p")
476   (if (delete-forward-p)
477       (kill-word arg)
478     (backward-kill-word arg)))
479
480 (defun backward-or-forward-kill-sentence (arg)
481     "Delete either one sentence backwards or one sentence forwards.
482 Controlled by the state of `delete-key-deletes-forward' and whether the
483 BackSpace keysym even exists on your keyboard.  If you don't have a
484 BackSpace keysym, the delete key should always delete one character
485 backwards."
486   (interactive "*P")
487   (if (delete-forward-p)
488       (kill-sentence arg)
489     (backward-kill-sentence (prefix-numeric-value arg))))
490
491 (defun backward-or-forward-kill-sexp (arg)
492     "Delete either one sexpr backwards or one sexpr forwards.
493 Controlled by the state of `delete-key-deletes-forward' and whether the
494 BackSpace keysym even exists on your keyboard.  If you don't have a
495 BackSpace keysym, the delete key should always delete one character
496 backwards."
497   (interactive "*p")
498   (if (delete-forward-p)
499       (kill-sexp arg)
500     (backward-kill-sexp arg)))
501
502 (defun zap-to-char (arg char)
503   "Kill up to and including ARG'th occurrence of CHAR.
504 Goes backward if ARG is negative; error if CHAR not found."
505   (interactive "*p\ncZap to char: ")
506   (kill-region (point) (with-interactive-search-caps-disable-folding
507                            (char-to-string char) nil
508                          (search-forward (char-to-string char) nil nil arg)
509                          (point))))
510
511 (defun zap-up-to-char (arg char)
512   "Kill up to ARG'th occurrence of CHAR.
513 Goes backward if ARG is negative; error if CHAR not found."
514   (interactive "*p\ncZap up to char: ")
515   (kill-region (point) (with-interactive-search-caps-disable-folding
516                            (char-to-string char) nil
517                          (search-forward (char-to-string char) nil nil arg)
518                          (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
519                          (point))))
520
521 (defun beginning-of-buffer (&optional arg)
522   "Move point to the beginning of the buffer; leave mark at previous position.
523 With arg N, put point N/10 of the way from the beginning.
524
525 If the buffer is narrowed, this command uses the beginning and size
526 of the accessible part of the buffer.
527
528 Don't use this command in Lisp programs!
529 \(goto-char (point-min)) is faster and avoids clobbering the mark."
530   ;; XEmacs change
531   (interactive "_P")
532   (push-mark)
533   (let ((size (- (point-max) (point-min))))
534     (goto-char (if arg
535                    (+ (point-min)
536                       (if (> size 10000)
537                           ;; Avoid overflow for large buffer sizes!
538                           (* (prefix-numeric-value arg)
539                              (/ size 10))
540                         (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
541                  (point-min))))
542   (if arg (forward-line 1)))
543
544 (defun end-of-buffer (&optional arg)
545   "Move point to the end of the buffer; leave mark at previous position.
546 With arg N, put point N/10 of the way from the end.
547
548 If the buffer is narrowed, this command uses the beginning and size
549 of the accessible part of the buffer.
550
551 Don't use this command in Lisp programs!
552 \(goto-char (point-max)) is faster and avoids clobbering the mark."
553   ;; XEmacs change
554   (interactive "_P")
555   (push-mark)
556   ;; XEmacs changes here.
557   (let ((scroll-to-end (not (pos-visible-in-window-p (point-max))))
558         (size (- (point-max) (point-min))))
559     (goto-char (if arg
560                    (- (point-max)
561                       (if (> size 10000)
562                           ;; Avoid overflow for large buffer sizes!
563                           (* (prefix-numeric-value arg)
564                              (/ size 10))
565                         (/ (* size (prefix-numeric-value arg)) 10)))
566                  (point-max)))
567     (cond (arg
568            ;; If we went to a place in the middle of the buffer,
569            ;; adjust it to the beginning of a line.
570            (forward-line 1))
571           ;; XEmacs change
572           (scroll-to-end
573            ;; If the end of the buffer is not already on the screen,
574            ;; then scroll specially to put it near, but not at, the bottom.
575            (recenter -3)))))
576
577 ;; XEmacs (not in FSF)
578 (defun mark-beginning-of-buffer (&optional arg)
579   "Push a mark at the beginning of the buffer; leave point where it is.
580 With arg N, push mark N/10 of the way from the true beginning."
581   (interactive "P")
582   (push-mark (if arg
583                  (if (> (buffer-size) 10000)
584                      ;; Avoid overflow for large buffer sizes!
585                      (* (prefix-numeric-value arg)
586                         (/ (buffer-size) 10))
587                    (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
588                (point-min))
589              nil
590              t))
591 (define-function 'mark-bob 'mark-beginning-of-buffer)
592
593 ;; XEmacs (not in FSF)
594 (defun mark-end-of-buffer (&optional arg)
595   "Push a mark at the end of the buffer; leave point where it is.
596 With arg N, push mark N/10 of the way from the true end."
597   (interactive "P")
598   (push-mark (if arg
599                  (- (1+ (buffer-size))
600                     (if (> (buffer-size) 10000)
601                         ;; Avoid overflow for large buffer sizes!
602                         (* (prefix-numeric-value arg)
603                            (/ (buffer-size) 10))
604                       (/ (* (buffer-size) (prefix-numeric-value arg)) 10)))
605                  (point-max))
606              nil
607              t))
608 (define-function 'mark-eob 'mark-end-of-buffer)
609
610 (defun mark-whole-buffer ()
611   "Put point at beginning and mark at end of buffer.
612 You probably should not use this function in Lisp programs;
613 it is usually a mistake for a Lisp function to use any subroutine
614 that uses or sets the mark."
615   (interactive)
616   (push-mark (point))
617   (push-mark (point-max) nil t)
618   (goto-char (point-min)))
619
620 ;; XEmacs
621 (defun eval-current-buffer (&optional printflag)
622   "Evaluate the current buffer as Lisp code.
623 Programs can pass argument PRINTFLAG which controls printing of output:
624 nil means discard it; anything else is stream for print."
625   (interactive)
626   (eval-buffer (current-buffer) printflag))
627
628 ;; XEmacs
629 (defun count-words-buffer (&optional buffer)
630   "Print the number of words in BUFFER.
631 If called noninteractively, the value is returned rather than printed.
632 BUFFER defaults to the current buffer."
633   (interactive)
634   (let ((words (count-words-region (point-min) (point-max) buffer)))
635     (when (interactive-p)
636       (message "Buffer has %d words" words))
637     words))
638
639 ;; XEmacs
640 (defun count-words-region (start end &optional buffer)
641   "Print the number of words in region between START and END in BUFFER.
642 If called noninteractively, the value is returned rather than printed.
643 BUFFER defaults to the current buffer."
644   (interactive "_r")
645   (save-excursion
646     (set-buffer (or buffer (current-buffer)))
647     (let ((words 0))
648       (goto-char start)
649       (while (< (point) end)
650         (when (forward-word 1)
651           (incf words)))
652       (when  (interactive-p)
653         (message "Region has %d words" words))
654       words)))
655
656 (defun count-lines-region (start end)
657   "Print number of lines and characters in the region."
658   ;; XEmacs change
659   (interactive "_r")
660   (message "Region has %d lines, %d characters"
661            (count-lines start end) (- end start)))
662
663 ;; XEmacs
664 (defun count-lines-buffer (&optional buffer)
665   "Print number of lines and characters in BUFFER."
666   (interactive)
667   (with-current-buffer (or buffer (current-buffer))
668     (let ((cnt (count-lines (point-min) (point-max))))
669       (message "Buffer has %d lines, %d characters"
670                cnt (- (point-max) (point-min)))
671       cnt)))
672
673 ;;; Modified by Bob Weiner, 8/24/95, to print narrowed line number also.
674 ;;; Expanded by Bob Weiner, BeOpen, on 02/12/1997
675 (defun what-line ()
676   "Print the following variants of the line number of point:
677      Region line     - displayed line within the active region
678      Collapsed line  - includes only selectively displayed lines;
679      Buffer line     - physical line in the buffer;
680      Narrowed line   - line number from the start of the buffer narrowing."
681   ;; XEmacs change
682   (interactive "_")
683   (let ((opoint (point)) start)
684     (save-excursion
685       (save-restriction
686         (if (region-active-p)
687             (goto-char (region-beginning))
688           (goto-char (point-min)))
689         (widen)
690         (beginning-of-line)
691         (setq start (point))
692         (goto-char opoint)
693         (beginning-of-line)
694         (let* ((buffer-line (1+ (count-lines 1 (point))))
695                (narrowed-p (or (/= start 1)
696                                (/= (point-max) (1+ (buffer-size)))))
697                (narrowed-line (if narrowed-p (1+ (count-lines start (point)))))
698                (selective-line (if selective-display
699                                    (1+ (count-lines start (point) t))))
700                (region-line (if (region-active-p)
701                                 (1+ (count-lines start (point) selective-display)))))
702           (cond (region-line
703                  (message "Region line %d; Buffer line %d"
704                           region-line buffer-line))
705                 ((and narrowed-p selective-line (/= selective-line narrowed-line))
706                  ;; buffer narrowed and some lines selectively displayed
707                  (message "Collapsed line %d; Buffer line %d; Narrowed line %d"
708                           selective-line buffer-line narrowed-line))
709                 (narrowed-p
710                  ;; buffer narrowed
711                  (message "Buffer line %d; Narrowed line %d"
712                           buffer-line narrowed-line))
713                 ((and selective-line (/= selective-line buffer-line))
714                  ;; some lines selectively displayed
715                  (message "Collapsed line %d; Buffer line %d"
716                           selective-line buffer-line))
717                 (t
718                  ;; give a basic line count
719                  (message "Line %d" buffer-line)))))))
720   (setq zmacs-region-stays t))
721
722 ;; new in XEmacs 21.2 (not in FSF).
723 (defun line-number (&optional pos respect-narrowing)
724   "Return the line number of POS (defaults to point).
725 If RESPECT-NARROWING is non-nil, then the narrowed line number is returned;
726 otherwise, the absolute line number is returned.  The returned line can always
727 be given to `goto-line' to get back to the current line."
728   (if (and pos (/= pos (point)))
729       (save-excursion
730         (goto-char pos)
731         (line-number nil respect-narrowing))
732     (1+ (count-lines (if respect-narrowing (point-min) 1) (point-at-bol)))))
733
734 (defun count-lines (start end &optional ignore-invisible-lines-flag)
735   "Return number of lines between START and END.
736 This is usually the number of newlines between them,
737 but can be one more if START is not equal to END
738 and the greater of them is not at the start of a line.
739
740 With optional IGNORE-INVISIBLE-LINES-FLAG non-nil, lines collapsed with
741 selective-display are excluded from the line count.
742
743 NOTE: The expression to return the current line number is not obvious:
744
745 (1+ (count-lines 1 (point-at-bol)))
746
747 See also `line-number'."
748   (save-excursion
749     (save-restriction
750       (narrow-to-region start end)
751       (goto-char (point-min))
752       (if (and (not ignore-invisible-lines-flag) (eq selective-display t))
753           (save-match-data
754             (let ((done 0))
755               (while (re-search-forward "[\n\C-m]" nil t 40)
756                 (setq done (+ 40 done)))
757               (while (re-search-forward "[\n\C-m]" nil t 1)
758                 (setq done (+ 1 done)))
759               (goto-char (point-max))
760               (if (and (/= start end)
761                        (not (bolp)))
762                   (1+ done)
763                 done)))
764         (- (buffer-size) (forward-line (buffer-size)))))))
765
766 (defun what-cursor-position ()
767   "Print info on cursor position (on screen and within buffer)."
768   ;; XEmacs change
769   (interactive "_")
770   (let* ((char (char-after (point))) ; XEmacs
771          (beg (point-min))
772          (end (point-max))
773          (pos (point))
774          (total (buffer-size))
775          (percent (if (> total 50000)
776                       ;; Avoid overflow from multiplying by 100!
777                       (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
778                     (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
779          (hscroll (if (= (window-hscroll) 0)
780                       ""
781                     (format " Hscroll=%d" (window-hscroll))))
782          (col (+ (current-column) (if column-number-start-at-one 1 0))))
783     (if (= pos end)
784         (if (or (/= beg 1) (/= end (1+ total)))
785             (message "point=%d of %d(%d%%) <%d - %d>  column %d %s"
786                      pos total percent beg end col hscroll)
787           (message "point=%d of %d(%d%%)  column %d %s"
788                    pos total percent col hscroll))
789       ;; XEmacs: don't use single-key-description
790       (if (or (/= beg 1) (/= end (1+ total)))
791           (message "Char: %s (0%o, %d, 0x%x)  point=%d of %d(%d%%) <%d - %d>  column %d %s"
792                    (text-char-description char) char char char pos total
793                    percent beg end col hscroll)
794         (message "Char: %s (0%o, %d, 0x%x)  point=%d of %d(%d%%)  column %d %s"
795                  (text-char-description char) char char char pos total
796                  percent col hscroll)))))
797
798 (defun fundamental-mode ()
799   "Major mode not specialized for anything in particular.
800 Other major modes are defined by comparison with this one."
801   (interactive)
802   (kill-all-local-variables))
803
804 ;; XEmacs the following are declared elsewhere
805 ;(defvar read-expression-map (cons 'keymap minibuffer-local-map)
806 ;  "Minibuffer keymap used for reading Lisp expressions.")
807 ;(define-key read-expression-map "\M-\t" 'lisp-complete-symbol)
808
809 ;(put 'eval-expression 'disabled t)
810
811 ;(defvar read-expression-history nil)
812
813 ;; We define this, rather than making `eval' interactive,
814 ;; for the sake of completion of names like eval-region, eval-current-buffer.
815 (defun eval-expression (expression &optional eval-expression-insert-value)
816   "Evaluate EXPRESSION and print value in minibuffer.
817 Value is also consed on to front of the variable `values'.
818 With prefix argument, insert the result to the current buffer."
819   ;(interactive "xEval: ")
820   (interactive
821    (list (read-from-minibuffer "Eval: "
822                                nil read-expression-map t
823                                'read-expression-history)
824          current-prefix-arg))
825   (setq values (cons (eval expression) values))
826   (prin1 (car values)
827          (if eval-expression-insert-value (current-buffer) t)))
828
829 ;; XEmacs -- extra parameter (variant, but equivalent logic)
830 (defun edit-and-eval-command (prompt form &optional history)
831   "Prompting with PROMPT, let user edit FORM and eval result.
832 FORM is a Lisp expression.  Let user edit that expression in
833 the minibuffer, then read and evaluate the result."
834   (let ((form (read-expression prompt
835                                ;; first try to format the thing readably;
836                                ;; and if that fails, print it normally.
837                                (condition-case ()
838                                    (let ((print-readably t))
839                                      (prin1-to-string form))
840                                  (error (prin1-to-string form)))
841                                (or history '(command-history . 1)))))
842     (or history (setq history 'command-history))
843     (if (consp history)
844         (setq history (car history)))
845     (if (eq history t)
846         nil
847       ;; If form was added to the history as a string,
848       ;; get rid of that.  We want only evallable expressions there.
849       (if (stringp (car (symbol-value history)))
850           (set history (cdr (symbol-value history))))
851
852       ;; If form to be redone does not match front of history,
853       ;; add it to the history.
854       (or (equal form (car (symbol-value history)))
855           (set history (cons form (symbol-value history)))))
856     (eval form)))
857
858 (defun repeat-complex-command (arg)
859   "Edit and re-evaluate last complex command, or ARGth from last.
860 A complex command is one which used the minibuffer.
861 The command is placed in the minibuffer as a Lisp form for editing.
862 The result is executed, repeating the command as changed.
863 If the command has been changed or is not the most recent previous command
864 it is added to the front of the command history.
865 You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
866 to get different commands to edit and resubmit."
867   (interactive "p")
868   ;; XEmacs: It looks like our version is better -sb
869   (let ((print-level nil))
870     (edit-and-eval-command "Redo: "
871                            (or (nth (1- arg) command-history)
872                                (error ""))
873                            (cons 'command-history arg))))
874
875 ;; XEmacs: Functions moved to minibuf.el
876 ;; previous-matching-history-element
877 ;; next-matching-history-element
878 ;; next-history-element
879 ;; previous-history-element
880 ;; next-complete-history-element
881 ;; previous-complete-history-element
882 \f
883 (defun goto-line (line)
884   "Goto line LINE, counting from line 1 at beginning of buffer."
885   (interactive "NGoto line: ")
886   (setq line (prefix-numeric-value line))
887   (save-restriction
888     (widen)
889     (goto-char 1)
890     (if (eq selective-display t)
891         (re-search-forward "[\n\C-m]" nil 'end (1- line))
892       (forward-line (1- line)))))
893
894 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
895 (define-function 'advertised-undo 'undo)
896
897 (defun undo (&optional count)
898   "Undo some previous changes.
899 Repeat this command to undo more changes.
900 A numeric argument serves as a repeat count."
901   (interactive "*p")
902   ;; If we don't get all the way through, make last-command indicate that
903   ;; for the following command.
904   (setq this-command t)
905   (let ((modified (buffer-modified-p))
906         (recent-save (recent-auto-save-p)))
907     (or (eq (selected-window) (minibuffer-window))
908         (display-message 'command "Undo!"))
909     (or (and (eq last-command 'undo)
910              (eq (current-buffer) last-undo-buffer)) ; XEmacs
911         (progn (undo-start)
912                (undo-more 1)))
913     (undo-more (or count 1))
914     ;; Don't specify a position in the undo record for the undo command.
915     ;; Instead, undoing this should move point to where the change is.
916     (let ((tail buffer-undo-list)
917           done)
918       (while (and tail (not done) (not (null (car tail))))
919         (if (integerp (car tail))
920             (progn
921               (setq done t)
922               (setq buffer-undo-list (delq (car tail) buffer-undo-list))))
923         (setq tail (cdr tail))))
924     (and modified (not (buffer-modified-p))
925          (delete-auto-save-file-if-necessary recent-save)))
926   ;; If we do get all the way through, make this-command indicate that.
927   (setq this-command 'undo))
928
929 (defvar pending-undo-list nil
930   "Within a run of consecutive undo commands, list remaining to be undone.")
931
932 (defvar last-undo-buffer nil)   ; XEmacs
933
934 (defun undo-start ()
935   "Set `pending-undo-list' to the front of the undo list.
936 The next call to `undo-more' will undo the most recently made change."
937   (if (eq buffer-undo-list t)
938       (error "No undo information in this buffer"))
939   (setq pending-undo-list buffer-undo-list))
940
941 (defun undo-more (count)
942   "Undo back N undo-boundaries beyond what was already undone recently.
943 Call `undo-start' to get ready to undo recent changes,
944 then call `undo-more' one or more times to undo them."
945   (or pending-undo-list
946       (error "No further undo information"))
947   (setq pending-undo-list (primitive-undo count pending-undo-list)
948         last-undo-buffer (current-buffer)))     ; XEmacs
949
950 ;; XEmacs
951 (defun call-with-transparent-undo (fn &rest args)
952   "Apply FN to ARGS, and then undo all changes made by FN to the current
953 buffer.  The undo records are processed even if FN returns non-locally.
954 There is no trace of the changes made by FN in the buffer's undo history.
955
956 You can use this in a write-file-hooks function with continue-save-buffer
957 to make the contents of a disk file differ from its in-memory buffer."
958   (let ((buffer-undo-list nil)
959         ;; Kludge to prevent undo list truncation:
960         (undo-high-threshold -1)
961         (undo-threshold -1)
962         (obuffer (current-buffer)))
963     (unwind-protect
964         (apply fn args)
965       ;; Go to the buffer we will restore and make it writable:
966       (set-buffer obuffer)
967       (save-excursion
968         (let ((buffer-read-only nil))
969           (save-restriction
970             (widen)
971             ;; Perform all undos, with further undo logging disabled:
972             (let ((tail buffer-undo-list))
973               (setq buffer-undo-list t)
974               (while tail
975                 (setq tail (primitive-undo (length tail) tail))))))))))
976
977 ;; XEmacs: The following are in other files
978 ;; shell-command-history
979 ;; shell-command-switch
980 ;; shell-command
981 ;; shell-command-sentinel
982
983 \f
984 (defconst universal-argument-map
985   (let ((map (make-sparse-keymap)))
986     (set-keymap-default-binding map 'universal-argument-other-key)
987     ;FSFmacs (define-key map [switch-frame] nil)
988     (define-key map [(t)] 'universal-argument-other-key)
989     (define-key map [(meta t)] 'universal-argument-other-key)
990     (define-key map [(control u)] 'universal-argument-more)
991     (define-key map [?-] 'universal-argument-minus)
992     (define-key map [?0] 'digit-argument)
993     (define-key map [?1] 'digit-argument)
994     (define-key map [?2] 'digit-argument)
995     (define-key map [?3] 'digit-argument)
996     (define-key map [?4] 'digit-argument)
997     (define-key map [?5] 'digit-argument)
998     (define-key map [?6] 'digit-argument)
999     (define-key map [?7] 'digit-argument)
1000     (define-key map [?8] 'digit-argument)
1001     (define-key map [?9] 'digit-argument)
1002     map)
1003   "Keymap used while processing \\[universal-argument].")
1004
1005 (defvar universal-argument-num-events nil
1006   "Number of argument-specifying events read by `universal-argument'.
1007 `universal-argument-other-key' uses this to discard those events
1008 from (this-command-keys), and reread only the final command.")
1009
1010 (defun universal-argument ()
1011   "Begin a numeric argument for the following command.
1012 Digits or minus sign following \\[universal-argument] make up the numeric argument.
1013 \\[universal-argument] following the digits or minus sign ends the argument.
1014 \\[universal-argument] without digits or minus sign provides 4 as argument.
1015 Repeating \\[universal-argument] without digits or minus sign
1016  multiplies the argument by 4 each time."
1017   (interactive)
1018   (setq prefix-arg (list 4))
1019   (setq zmacs-region-stays t)   ; XEmacs
1020   (setq universal-argument-num-events (length (this-command-keys)))
1021   (setq overriding-terminal-local-map universal-argument-map))
1022
1023 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
1024 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
1025 (defun universal-argument-more (arg)
1026   (interactive "_P")                    ; XEmacs
1027   (if (consp arg)
1028       (setq prefix-arg (list (* 4 (car arg))))
1029     (setq prefix-arg arg)
1030     (setq overriding-terminal-local-map nil))
1031   (setq universal-argument-num-events (length (this-command-keys))))
1032
1033 (defun negative-argument (arg)
1034   "Begin a negative numeric argument for the next command.
1035 \\[universal-argument] following digits or minus sign ends the argument."
1036   (interactive "_P")                    ; XEmacs
1037   (cond ((integerp arg)
1038           (setq prefix-arg (- arg)))
1039          ((eq arg '-)
1040           (setq prefix-arg nil))
1041          (t
1042           (setq prefix-arg '-)))
1043   (setq universal-argument-num-events (length (this-command-keys)))
1044   (setq overriding-terminal-local-map universal-argument-map))
1045
1046 ;; XEmacs:  This function not synched with FSF
1047 (defun digit-argument (arg)
1048   "Part of the numeric argument for the next command.
1049 \\[universal-argument] following digits or minus sign ends the argument."
1050   (interactive "_P")                    ; XEmacs
1051   (let* ((event last-command-event)
1052          (key (and (key-press-event-p event)
1053                    (event-key event)))
1054          (digit (and key (characterp key) (>= key ?0) (<= key ?9)
1055                      (- key ?0))))
1056     (if (null digit)
1057         (universal-argument-other-key arg)
1058       (cond ((integerp arg)
1059              (setq prefix-arg (+ (* arg 10)
1060                                  (if (< arg 0) (- digit) digit))))
1061             ((eq arg '-)
1062              ;; Treat -0 as just -, so that -01 will work.
1063              (setq prefix-arg (if (zerop digit) '- (- digit))))
1064             (t
1065              (setq prefix-arg digit)))
1066       (setq universal-argument-num-events (length (this-command-keys)))
1067       (setq overriding-terminal-local-map universal-argument-map))))
1068
1069 ;; For backward compatibility, minus with no modifiers is an ordinary
1070 ;; command if digits have already been entered.
1071 (defun universal-argument-minus (arg)
1072   (interactive "_P") ; XEmacs
1073   (if (integerp arg)
1074       (universal-argument-other-key arg)
1075     (negative-argument arg)))
1076
1077 ;; Anything else terminates the argument and is left in the queue to be
1078 ;; executed as a command.
1079 (defun universal-argument-other-key (arg)
1080   (interactive "_P")                    ; XEmacs
1081   (setq prefix-arg arg)
1082   (let* ((key (this-command-keys))
1083          ;; FSF calls silly function `listify-key-sequence' here.
1084           (keylist (append key nil)))
1085     (setq unread-command-events
1086            (append (nthcdr universal-argument-num-events keylist)
1087                    unread-command-events)))
1088   (reset-this-command-lengths)
1089   (setq overriding-terminal-local-map nil))
1090
1091 \f
1092 ;; XEmacs -- keep zmacs-region active.
1093 (defun forward-to-indentation (count)
1094   "Move forward COUNT lines and position at first nonblank character."
1095   (interactive "_p")
1096   (forward-line count)
1097   (skip-chars-forward " \t"))
1098
1099 (defun backward-to-indentation (count)
1100   "Move backward COUNT lines and position at first nonblank character."
1101   (interactive "_p")
1102   (forward-line (- count))
1103   (skip-chars-forward " \t"))
1104
1105 (defcustom kill-whole-line nil
1106   "*Control when and whether `kill-line' removes entire lines.
1107 Note: This only applies when `kill-line' is called interactively;
1108 otherwise, it behaves \"historically\".
1109
1110 If `always', `kill-line' with no arg always kills the whole line,
1111 wherever point is in the line. (If you want to just kill to the end
1112 of the line, use \\[historical-kill-line].)
1113
1114 If not `always' but non-nil, `kill-line' with no arg kills the whole
1115 line if point is at the beginning, and otherwise behaves historically.
1116
1117 If nil, `kill-line' behaves historically."
1118   :type '(radio (const :tag "Kill to end of line" nil)
1119                 (const :tag "Kill whole line" always)
1120                 (const
1121                  :tag "Kill whole line at beginning, otherwise end of line" t))
1122   :group 'killing)
1123
1124 (defun historical-kill-line (&optional arg)
1125   "Same as `kill-line' but ignores value of `kill-whole-line'."
1126   (interactive "*P")
1127   (let ((kill-whole-line nil))
1128     (if (interactive-p)
1129         (call-interactively 'kill-line)
1130       (kill-line arg))))
1131
1132 (defun kill-line (&optional arg)
1133   "Kill the rest of the current line, or the entire line.
1134 If no nonblanks there, kill thru newline.
1135 If called interactively, may kill the entire line; see `kill-whole-line'.
1136 when given no argument at the beginning of a line.
1137 With prefix argument, kill that many lines from point.
1138 Negative arguments kill lines backward.
1139
1140 When calling from a program, nil means \"no arg\",
1141 a number counts as a prefix arg."
1142   (interactive "*P")
1143   (kill-region (if (and (interactive-p)
1144                         (not arg)
1145                         (eq kill-whole-line 'always))
1146                    (save-excursion
1147                      (beginning-of-line)
1148                      (point))
1149                  (point))
1150                ;; Don't shift point before doing the delete; that way,
1151                ;; undo will record the right position of point.
1152 ;; FSF
1153 ;              ;; It is better to move point to the other end of the kill
1154 ;              ;; before killing.  That way, in a read-only buffer, point
1155 ;              ;; moves across the text that is copied to the kill ring.
1156 ;              ;; The choice has no effect on undo now that undo records
1157 ;              ;; the value of point from before the command was run.
1158 ;              (progn
1159                (save-excursion
1160                  (if arg
1161                      (forward-line (prefix-numeric-value arg))
1162                    (if (eobp)
1163                        (signal 'end-of-buffer nil))
1164                    (if (or (looking-at "[ \t]*$")
1165                            (and (interactive-p)
1166                                 (or (eq kill-whole-line 'always)
1167                                     (and kill-whole-line (bolp)))))
1168                        (forward-line 1)
1169                      (end-of-line)))
1170                  (point))))
1171
1172 ;; XEmacs
1173 (defun backward-kill-line nil
1174   "Kill back to the beginning of the line."
1175   (interactive)
1176   (let ((point (point)))
1177     (beginning-of-line nil)
1178     (kill-region (point) point)))
1179
1180 \f
1181 ;;;; Window system cut and paste hooks.
1182 ;;;
1183 ;;; I think that kill-hooks is a better name and more general mechanism
1184 ;;; than interprogram-cut-function (from FSFmacs).  I don't like the behavior
1185 ;;; of interprogram-paste-function: ^Y should always come from the kill ring,
1186 ;;; not the X selection.  But if that were provided, it should be called (and
1187 ;;; behave as) yank-hooks instead.  -- jwz
1188
1189 ;; [... code snipped ...]
1190
1191 (defcustom kill-hooks nil
1192   "*Functions run when something is added to the XEmacs kill ring.
1193 These functions are called with one argument, the string most recently
1194 cut or copied.  You can use this to, for example, make the most recent
1195 kill become the X Clipboard selection."
1196   :type 'hook
1197   :group 'killing)
1198
1199 ;;; `kill-hooks' seems not sufficient because
1200 ;;; `interprogram-cut-function' requires more variable about to rotate
1201 ;;; the cut buffers.  I'm afraid to change interface of `kill-hooks',
1202 ;;; so I add it. (1997-11-03 by MORIOKA Tomohiko)
1203
1204 (defcustom interprogram-cut-function 'own-clipboard
1205   "Function to call to make a killed region available to other programs.
1206
1207 Most window systems provide some sort of facility for cutting and
1208 pasting text between the windows of different programs.
1209 This variable holds a function that Emacs calls whenever text
1210 is put in the kill ring, to make the new kill available to other
1211 programs.
1212
1213 The function takes one or two arguments.
1214 The first argument, TEXT, is a string containing
1215 the text which should be made available.
1216 The second, PUSH, if non-nil means this is a \"new\" kill;
1217 nil means appending to an \"old\" kill."
1218   :type '(radio (function-item :tag "Send to Clipboard"
1219                                :format "%t\n"
1220                                own-clipboard)
1221                 (const :tag "None" nil)
1222                 (function :tag "Other"))
1223   :group 'killing)
1224
1225 (defcustom interprogram-paste-function 'get-clipboard
1226   "Function to call to get text cut from other programs.
1227
1228 Most window systems provide some sort of facility for cutting and
1229 pasting text between the windows of different programs.
1230 This variable holds a function that Emacs calls to obtain
1231 text that other programs have provided for pasting.
1232
1233 The function should be called with no arguments.  If the function
1234 returns nil, then no other program has provided such text, and the top
1235 of the Emacs kill ring should be used.  If the function returns a
1236 string, that string should be put in the kill ring as the latest kill.
1237
1238 Note that the function should return a string only if a program other
1239 than Emacs has provided a string for pasting; if Emacs provided the
1240 most recent string, the function should return nil.  If it is
1241 difficult to tell whether Emacs or some other program provided the
1242 current string, it is probably good enough to return nil if the string
1243 is equal (according to `string=') to the last text Emacs provided."
1244   :type '(radio (function-item :tag "Get from Clipboard"
1245                                :format "%t\n"
1246                                get-clipboard)
1247                 (const :tag "None" nil)
1248                 (function :tag "Other"))
1249   :group 'killing)
1250
1251 \f
1252 ;;;; The kill ring data structure.
1253
1254 (defvar kill-ring nil
1255   "List of killed text sequences.
1256 Since the kill ring is supposed to interact nicely with cut-and-paste
1257 facilities offered by window systems, use of this variable should
1258 interact nicely with `interprogram-cut-function' and
1259 `interprogram-paste-function'.  The functions `kill-new',
1260 `kill-append', and `current-kill' are supposed to implement this
1261 interaction; you may want to use them instead of manipulating the kill
1262 ring directly.")
1263
1264 (defcustom kill-ring-max 30
1265   "*Maximum length of kill ring before oldest elements are thrown away."
1266   :type 'integer
1267   :group 'killing)
1268
1269 (defvar kill-ring-yank-pointer nil
1270   "The tail of the kill ring whose car is the last thing yanked.")
1271
1272 (defun kill-new (string &optional replace)
1273   "Make STRING the latest kill in the kill ring.
1274 Set `kill-ring-yank-pointer' to point to it.
1275 Run `kill-hooks'.
1276 Optional second argument REPLACE non-nil means that STRING will replace
1277 the front of the kill ring, rather than being added to the list."
1278 ;  (and (fboundp 'menu-bar-update-yank-menu)
1279 ;       (menu-bar-update-yank-menu string (and replace (car kill-ring))))
1280   (if replace
1281       (setcar kill-ring string)
1282     (setq kill-ring (cons string kill-ring))
1283     (if (> (length kill-ring) kill-ring-max)
1284         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
1285   (setq kill-ring-yank-pointer kill-ring)
1286   (if interprogram-cut-function
1287       (funcall interprogram-cut-function string (not replace)))
1288   (run-hook-with-args 'kill-hooks string))
1289
1290 (defun kill-append (string before-p)
1291   "Append STRING to the end of the latest kill in the kill ring.
1292 If BEFORE-P is non-nil, prepend STRING to the kill.
1293 Run `kill-hooks'."
1294   (kill-new (if before-p
1295                 (concat string (car kill-ring))
1296               (concat (car kill-ring) string)) t))
1297
1298 (defun current-kill (n &optional do-not-move)
1299   "Rotate the yanking point by N places, and then return that kill.
1300 If N is zero, `interprogram-paste-function' is set, and calling it
1301 returns a string, then that string is added to the front of the
1302 kill ring and returned as the latest kill.
1303 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
1304 yanking point\; just return the Nth kill forward."
1305   (let ((interprogram-paste (and (= n 0)
1306                                  interprogram-paste-function
1307                                  (funcall interprogram-paste-function))))
1308     (if interprogram-paste
1309         (progn
1310           ;; Disable the interprogram cut function when we add the new
1311           ;; text to the kill ring, so Emacs doesn't try to own the
1312           ;; selection, with identical text.
1313           (let ((interprogram-cut-function nil))
1314             (kill-new interprogram-paste))
1315           interprogram-paste)
1316       (or kill-ring (error "Kill ring is empty"))
1317       (let* ((tem (nthcdr (mod (- n (length kill-ring-yank-pointer))
1318                                (length kill-ring))
1319                           kill-ring)))
1320         (or do-not-move
1321             (setq kill-ring-yank-pointer tem))
1322         (car tem)))))
1323
1324
1325 \f
1326 ;;;; Commands for manipulating the kill ring.
1327
1328 ;; In FSF killing read-only text just pastes it into kill-ring.  Which
1329 ;; is a very bad idea -- see Jamie's comment below.
1330
1331 ;(defvar kill-read-only-ok nil
1332 ;  "*Non-nil means don't signal an error for killing read-only text.")
1333
1334 (defun kill-region (start end &optional verbose) ; verbose is XEmacs addition
1335   "Kill between point and mark.
1336 The text is deleted but saved in the kill ring.
1337 The command \\[yank] can retrieve it from there.
1338 \(If you want to kill and then yank immediately, use \\[copy-region-as-kill].)
1339
1340 This is the primitive for programs to kill text (as opposed to deleting it).
1341 Supply two arguments, character numbers indicating the stretch of text
1342  to be killed.
1343 Any command that calls this function is a \"kill command\".
1344 If the previous command was also a kill command,
1345 the text killed this time appends to the text killed last time
1346 to make one entry in the kill ring."
1347   (interactive "*r\np")
1348 ;  (interactive
1349 ;   (let ((region-hack (and zmacs-regions (eq last-command 'yank))))
1350 ;     ;; This lets "^Y^W" work.  I think this is dumb, but zwei did it.
1351 ;     (if region-hack (zmacs-activate-region))
1352 ;     (prog1
1353 ;        (list (point) (mark) current-prefix-arg)
1354 ;       (if region-hack (zmacs-deactivate-region)))))
1355   ;; start and end can be markers but the rest of this function is
1356   ;; written as if they are only integers
1357   (if (markerp start) (setq start (marker-position start)))
1358   (if (markerp end) (setq end (marker-position end)))
1359   (or (and start end) (if zmacs-regions ;; rewritten for I18N3 snarfing
1360                         (error "The region is not active now")
1361                       (error "The mark is not set now")))
1362   (if verbose (if buffer-read-only
1363                   (lmessage 'command "Copying %d characters"
1364                             (- (max start end) (min start end)))
1365                 (lmessage 'command "Killing %d characters"
1366                           (- (max start end) (min start end)))))
1367   (cond
1368
1369    ;; I don't like this large change in behavior -- jwz
1370    ;; Read-Only text means it shouldn't be deleted, so I'm restoring
1371    ;; this code, but only for text-properties and not full extents. -sb
1372    ;; If the buffer is read-only, we should beep, in case the person
1373    ;; just isn't aware of this.  However, there's no harm in putting
1374    ;; the region's text in the kill ring, anyway.
1375    ((or (and buffer-read-only (not inhibit-read-only))
1376         (text-property-not-all (min start end) (max start end) 'read-only nil))
1377    ;; This is redundant.
1378    ;; (if verbose (message "Copying %d characters"
1379    ;;                    (- (max start end) (min start end))))
1380     (copy-region-as-kill start end)
1381    ;; ;; This should always barf, and give us the correct error.
1382    ;; (if kill-read-only-ok
1383    ;;     (message "Read only text copied to kill ring")
1384     (setq this-command 'kill-region)
1385     (barf-if-buffer-read-only)
1386     (signal 'buffer-read-only (list (current-buffer))))
1387
1388    ;; In certain cases, we can arrange for the undo list and the kill
1389    ;; ring to share the same string object.  This code does that.
1390    ((not (or (eq buffer-undo-list t)
1391              (eq last-command 'kill-region)
1392              ;; Use = since positions may be numbers or markers.
1393              (= start end)))
1394     ;; Don't let the undo list be truncated before we can even access it.
1395     ;; FSF calls this `undo-strong-limit'
1396     (let ((undo-high-threshold (+ (- end start) 100))
1397           ;(old-list buffer-undo-list)
1398           tail)
1399       (delete-region start end)
1400       ;; Search back in buffer-undo-list for this string,
1401       ;; in case a change hook made property changes.
1402       (setq tail buffer-undo-list)
1403       (while (and tail
1404                   (not (stringp (car-safe (car-safe tail))))) ; XEmacs
1405         (pop tail))
1406       ;; Take the same string recorded for undo
1407       ;; and put it in the kill-ring.
1408       (and tail
1409            (kill-new (car (car tail))))))
1410
1411    (t
1412     ;; if undo is not kept, grab the string then delete it (which won't
1413     ;; add another string to the undo list).
1414     (copy-region-as-kill start end)
1415     (delete-region start end)))
1416   (setq this-command 'kill-region))
1417
1418 ;; copy-region-as-kill no longer sets this-command, because it's confusing
1419 ;; to get two copies of the text when the user accidentally types M-w and
1420 ;; then corrects it with the intended C-w.
1421 (defun copy-region-as-kill (start end)
1422   "Save the region as if killed, but don't kill it.
1423 Run `kill-hooks'."
1424   (interactive "r")
1425   (if (eq last-command 'kill-region)
1426       (kill-append (buffer-substring start end) (< end start))
1427     (kill-new (buffer-substring start end)))
1428   nil)
1429
1430 (defun kill-ring-save (start end)
1431   "Save the region as if killed, but don't kill it.
1432 This command is similar to `copy-region-as-kill', except that it gives
1433 visual feedback indicating the extent of the region being copied."
1434   (interactive "r")
1435   (copy-region-as-kill start end)
1436   ;; copy before delay, for xclipboard's benefit
1437   (if (interactive-p)
1438       (let ((other-end (if (= (point) start) end start))
1439             (opoint (point))
1440             ;; Inhibit quitting so we can make a quit here
1441             ;; look like a C-g typed as a command.
1442             (inhibit-quit t))
1443         (if (pos-visible-in-window-p other-end (selected-window))
1444             (progn
1445               ;; FSF (I'm not sure what this does -sb)
1446 ;             ;; Swap point and mark.
1447 ;             (set-marker (mark-marker) (point) (current-buffer))
1448               (goto-char other-end)
1449               (sit-for 1)
1450 ;             ;; Swap back.
1451 ;             (set-marker (mark-marker) other-end (current-buffer))
1452               (goto-char opoint)
1453               ;; If user quit, deactivate the mark
1454               ;; as C-g would as a command.
1455               (and quit-flag (mark)
1456                    (zmacs-deactivate-region)))
1457           ;; too noisy. -- jwz
1458 ;         (let* ((killed-text (current-kill 0))
1459 ;                (message-len (min (length killed-text) 40)))
1460 ;           (if (= (point) start)
1461 ;               ;; Don't say "killed"; that is misleading.
1462 ;               (message "Saved text until \"%s\""
1463 ;                       (substring killed-text (- message-len)))
1464 ;             (message "Saved text from \"%s\""
1465 ;                     (substring killed-text 0 message-len))))
1466           ))))
1467
1468 (defun append-next-kill ()
1469   "Cause following command, if it kills, to append to previous kill."
1470   ;; XEmacs
1471   (interactive "_")
1472   (if (interactive-p)
1473       (progn
1474         (setq this-command 'kill-region)
1475         (display-message 'command
1476           "If the next command is a kill, it will append"))
1477     (setq last-command 'kill-region)))
1478
1479 (defun yank-pop (arg)
1480   "Replace just-yanked stretch of killed text with a different stretch.
1481 This command is allowed only immediately after a `yank' or a `yank-pop'.
1482 At such a time, the region contains a stretch of reinserted
1483 previously-killed text.  `yank-pop' deletes that text and inserts in its
1484 place a different stretch of killed text.
1485
1486 With no argument, the previous kill is inserted.
1487 With argument N, insert the Nth previous kill.
1488 If N is negative, this is a more recent kill.
1489
1490 The sequence of kills wraps around, so that after the oldest one
1491 comes the newest one."
1492   (interactive "*p")
1493   (if (not (eq last-command 'yank))
1494       (error "Previous command was not a yank"))
1495   (setq this-command 'yank)
1496   (let ((inhibit-read-only t)
1497         (before (< (point) (mark t))))
1498     (delete-region (point) (mark t))
1499     ;;(set-marker (mark-marker) (point) (current-buffer))
1500     (set-mark (point))
1501     (insert (current-kill arg))
1502     (if before
1503         ;; This is like exchange-point-and-mark, but doesn't activate the mark.
1504         ;; It is cleaner to avoid activation, even though the command
1505         ;; loop would deactivate the mark because we inserted text.
1506         (goto-char (prog1 (mark t)
1507                      (set-marker (mark-marker t) (point) (current-buffer))))))
1508   nil)
1509
1510
1511 (defun yank (&optional arg)
1512   "Reinsert the last stretch of killed text.
1513 More precisely, reinsert the stretch of killed text most recently
1514 killed OR yanked.  Put point at end, and set mark at beginning.
1515 With just C-u as argument, same but put point at beginning (and mark at end).
1516 With argument N, reinsert the Nth most recently killed stretch of killed
1517 text.
1518 See also the command \\[yank-pop]."
1519   (interactive "*P")
1520   ;; If we don't get all the way through, make last-command indicate that
1521   ;; for the following command.
1522   (setq this-command t)
1523   (push-mark (point))
1524   (insert (current-kill (cond
1525                          ((listp arg) 0)
1526                          ((eq arg '-) -1)
1527                          (t (1- arg)))))
1528   (if (consp arg)
1529       ;; This is like exchange-point-and-mark, but doesn't activate the mark.
1530       ;; It is cleaner to avoid activation, even though the command
1531       ;; loop would deactivate the mark because we inserted text.
1532       ;; (But it's an unnecessary kludge in XEmacs.)
1533       ;(goto-char (prog1 (mark t)
1534                    ;(set-marker (mark-marker) (point) (current-buffer)))))
1535       (exchange-point-and-mark t))
1536   ;; If we do get all the way thru, make this-command indicate that.
1537   (setq this-command 'yank)
1538   nil)
1539
1540 (defun rotate-yank-pointer (arg)
1541   "Rotate the yanking point in the kill ring.
1542 With argument, rotate that many kills forward (or backward, if negative)."
1543   (interactive "p")
1544   (current-kill arg))
1545
1546 \f
1547 (defun insert-buffer (buffer)
1548   "Insert after point the contents of BUFFER.
1549 Puts mark after the inserted text.
1550 BUFFER may be a buffer or a buffer name."
1551   (interactive
1552    (list
1553     (progn
1554       (barf-if-buffer-read-only)
1555       (read-buffer "Insert buffer: "
1556                    ;; XEmacs: we have different args
1557                    (other-buffer (current-buffer) nil t)
1558                    t))))
1559   (or (bufferp buffer)
1560       (setq buffer (get-buffer buffer)))
1561   (let (start end newmark)
1562     (save-excursion
1563       (save-excursion
1564         (set-buffer buffer)
1565         (setq start (point-min) end (point-max)))
1566       (insert-buffer-substring buffer start end)
1567       (setq newmark (point)))
1568     (push-mark newmark))
1569   nil)
1570
1571 (defun append-to-buffer (buffer start end)
1572   "Append to specified buffer the text of the region.
1573 It is inserted into that buffer before its point.
1574
1575 When calling from a program, give three arguments:
1576 BUFFER (or buffer name), START and END.
1577 START and END specify the portion of the current buffer to be copied."
1578   (interactive
1579    ;; XEmacs: we have different args to other-buffer
1580    (list (read-buffer "Append to buffer: " (other-buffer (current-buffer)
1581                                                          nil t))
1582          (region-beginning) (region-end)))
1583   (let ((oldbuf (current-buffer)))
1584     (save-excursion
1585       (set-buffer (get-buffer-create buffer))
1586       (insert-buffer-substring oldbuf start end))))
1587
1588 (defun prepend-to-buffer (buffer start end)
1589   "Prepend to specified buffer the text of the region.
1590 It is inserted into that buffer after its point.
1591
1592 When calling from a program, give three arguments:
1593 BUFFER (or buffer name), START and END.
1594 START and END specify the portion of the current buffer to be copied."
1595   (interactive "BPrepend to buffer: \nr")
1596   (let ((oldbuf (current-buffer)))
1597     (save-excursion
1598       (set-buffer (get-buffer-create buffer))
1599       (save-excursion
1600         (insert-buffer-substring oldbuf start end)))))
1601
1602 (defun copy-to-buffer (buffer start end)
1603   "Copy to specified buffer the text of the region.
1604 It is inserted into that buffer, replacing existing text there.
1605
1606 When calling from a program, give three arguments:
1607 BUFFER (or buffer name), START and END.
1608 START and END specify the portion of the current buffer to be copied."
1609   (interactive "BCopy to buffer: \nr")
1610   (let ((oldbuf (current-buffer)))
1611     (save-excursion
1612       (set-buffer (get-buffer-create buffer))
1613       (erase-buffer)
1614       (save-excursion
1615         (insert-buffer-substring oldbuf start end)))))
1616 \f
1617 ;FSFmacs
1618 ;(put 'mark-inactive 'error-conditions '(mark-inactive error))
1619 ;(put 'mark-inactive 'error-message "The mark is not active now")
1620
1621 (defun mark (&optional force buffer)
1622   "Return this buffer's mark value as integer, or nil if no mark.
1623
1624 If `zmacs-regions' is true, then this returns nil unless the region is
1625 currently in the active (highlighted) state.  With an argument of t, this
1626 returns the mark (if there is one) regardless of the active-region state.
1627 You should *generally* not use the mark unless the region is active, if
1628 the user has expressed a preference for the active-region model.
1629
1630 If you are using this in an editing command, you are most likely making
1631 a mistake; see the documentation of `set-mark'."
1632   (setq buffer (decode-buffer buffer))
1633 ;FSFmacs version:
1634 ;  (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
1635 ;      (marker-position (mark-marker))
1636 ;    (signal 'mark-inactive nil)))
1637   (let ((m (mark-marker force buffer)))
1638     (and m (marker-position m))))
1639
1640 ;;;#### FSFmacs
1641 ;;; Many places set mark-active directly, and several of them failed to also
1642 ;;; run deactivate-mark-hook.  This shorthand should simplify.
1643 ;(defsubst deactivate-mark ()
1644 ;  "Deactivate the mark by setting `mark-active' to nil.
1645 ;\(That makes a difference only in Transient Mark mode.)
1646 ;Also runs the hook `deactivate-mark-hook'."
1647 ;  (if transient-mark-mode
1648 ;      (progn
1649 ;       (setq mark-active nil)
1650 ;       (run-hooks 'deactivate-mark-hook))))
1651
1652 (defun set-mark (pos &optional buffer)
1653   "Set this buffer's mark to POS.  Don't use this function!
1654 That is to say, don't use this function unless you want
1655 the user to see that the mark has moved, and you want the previous
1656 mark position to be lost.
1657
1658 Normally, when a new mark is set, the old one should go on the stack.
1659 This is why most applications should use `push-mark', not `set-mark'.
1660
1661 Novice Emacs Lisp programmers often try to use the mark for the wrong
1662 purposes.  The mark saves a location for the user's convenience.
1663 Most editing commands should not alter the mark.
1664 To remember a location for internal use in the Lisp program,
1665 store it in a Lisp variable.  Example:
1666
1667    (let ((start (point))) (forward-line 1) (delete-region start (point)))."
1668
1669   (setq buffer (decode-buffer buffer))
1670   (set-marker (mark-marker t buffer) pos buffer))
1671 ;; FSF
1672 ;  (if pos
1673 ;     (progn
1674 ;       (setq mark-active t)
1675 ;       (run-hooks 'activate-mark-hook)
1676 ;       (set-marker (mark-marker) pos (current-buffer)))
1677 ;    ;; Normally we never clear mark-active except in Transient Mark mode.
1678 ;    ;; But when we actually clear out the mark value too,
1679 ;    ;; we must clear mark-active in any mode.
1680 ;    (setq mark-active nil)
1681 ;    (run-hooks 'deactivate-mark-hook)
1682 ;    (set-marker (mark-marker) nil)))
1683
1684 (defvar mark-ring nil
1685   "The list of former marks of the current buffer, most recent first.
1686 This variable is automatically buffer-local.")
1687 (make-variable-buffer-local 'mark-ring)
1688 (put 'mark-ring 'permanent-local t)
1689
1690 (defvar dont-record-current-mark nil
1691   "If set to t, the current mark value should not be recorded on the mark ring.
1692 This is set by commands that manipulate the mark incidentally, to avoid
1693 cluttering the mark ring unnecessarily.  Under most circumstances, you do
1694 not need to set this directly; it is automatically reset each time
1695 `push-mark' is called, according to `mark-ring-unrecorded-commands'.  This
1696 variable is automatically buffer-local.")
1697 (make-variable-buffer-local 'dont-record-current-mark)
1698 (put 'dont-record-current-mark 'permanent-local t)
1699
1700 ;; a conspiracy between push-mark and handle-pre-motion-command
1701 (defvar in-shifted-motion-command nil)
1702
1703 (defcustom mark-ring-unrecorded-commands '(shifted-motion-commands
1704                                            yank
1705                                            mark-beginning-of-buffer
1706                                            mark-bob
1707                                            mark-defun
1708                                            mark-end-of-buffer
1709                                            mark-end-of-line
1710                                            mark-end-of-sentence
1711                                            mark-eob
1712                                            mark-marker
1713                                            mark-page
1714                                            mark-paragraph
1715                                            mark-sexp
1716                                            mark-whole-buffer
1717                                            mark-word)
1718   "*List of commands whose marks should not be recorded on the mark stack.
1719 Many commands set the mark as part of their action.  Normally, all such
1720 marks get recorded onto the mark stack.  However, this tends to clutter up
1721 the mark stack unnecessarily.  You can control this by putting a command
1722 onto this list.  Then, any marks set by the function will not be recorded.
1723
1724 The special value `shifted-motion-commands' causes marks set as a result
1725 of selection using any shifted motion commands to not be recorded.
1726
1727 The value `yank' affects all yank-like commands, as well as just `yank'."
1728   :type '(repeat (choice (const :tag "shifted motion commands"
1729                                 'shifted-motion-commands)
1730                          (const :tag "functions that select text"
1731                                 :inline t
1732                                 '(mark-beginning-of-buffer
1733                                   mark-bob
1734                                   mark-defun
1735                                   mark-end-of-buffer
1736                                   mark-end-of-line
1737                                   mark-end-of-sentence
1738                                   mark-eob
1739                                   mark-marker
1740                                   mark-page
1741                                   mark-paragraph
1742                                   mark-sexp
1743                                   mark-whole-buffer
1744                                   mark-word))
1745                          (const :tag "functions that paste text"
1746                                 'yank)
1747                          function))
1748   :group 'killing)
1749
1750 (defcustom mark-ring-max 16
1751   "*Maximum size of mark ring.  Start discarding off end if gets this big."
1752   :type 'integer
1753   :group 'killing)
1754
1755 (defvar global-mark-ring nil
1756   "The list of saved global marks, most recent first.")
1757
1758 (defcustom global-mark-ring-max 16
1759   "*Maximum size of global mark ring.  \
1760 Start discarding off end if gets this big."
1761   :type 'integer
1762   :group 'killing)
1763
1764 (defun set-mark-command (arg)
1765   "Set mark at where point is, or jump to mark.
1766 With no prefix argument, set mark, push old mark position on local mark
1767 ring, and push mark on global mark ring.
1768 With argument, jump to mark, and pop a new position for mark off the ring
1769 \(does not affect global mark ring\).
1770
1771 The mark ring is a per-buffer stack of marks, most recent first.  Its
1772 maximum length is controlled by `mark-ring-max'.  Generally, when new
1773 marks are set, the current mark is pushed onto the stack.  You can pop
1774 marks off the stack using \\[universal-argument] \\[set-mark-command].  The term \"ring\" is used because when
1775 you pop a mark off the stack, the current mark value is pushed onto the
1776 far end of the stack.  If this is confusing, just think of the mark ring
1777 as a stack.
1778
1779 Novice Emacs Lisp programmers often try to use the mark for the wrong
1780 purposes.  See the documentation of `set-mark' for more information."
1781   (interactive "P")
1782   (if (null arg)
1783       (push-mark nil nil t)
1784     (if (null (mark t))
1785         (error "No mark set in this buffer")
1786       (if dont-record-current-mark (pop-mark))
1787       (goto-char (mark t))
1788       (pop-mark))))
1789
1790 ;; XEmacs: Extra parameter
1791 (defun push-mark (&optional location nomsg activate-region buffer)
1792   "Set mark at LOCATION (point, by default) and push old mark on mark ring.
1793 If the last global mark pushed was not in the current buffer,
1794 also push LOCATION on the global mark ring.
1795 Display `Mark set' unless the optional second arg NOMSG is non-nil.
1796 Activate mark if optional third arg ACTIVATE-REGION non-nil.
1797
1798 Novice Emacs Lisp programmers often try to use the mark for the wrong
1799 purposes.  See the documentation of `set-mark' for more information."
1800   (setq buffer (decode-buffer buffer)) ; XEmacs
1801   (if (or dont-record-current-mark (null (mark t buffer))) ; XEmacs
1802       nil
1803     ;; The save-excursion / set-buffer is necessary because mark-ring
1804     ;; is a buffer local variable
1805     (save-excursion
1806       (set-buffer buffer)
1807       (setq mark-ring (cons (copy-marker (mark-marker t buffer)) mark-ring))
1808       (if (> (length mark-ring) mark-ring-max)
1809           (progn
1810             (move-marker (car (nthcdr mark-ring-max mark-ring)) nil buffer)
1811             (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))))
1812   (set-mark (or location (point buffer)) buffer)
1813 ; (set-marker (mark-marker) (or location (point)) (current-buffer)) ; FSF
1814   ;; Now push the mark on the global mark ring.
1815   (if (and (not dont-record-current-mark)
1816            (or (null global-mark-ring)
1817                (not (eq (marker-buffer (car global-mark-ring)) buffer))))
1818       ;; The last global mark pushed wasn't in this same buffer.
1819       (progn
1820         (setq global-mark-ring (cons (copy-marker (mark-marker t buffer))
1821                                      global-mark-ring))
1822         (if (> (length global-mark-ring) global-mark-ring-max)
1823             (progn
1824               (move-marker (car (nthcdr global-mark-ring-max global-mark-ring))
1825                            nil buffer)
1826               (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))))
1827   (setq dont-record-current-mark
1828         (not (not (or (and in-shifted-motion-command
1829                            (memq 'shifted-motion-commands
1830                                  mark-ring-unrecorded-commands))
1831                       (memq this-command mark-ring-unrecorded-commands)))))
1832   (or dont-record-current-mark nomsg executing-kbd-macro
1833       (> (minibuffer-depth) 0)
1834       (display-message 'command "Mark set"))
1835   (if activate-region
1836       (progn
1837         (setq zmacs-region-stays t)
1838         (zmacs-activate-region)))
1839 ; (if (or activate (not transient-mark-mode)) ; FSF
1840 ;     (set-mark (mark t))) ; FSF
1841   nil)
1842
1843 (defun pop-mark ()
1844   "Pop off mark ring into the buffer's actual mark.
1845 Does not set point.  Does nothing if mark ring is empty."
1846   (if mark-ring
1847       (progn
1848         (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker t)))))
1849         (set-mark (car mark-ring))
1850         (move-marker (car mark-ring) nil)
1851         (if (null (mark t)) (ding))
1852         (setq mark-ring (cdr mark-ring)))))
1853
1854 (define-function 'exchange-dot-and-mark 'exchange-point-and-mark)
1855 (defun exchange-point-and-mark (&optional dont-activate-region)
1856   "Put the mark where point is now, and point where the mark is now.
1857 The mark is activated unless DONT-ACTIVATE-REGION is non-nil."
1858   (interactive nil)
1859   (let ((omark (mark t)))
1860     (if (null omark)
1861         (error "No mark set in this buffer"))
1862     (set-mark (point))
1863     (goto-char omark)
1864     (or dont-activate-region (zmacs-activate-region)) ; XEmacs
1865     nil))
1866
1867 ;; XEmacs
1868 (defun mark-something (mark-fn movement-fn arg)
1869   "internal function used by mark-sexp, mark-word, etc."
1870   (let (newmark (pushp t))
1871     (save-excursion
1872       (if (and (eq last-command mark-fn) (mark))
1873           ;; Extend the previous state in the same direction:
1874           (progn
1875             (if (< (mark) (point)) (setq arg (- arg)))
1876             (goto-char (mark))
1877             (setq pushp nil)))
1878       (funcall movement-fn arg)
1879       (setq newmark (point)))
1880     (if pushp
1881         (push-mark newmark nil t)
1882       ;; Do not mess with the mark stack, but merely adjust the previous state:
1883       (set-mark newmark)
1884       (activate-region))))
1885
1886 ;(defun transient-mark-mode (arg)
1887 ;  "Toggle Transient Mark mode.
1888 ;With arg, turn Transient Mark mode on if arg is positive, off otherwise.
1889 ;
1890 ;In Transient Mark mode, when the mark is active, the region is highlighted.
1891 ;Changing the buffer \"deactivates\" the mark.
1892 ;So do certain other operations that set the mark
1893 ;but whose main purpose is something else--for example,
1894 ;incremental search, \\[beginning-of-buffer], and \\[end-of-buffer]."
1895 ;  (interactive "P")
1896 ;  (setq transient-mark-mode
1897 ;       (if (null arg)
1898 ;           (not transient-mark-mode)
1899 ;         (> (prefix-numeric-value arg) 0))))
1900
1901 (defun pop-global-mark ()
1902   "Pop off global mark ring and jump to the top location."
1903   (interactive)
1904   ;; Pop entries which refer to non-existent buffers.
1905   (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
1906     (setq global-mark-ring (cdr global-mark-ring)))
1907   (or global-mark-ring
1908       (error "No global mark set"))
1909   (let* ((marker (car global-mark-ring))
1910          (buffer (marker-buffer marker))
1911          (position (marker-position marker)))
1912     (setq global-mark-ring (nconc (cdr global-mark-ring)
1913                                   (list (car global-mark-ring))))
1914     (set-buffer buffer)
1915     (or (and (>= position (point-min))
1916              (<= position (point-max)))
1917         (widen))
1918     (goto-char position)
1919     (switch-to-buffer buffer)))
1920
1921 \f
1922 (defcustom signal-error-on-buffer-boundary t
1923   "*Non-nil value causes XEmacs to beep or signal an error when certain interactive commands would move point past (point-min) or (point-max).
1924 The commands that honor this variable are
1925
1926 forward-char-command
1927 backward-char-command
1928 next-line
1929 previous-line
1930 scroll-up-command
1931 scroll-down-command"
1932   :type 'boolean
1933   :group 'editing-basics)
1934
1935 ;;; After 8 years of waiting ... -sb
1936 (defcustom next-line-add-newlines nil  ; XEmacs
1937   "*If non-nil, `next-line' inserts newline when the point is at end of buffer.
1938 This behavior used to be the default, and is still default in FSF Emacs.
1939 We think it is an unnecessary and unwanted side-effect."
1940   :type 'boolean
1941   :group 'editing-basics)
1942
1943 (defcustom shifted-motion-keys-select-region t
1944   "*If non-nil, shifted motion keys select text, like in MS Windows.
1945 See also `unshifted-motion-keys-deselect-region'."
1946   :type 'boolean
1947   :group 'editing-basics)
1948
1949 (defcustom unshifted-motion-keys-deselect-region t
1950   "*If non-nil, unshifted motion keys deselect a shifted-motion region.
1951 This only occurs after a region has been selected using shifted motion keys
1952 (not when using the traditional set-mark-then-move method), and has no effect
1953 if `shifted-motion-keys-select-region' is nil."
1954   :type 'boolean
1955   :group 'editing-basics)
1956
1957 (defun handle-pre-motion-command-current-command-is-motion ()
1958   (and (key-press-event-p last-input-event)
1959   (memq (event-key last-input-event)
1960         '(left right up down home end prior next
1961                kp-left kp-right kp-up kp-down
1962                kp-home kp-end kp-prior kp-next))))
1963
1964 (defun handle-pre-motion-command ()
1965   (if
1966       (and
1967        (handle-pre-motion-command-current-command-is-motion)
1968        zmacs-regions
1969        shifted-motion-keys-select-region
1970        (not (region-active-p))
1971        (memq 'shift (event-modifiers last-input-event)))
1972       (let ((in-shifted-motion-command t))
1973         (push-mark nil nil t))))
1974
1975 (defun handle-post-motion-command ()
1976   (if
1977       (and
1978        (handle-pre-motion-command-current-command-is-motion)
1979        zmacs-regions
1980        (region-active-p))
1981       (cond ((memq 'shift (event-modifiers last-input-event))
1982              (if shifted-motion-keys-select-region
1983                  (putf this-command-properties 'shifted-motion-command t))
1984              (setq zmacs-region-stays t))
1985             ((and (getf last-command-properties 'shifted-motion-command)
1986                   unshifted-motion-keys-deselect-region)
1987              (setq zmacs-region-stays nil))
1988             (t
1989              (setq zmacs-region-stays t)))))
1990
1991 (defun forward-char-command (&optional arg buffer)
1992   "Move point right ARG characters (left if ARG negative) in BUFFER.
1993 On attempt to pass end of buffer, stop and signal `end-of-buffer'.
1994 On attempt to pass beginning of buffer, stop and signal `beginning-of-buffer'.
1995 Error signaling is suppressed if `signal-error-on-buffer-boundary'
1996 is nil.  If BUFFER is nil, the current buffer is assumed."
1997   (interactive "_p")
1998   (if signal-error-on-buffer-boundary
1999       (forward-char arg buffer)
2000     (condition-case nil
2001         (forward-char arg buffer)
2002       (beginning-of-buffer nil)
2003       (end-of-buffer nil))))
2004
2005 (defun backward-char-command (&optional arg buffer)
2006   "Move point left ARG characters (right if ARG negative) in BUFFER.
2007 On attempt to pass end of buffer, stop and signal `end-of-buffer'.
2008 On attempt to pass beginning of buffer, stop and signal `beginning-of-buffer'.
2009 Error signaling is suppressed if `signal-error-on-buffer-boundary'
2010 is nil.  If BUFFER is nil, the current buffer is assumed."
2011   (interactive "_p")
2012   (if signal-error-on-buffer-boundary
2013       (backward-char arg buffer)
2014     (condition-case nil
2015         (backward-char arg buffer)
2016       (beginning-of-buffer nil)
2017       (end-of-buffer nil))))
2018
2019 (defun scroll-up-one ()
2020   "Scroll text of current window upward one line.
2021 On attempt to scroll past end of buffer, `end-of-buffer' is signaled.
2022 On attempt to scroll past beginning of buffer, `beginning-of-buffer' is
2023 signaled.
2024
2025 If `signal-error-on-buffer-boundary' is nil, attempts to scroll past buffer
2026 boundaries do not cause an error to be signaled."
2027   (interactive "_")
2028   (scroll-up-command 1))
2029
2030 (defun scroll-up-command (&optional n)
2031   "Scroll current window upward N lines; or near full screen if N is nil.
2032 A near full screen is `next-screen-context-lines' less than a full screen.
2033 Negative N means scroll downward.
2034 When calling from a program, supply a number as argument or nil.
2035 On attempt to scroll past end of buffer, `end-of-buffer' is signaled.
2036 On attempt to scroll past beginning of buffer, `beginning-of-buffer' is
2037 signaled.
2038
2039 If `signal-error-on-buffer-boundary' is nil, attempts to scroll past buffer
2040 boundaries do not cause an error to be signaled."
2041   (interactive "_P")
2042   (if signal-error-on-buffer-boundary
2043       (scroll-up n)
2044     (condition-case nil
2045         (scroll-up n)
2046       (beginning-of-buffer nil)
2047       (end-of-buffer nil))))
2048
2049 (defun scroll-down-one ()
2050   "Scroll text of current window downward one line.
2051 On attempt to scroll past end of buffer, `end-of-buffer' is signaled.
2052 On attempt to scroll past beginning of buffer, `beginning-of-buffer' is
2053 signaled.
2054
2055 If `signal-error-on-buffer-boundary' is nil, attempts to scroll past buffer
2056 boundaries do not cause an error to be signaled."
2057   (interactive "_")
2058   (scroll-down-command 1))
2059
2060 (defun scroll-down-command (&optional n)
2061   "Scroll current window downward N lines; or near full screen if N is nil.
2062 A near full screen is `next-screen-context-lines' less than a full screen.
2063 Negative N means scroll upward.
2064 When calling from a program, supply a number as argument or nil.
2065 On attempt to scroll past end of buffer, `end-of-buffer' is signaled.
2066 On attempt to scroll past beginning of buffer, `beginning-of-buffer' is
2067 signaled.
2068
2069 If `signal-error-on-buffer-boundary' is nil, attempts to scroll past buffer
2070 boundaries do not cause an error to be signaled."
2071   (interactive "_P")
2072   (if signal-error-on-buffer-boundary
2073       (scroll-down n)
2074     (condition-case nil
2075         (scroll-down n)
2076       (beginning-of-buffer nil)
2077       (end-of-buffer nil))))
2078
2079 (defun next-line (count)
2080   "Move cursor vertically down COUNT lines.
2081 If there is no character in the target line exactly under the current column,
2082 the cursor is positioned after the character in that line which spans this
2083 column, or at the end of the line if it is not long enough.
2084
2085 If there is no line in the buffer after this one, behavior depends on the
2086 value of `next-line-add-newlines'.  If non-nil, it inserts a newline character
2087 to create a line, and moves the cursor to that line.  Otherwise it moves the
2088 cursor to the end of the buffer.
2089
2090 The command \\[set-goal-column] can be used to create
2091 a semipermanent goal column to which this command always moves.
2092 Then it does not try to move vertically.  This goal column is stored
2093 in `goal-column', which is nil when there is none.
2094
2095 If you are thinking of using this in a Lisp program, consider
2096 using `forward-line' instead.  It is usually easier to use
2097 and more reliable (no dependence on goal column, etc.)."
2098   (interactive "_p")
2099   (if (and next-line-add-newlines (= count 1))
2100       (let ((opoint (point)))
2101         (end-of-line)
2102         (if (eobp)
2103             (newline 1)
2104           (goto-char opoint)
2105           (line-move count)))
2106     (if (interactive-p)
2107         ;; XEmacs:  Not sure what to do about this.  It's inconsistent. -sb
2108         (condition-case nil
2109             (line-move count)
2110           ((beginning-of-buffer end-of-buffer)
2111            (when signal-error-on-buffer-boundary
2112              (ding nil 'buffer-bound))))
2113       (line-move count)))
2114   nil)
2115
2116 (defun previous-line (count)
2117   "Move cursor vertically up COUNT lines.
2118 If there is no character in the target line exactly over the current column,
2119 the cursor is positioned after the character in that line which spans this
2120 column, or at the end of the line if it is not long enough.
2121
2122 The command \\[set-goal-column] can be used to create
2123 a semipermanent goal column to which this command always moves.
2124 Then it does not try to move vertically.
2125
2126 If you are thinking of using this in a Lisp program, consider using
2127 `forward-line' with a negative argument instead.  It is usually easier
2128 to use and more reliable (no dependence on goal column, etc.)."
2129   (interactive "_p")
2130   (if (interactive-p)
2131       (condition-case nil
2132           (line-move (- count))
2133         ((beginning-of-buffer end-of-buffer)
2134          (when signal-error-on-buffer-boundary ; XEmacs
2135            (ding nil 'buffer-bound))))
2136     (line-move (- count)))
2137   nil)
2138
2139 (defcustom block-movement-size 6
2140   "*Number of lines that \"block movement\" commands (\\[forward-block-of-lines], \\[backward-block-of-lines]) move by."
2141   :type 'integer
2142   :group 'editing-basics)
2143
2144 (defun backward-block-of-lines ()
2145   "Move backward by one \"block\" of lines.
2146 The number of lines that make up a block is controlled by
2147 `block-movement-size', which defaults to 6."
2148   (interactive "_")
2149   (forward-line (- block-movement-size)))
2150
2151 (defun forward-block-of-lines ()
2152   "Move forward by one \"block\" of lines.
2153 The number of lines that make up a block is controlled by
2154 `block-movement-size', which defaults to 6."
2155   (interactive "_")
2156   (forward-line block-movement-size))
2157
2158 (defcustom track-eol nil
2159   "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
2160 This means moving to the end of each line moved onto.
2161 The beginning of a blank line does not count as the end of a line."
2162   :type 'boolean
2163   :group 'editing-basics)
2164
2165 (defcustom goal-column nil
2166   "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
2167   :type '(choice integer (const :tag "None" nil))
2168   :group 'editing-basics)
2169 (make-variable-buffer-local 'goal-column)
2170
2171 (defvar temporary-goal-column 0
2172   "Current goal column for vertical motion.
2173 It is the column where point was
2174 at the start of current run of vertical motion commands.
2175 When the `track-eol' feature is doing its job, the value is 9999.")
2176 (make-variable-buffer-local 'temporary-goal-column)
2177
2178 ;XEmacs: not yet ported, so avoid compiler warnings
2179 (eval-when-compile
2180   (defvar inhibit-point-motion-hooks))
2181
2182 (defcustom line-move-ignore-invisible nil
2183   "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
2184 Use with care, as it slows down movement significantly.  Outline mode sets this."
2185   :type 'boolean
2186   :group 'editing-basics)
2187
2188 ;; This is the guts of next-line and previous-line.
2189 ;; Count says how many lines to move.
2190 (defun line-move (count)
2191   ;; Don't run any point-motion hooks, and disregard intangibility,
2192   ;; for intermediate positions.
2193   (let ((inhibit-point-motion-hooks t)
2194         (opoint (point))
2195         new)
2196     (unwind-protect
2197         (progn
2198           (if (not (or (eq last-command 'next-line)
2199                        (eq last-command 'previous-line)))
2200               (setq temporary-goal-column
2201                     (if (and track-eol (eolp)
2202                              ;; Don't count start of empty line as end of line
2203                              ;; unless we just did explicit end-of-line.
2204                              (or (not (bolp)) (eq last-command 'end-of-line)))
2205                         9999
2206                       (current-column))))
2207           (if (and (not (integerp selective-display))
2208                    (not line-move-ignore-invisible))
2209               ;; Use just newline characters.
2210               (or (if (> count 0)
2211                       (progn (if (> count 1) (forward-line (1- count)))
2212                              ;; This way of moving forward COUNT lines
2213                              ;; verifies that we have a newline after the last one.
2214                              ;; It doesn't get confused by intangible text.
2215                              (end-of-line)
2216                              (zerop (forward-line 1)))
2217                     (and (zerop (forward-line count))
2218                          (bolp)))
2219                   (signal (if (< count 0)
2220                               'beginning-of-buffer
2221                             'end-of-buffer)
2222                           nil))
2223             ;; Move by count lines, but ignore invisible ones.
2224             (while (> count 0)
2225               (end-of-line)
2226               (and (zerop (vertical-motion 1))
2227                    (signal 'end-of-buffer nil))
2228               ;; If the following character is currently invisible,
2229               ;; skip all characters with that same `invisible' property value.
2230               (while (and (not (eobp))
2231                           (let ((prop
2232                                  (get-char-property (point) 'invisible)))
2233                             (if (eq buffer-invisibility-spec t)
2234                                 prop
2235                               (or (memq prop buffer-invisibility-spec)
2236                                   (assq prop buffer-invisibility-spec)))))
2237                 (if (get-text-property (point) 'invisible)
2238                     (goto-char (next-single-property-change (point) 'invisible))
2239                   (goto-char (next-extent-change (point))))) ; XEmacs
2240               (setq count (1- count)))
2241             (while (< count 0)
2242               (beginning-of-line)
2243               (and (zerop (vertical-motion -1))
2244                    (signal 'beginning-of-buffer nil))
2245               (while (and (not (bobp))
2246                           (let ((prop
2247                                  (get-char-property (1- (point)) 'invisible)))
2248                             (if (eq buffer-invisibility-spec t)
2249                                 prop
2250                               (or (memq prop buffer-invisibility-spec)
2251                                   (assq prop buffer-invisibility-spec)))))
2252                 (if (get-text-property (1- (point)) 'invisible)
2253                     (goto-char (previous-single-property-change (point) 'invisible))
2254                   (goto-char (previous-extent-change (point))))) ; XEmacs
2255               (setq count (1+ count))))
2256           (move-to-column (or goal-column temporary-goal-column)))
2257       ;; Remember where we moved to, go back home,
2258       ;; then do the motion over again
2259       ;; in just one step, with intangibility and point-motion hooks
2260       ;; enabled this time.
2261       (setq new (point))
2262       (goto-char opoint)
2263       (setq inhibit-point-motion-hooks nil)
2264       (goto-char new)))
2265   nil)
2266
2267 ;;; Many people have said they rarely use this feature, and often type
2268 ;;; it by accident.  Maybe it shouldn't even be on a key.
2269 ;; It's not on a key, as of 20.2.  So no need for this.
2270 ;(put 'set-goal-column 'disabled t)
2271
2272 (defun set-goal-column (column)
2273   "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
2274 Those commands will move to this position in the line moved to
2275 rather than trying to keep the same horizontal position.
2276 With a non-nil argument, clears out the goal column
2277 so that \\[next-line] and \\[previous-line] resume vertical motion.
2278 The goal column is stored in the variable `goal-column'."
2279   (interactive "_P") ; XEmacs
2280   (if column
2281       (progn
2282         (setq goal-column nil)
2283         (display-message 'command "No goal column"))
2284     (setq goal-column (current-column))
2285     (lmessage 'command
2286         "Goal column %d (use %s with a prefix arg to unset it)"
2287       goal-column
2288       (substitute-command-keys "\\[set-goal-column]")))
2289   nil)
2290 \f
2291 ;; deleted FSFmacs terminal randomness hscroll-point-visible stuff.
2292 ;; hscroll-step
2293 ;; hscroll-point-visible
2294 ;; hscroll-window-column
2295 ;; right-arrow
2296 ;; left-arrow
2297
2298 (defun scroll-other-window-down (lines)
2299   "Scroll the \"other window\" down.
2300 For more details, see the documentation for `scroll-other-window'."
2301   (interactive "P")
2302   (scroll-other-window
2303    ;; Just invert the argument's meaning.
2304    ;; We can do that without knowing which window it will be.
2305    (if (eq lines '-) nil
2306      (if (null lines) '-
2307        (- (prefix-numeric-value lines))))))
2308 ;(define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
2309
2310 (defun beginning-of-buffer-other-window (arg)
2311   "Move point to the beginning of the buffer in the other window.
2312 Leave mark at previous position.
2313 With arg N, put point N/10 of the way from the true beginning."
2314   (interactive "P")
2315   (let ((orig-window (selected-window))
2316         (window (other-window-for-scrolling)))
2317     ;; We use unwind-protect rather than save-window-excursion
2318     ;; because the latter would preserve the things we want to change.
2319     (unwind-protect
2320         (progn
2321           (select-window window)
2322           ;; Set point and mark in that window's buffer.
2323           (beginning-of-buffer arg)
2324           ;; Set point accordingly.
2325           (recenter '(t)))
2326       (select-window orig-window))))
2327
2328 (defun end-of-buffer-other-window (arg)
2329   "Move point to the end of the buffer in the other window.
2330 Leave mark at previous position.
2331 With arg N, put point N/10 of the way from the true end."
2332   (interactive "P")
2333   ;; See beginning-of-buffer-other-window for comments.
2334   (let ((orig-window (selected-window))
2335         (window (other-window-for-scrolling)))
2336     (unwind-protect
2337         (progn
2338           (select-window window)
2339           (end-of-buffer arg)
2340           (recenter '(t)))
2341       (select-window orig-window))))
2342 \f
2343 (defun transpose-chars (arg)
2344   "Interchange characters around point, moving forward one character.
2345 With prefix arg ARG, effect is to take character before point
2346 and drag it forward past ARG other characters (backward if ARG negative).
2347 If no argument and at end of line, the previous two chars are exchanged."
2348   (interactive "*P")
2349   (and (null arg) (eolp) (forward-char -1))
2350   (transpose-subr 'forward-char (prefix-numeric-value arg)))
2351
2352 ;;; A very old implementation of transpose-chars from the old days ...
2353 (defun transpose-preceding-chars (arg)
2354   "Interchange characters before point.
2355 With prefix arg ARG, effect is to take character before point
2356 and drag it forward past ARG other characters (backward if ARG negative).
2357 If no argument and not at start of line, the previous two chars are exchanged."
2358   (interactive "*P")
2359   (and (null arg) (not (bolp)) (forward-char -1))
2360   (transpose-subr 'forward-char (prefix-numeric-value arg)))
2361
2362
2363 (defun transpose-words (arg)
2364   "Interchange words around point, leaving point at end of them.
2365 With prefix arg ARG, effect is to take word before or around point
2366 and drag it forward past ARG other words (backward if ARG negative).
2367 If ARG is zero, the words around or after point and around or after mark
2368 are interchanged."
2369   (interactive "*p")
2370   (transpose-subr 'forward-word arg))
2371
2372 (defun transpose-sexps (arg)
2373   "Like \\[transpose-words] but applies to sexps.
2374 Does not work on a sexp that point is in the middle of
2375 if it is a list or string."
2376   (interactive "*p")
2377   (transpose-subr 'forward-sexp arg))
2378
2379 (defun transpose-lines (arg)
2380   "Exchange current line and previous line, leaving point after both.
2381 With argument ARG, takes previous line and moves it past ARG lines.
2382 With argument 0, interchanges line point is in with line mark is in."
2383   (interactive "*p")
2384   (transpose-subr #'(lambda (arg)
2385                      (if (= arg 1)
2386                          (progn
2387                            ;; Move forward over a line,
2388                            ;; but create a newline if none exists yet.
2389                            (end-of-line)
2390                            (if (eobp)
2391                                (newline)
2392                              (forward-char 1)))
2393                        (forward-line arg)))
2394                   arg))
2395
2396 (defun transpose-line-up (arg)
2397   "Move current line one line up, leaving point at beginning of that line.
2398 This can be run repeatedly to move the current line up a number of lines."
2399   (interactive "*p")
2400   ;; Move forward over a line,
2401   ;; but create a newline if none exists yet.
2402   (end-of-line)
2403   (if (eobp)
2404       (newline)
2405     (forward-char 1))
2406   (transpose-lines (- arg))
2407   (forward-line -1))
2408
2409 (defun transpose-line-down (arg)
2410   "Move current line one line down, leaving point at beginning of that line.
2411 This can be run repeatedly to move the current line down a number of lines."
2412   (interactive "*p")
2413   ;; Move forward over a line,
2414   ;; but create a newline if none exists yet.
2415   (end-of-line)
2416   (if (eobp)
2417       (newline)
2418     (forward-char 1))
2419   (transpose-lines arg)
2420   (forward-line -1))
2421
2422 (defun transpose-subr (mover arg)
2423   (let (start1 end1 start2 end2)
2424     ;; XEmacs -- use flet instead of defining a separate function and
2425     ;; relying on dynamic scope!!!
2426     (flet ((transpose-subr-1 ()
2427              (if (> (min end1 end2) (max start1 start2))
2428                  (error "Don't have two things to transpose"))
2429              (let ((word1 (buffer-substring start1 end1))
2430                    (word2 (buffer-substring start2 end2)))
2431                (delete-region start2 end2)
2432                (goto-char start2)
2433                (insert word1)
2434                (goto-char (if (< start1 start2) start1
2435                             (+ start1 (- (length word1) (length word2)))))
2436                (delete-char (length word1))
2437                (insert word2))))
2438       (if (= arg 0)
2439           (progn
2440             (save-excursion
2441               (funcall mover 1)
2442               (setq end2 (point))
2443               (funcall mover -1)
2444               (setq start2 (point))
2445               (goto-char (mark t)) ; XEmacs
2446               (funcall mover 1)
2447               (setq end1 (point))
2448               (funcall mover -1)
2449               (setq start1 (point))
2450               (transpose-subr-1))
2451             (exchange-point-and-mark t))) ; XEmacs
2452       (while (> arg 0)
2453         (funcall mover -1)
2454         (setq start1 (point))
2455         (funcall mover 1)
2456         (setq end1 (point))
2457         (funcall mover 1)
2458         (setq end2 (point))
2459         (funcall mover -1)
2460         (setq start2 (point))
2461         (transpose-subr-1)
2462         (goto-char end2)
2463         (setq arg (1- arg)))
2464       (while (< arg 0)
2465         (funcall mover -1)
2466         (setq start2 (point))
2467         (funcall mover -1)
2468         (setq start1 (point))
2469         (funcall mover 1)
2470         (setq end1 (point))
2471         (funcall mover 1)
2472         (setq end2 (point))
2473         (transpose-subr-1)
2474         (setq arg (1+ arg))))))
2475
2476 \f
2477 (defcustom comment-column 32
2478   "*Column to indent right-margin comments to.
2479 Setting this variable automatically makes it local to the current buffer.
2480 Each mode establishes a different default value for this variable; you
2481 can set the value for a particular mode using that mode's hook."
2482   :type 'integer
2483   :group 'fill-comments)
2484 (make-variable-buffer-local 'comment-column)
2485
2486 (defcustom comment-start nil
2487   "*String to insert to start a new comment, or nil if no comment syntax."
2488   :type '(choice (const :tag "None" nil)
2489                  string)
2490   :group 'fill-comments)
2491
2492 (defcustom comment-start-skip nil
2493   "*Regexp to match the start of a comment plus everything up to its body.
2494 If there are any \\(...\\) pairs, the comment delimiter text is held to begin
2495 at the place matched by the close of the first pair."
2496   :type '(choice (const :tag "None" nil)
2497                  regexp)
2498   :group 'fill-comments)
2499
2500 (defcustom comment-end ""
2501   "*String to insert to end a new comment.
2502 Should be an empty string if comments are terminated by end-of-line."
2503   :type 'string
2504   :group 'fill-comments)
2505
2506 (defconst comment-indent-hook nil
2507   "Obsolete variable for function to compute desired indentation for a comment.
2508 Use `comment-indent-function' instead.
2509 This function is called with no args with point at the beginning of
2510 the comment's starting delimiter.")
2511
2512 (defconst comment-indent-function
2513   ;; XEmacs - add at least one space after the end of the text on the
2514   ;; current line...
2515   (lambda ()
2516     (save-excursion
2517       (beginning-of-line)
2518       (let ((eol (save-excursion (end-of-line) (point))))
2519         (and comment-start-skip
2520              (re-search-forward comment-start-skip eol t)
2521              (setq eol (match-beginning 0)))
2522         (goto-char eol)
2523         (skip-chars-backward " \t")
2524         (max comment-column (1+ (current-column))))))
2525   "Function to compute desired indentation for a comment.
2526 This function is called with no args with point at the beginning of
2527 the comment's starting delimiter.")
2528
2529 (defcustom block-comment-start nil
2530   "*String to insert to start a new comment on a line by itself.
2531 If nil, use `comment-start' instead.
2532 Note that the regular expression `comment-start-skip' should skip this string
2533 as well as the `comment-start' string."
2534   :type '(choice (const :tag "Use `comment-start'" nil)
2535                  string)
2536   :group 'fill-comments)
2537
2538 (defcustom block-comment-end nil
2539   "*String to insert to end a new comment on a line by itself.
2540 Should be an empty string if comments are terminated by end-of-line.
2541 If nil, use `comment-end' instead."
2542   :type '(choice (const :tag "Use `comment-end'" nil)
2543                  string)
2544   :group 'fill-comments)
2545
2546 (defun indent-for-comment ()
2547   "Indent this line's comment to comment column, or insert an empty comment."
2548   (interactive "*")
2549   (let* ((empty (save-excursion (beginning-of-line)
2550                                 (looking-at "[ \t]*$")))
2551          (starter (or (and empty block-comment-start) comment-start))
2552          (ender (or (and empty block-comment-end) comment-end)))
2553     (if (null starter)
2554         (error "No comment syntax defined")
2555       (let* ((eolpos (save-excursion (end-of-line) (point)))
2556              cpos indent begpos)
2557         (beginning-of-line)
2558         (if (re-search-forward comment-start-skip eolpos 'move)
2559             (progn (setq cpos (point-marker))
2560                    ;; Find the start of the comment delimiter.
2561                    ;; If there were paren-pairs in comment-start-skip,
2562                    ;; position at the end of the first pair.
2563                    (if (match-end 1)
2564                        (goto-char (match-end 1))
2565                      ;; If comment-start-skip matched a string with
2566                      ;; internal whitespace (not final whitespace) then
2567                      ;; the delimiter start at the end of that
2568                      ;; whitespace.  Otherwise, it starts at the
2569                      ;; beginning of what was matched.
2570                      (skip-syntax-backward " " (match-beginning 0))
2571                      (skip-syntax-backward "^ " (match-beginning 0)))))
2572         (setq begpos (point))
2573         ;; Compute desired indent.
2574         (if (= (current-column)
2575                (setq indent (funcall comment-indent-function)))
2576             (goto-char begpos)
2577           ;; If that's different from current, change it.
2578           (skip-chars-backward " \t")
2579           (delete-region (point) begpos)
2580           (indent-to indent))
2581         ;; An existing comment?
2582         (if cpos
2583             (progn (goto-char cpos)
2584                    (set-marker cpos nil))
2585           ;; No, insert one.
2586           (insert starter)
2587           (save-excursion
2588             (insert ender)))))))
2589
2590 (defun set-comment-column (arg)
2591   "Set the comment column based on point.
2592 With no arg, set the comment column to the current column.
2593 With just minus as arg, kill any comment on this line.
2594 With any other arg, set comment column to indentation of the previous comment
2595  and then align or create a comment on this line at that column."
2596   (interactive "P")
2597   (if (eq arg '-)
2598       (kill-comment nil)
2599     (if arg
2600         (progn
2601           (save-excursion
2602             (beginning-of-line)
2603             (re-search-backward comment-start-skip)
2604             (beginning-of-line)
2605             (re-search-forward comment-start-skip)
2606             (goto-char (match-beginning 0))
2607             (setq comment-column (current-column))
2608             (lmessage 'command "Comment column set to %d" comment-column))
2609           (indent-for-comment))
2610       (setq comment-column (current-column))
2611       (lmessage 'command "Comment column set to %d" comment-column))))
2612
2613 (defun kill-comment (arg)
2614   "Kill the comment on this line, if any.
2615 With argument, kill comments on that many lines starting with this one."
2616   ;; this function loses in a lot of situations.  it incorrectly recognizes
2617   ;; comment delimiters sometimes (ergo, inside a string), doesn't work
2618   ;; with multi-line comments, can kill extra whitespace if comment wasn't
2619   ;; through end-of-line, et cetera.
2620   (interactive "*P")
2621   (or comment-start-skip (error "No comment syntax defined"))
2622   (let ((count (prefix-numeric-value arg)) endc)
2623     (while (> count 0)
2624       (save-excursion
2625         (end-of-line)
2626         (setq endc (point))
2627         (beginning-of-line)
2628         (and (string< "" comment-end)
2629              (setq endc
2630                    (progn
2631                      (re-search-forward (regexp-quote comment-end) endc 'move)
2632                      (skip-chars-forward " \t")
2633                      (point))))
2634         (beginning-of-line)
2635         (if (re-search-forward comment-start-skip endc t)
2636             (progn
2637               (goto-char (match-beginning 0))
2638               (skip-chars-backward " \t")
2639               (kill-region (point) endc)
2640               ;; to catch comments a line beginnings
2641               (indent-according-to-mode))))
2642       (if arg (forward-line 1))
2643       (setq count (1- count)))))
2644
2645 (defun comment-region (start end &optional arg)
2646   "Comment or uncomment each line in the region.
2647 With just C-u prefix arg, uncomment each line in region.
2648 Numeric prefix arg ARG means use ARG comment characters.
2649 If ARG is negative, delete that many comment characters instead.
2650 Comments are terminated on each line, even for syntax in which newline does
2651 not end the comment.  Blank lines do not get comments."
2652   ;; if someone wants it to only put a comment-start at the beginning and
2653   ;; comment-end at the end then typing it, C-x C-x, closing it, C-x C-x
2654   ;; is easy enough.  No option is made here for other than commenting
2655   ;; every line.
2656   (interactive "r\nP")
2657   (or comment-start (error "No comment syntax is defined"))
2658   (if (> start end) (let (mid) (setq mid start start end end mid)))
2659   (save-excursion
2660     (save-restriction
2661       (let ((cs comment-start) (ce comment-end)
2662             numarg)
2663         (if (consp arg) (setq numarg t)
2664           (setq numarg (prefix-numeric-value arg))
2665           ;; For positive arg > 1, replicate the comment delims now,
2666           ;; then insert the replicated strings just once.
2667           (while (> numarg 1)
2668             (setq cs (concat cs comment-start)
2669                   ce (concat ce comment-end))
2670             (setq numarg (1- numarg))))
2671         ;; Loop over all lines from START to END.
2672         (narrow-to-region start end)
2673         (goto-char start)
2674         (while (not (eobp))
2675           (if (or (eq numarg t) (< numarg 0))
2676               (progn
2677                 ;; Delete comment start from beginning of line.
2678                 (if (eq numarg t)
2679                     (while (looking-at (regexp-quote cs))
2680                       (delete-char (length cs)))
2681                   (let ((count numarg))
2682                     (while (and (> 1 (setq count (1+ count)))
2683                                 (looking-at (regexp-quote cs)))
2684                       (delete-char (length cs)))))
2685                 ;; Delete comment end from end of line.
2686                 (if (string= "" ce)
2687                     nil
2688                   (if (eq numarg t)
2689                       (progn
2690                         (end-of-line)
2691                         ;; This is questionable if comment-end ends in
2692                         ;; whitespace.  That is pretty brain-damaged,
2693                         ;; though.
2694                         (skip-chars-backward " \t")
2695                         (if (and (>= (- (point) (point-min)) (length ce))
2696                                  (save-excursion
2697                                    (backward-char (length ce))
2698                                    (looking-at (regexp-quote ce))))
2699                             (delete-char (- (length ce)))))
2700                     (let ((count numarg))
2701                       (while (> 1 (setq count (1+ count)))
2702                         (end-of-line)
2703                         ;; This is questionable if comment-end ends in
2704                         ;; whitespace.  That is pretty brain-damaged though
2705                         (skip-chars-backward " \t")
2706                         (save-excursion
2707                           (backward-char (length ce))
2708                           (if (looking-at (regexp-quote ce))
2709                               (delete-char (length ce))))))))
2710                 (forward-line 1))
2711             ;; Insert at beginning and at end.
2712             (if (looking-at "[ \t]*$") ()
2713               (insert cs)
2714               (if (string= "" ce) ()
2715                 (end-of-line)
2716                 (insert ce)))
2717             (search-forward "\n" nil 'move)))))))
2718
2719 ;; XEmacs
2720 (defun prefix-region (prefix)
2721   "Add a prefix string to each line between mark and point."
2722   (interactive "sPrefix string: ")
2723   (if prefix
2724       (let ((count (count-lines (mark) (point))))
2725         (goto-char (min (mark) (point)))
2726         (while (> count 0)
2727           (setq count (1- count))
2728           (beginning-of-line 1)
2729           (insert prefix)
2730           (end-of-line 1)
2731           (forward-char 1)))))
2732
2733 \f
2734 ;; XEmacs - extra parameter
2735 (defun backward-word (arg &optional buffer)
2736   "Move backward until encountering the end of a word.
2737 With argument, do this that many times.
2738 In programs, it is faster to call `forward-word' with negative arg."
2739   (interactive "_p") ; XEmacs
2740   (forward-word (- arg) buffer))
2741
2742 (defun mark-word (arg)
2743   "Set mark arg words away from point."
2744   (interactive "p")
2745   (mark-something 'mark-word 'forward-word arg))
2746
2747 ;; XEmacs modified
2748 (defun kill-word (arg)
2749   "Kill characters forward until encountering the end of a word.
2750 With argument, do this that many times."
2751   (interactive "*p")
2752   (kill-region (point) (save-excursion (forward-word arg) (point))))
2753
2754 (defun backward-kill-word (arg)
2755   "Kill characters backward until encountering the end of a word.
2756 With argument, do this that many times."
2757   (interactive "*p") ; XEmacs
2758   (kill-word (- arg)))
2759
2760 (defun current-word (&optional strict)
2761   "Return the word point is on (or a nearby word) as a string.
2762 If optional arg STRICT is non-nil, return nil unless point is within
2763 or adjacent to a word.
2764 If point is not between two word-constituent characters, but immediately
2765 follows one, move back first.
2766 Otherwise, if point precedes a word constituent, move forward first.
2767 Otherwise, move backwards until a word constituent is found and get that word;
2768 if you a newlines is reached first, move forward instead."
2769   (save-excursion
2770     (let ((oldpoint (point)) (start (point)) (end (point)))
2771       (skip-syntax-backward "w_") (setq start (point))
2772       (goto-char oldpoint)
2773       (skip-syntax-forward "w_") (setq end (point))
2774       (if (and (eq start oldpoint) (eq end oldpoint))
2775           ;; Point is neither within nor adjacent to a word.
2776           (and (not strict)
2777                (progn
2778                  ;; Look for preceding word in same line.
2779                  (skip-syntax-backward "^w_"
2780                                        (save-excursion
2781                                          (beginning-of-line) (point)))
2782                  (if (bolp)
2783                      ;; No preceding word in same line.
2784                      ;; Look for following word in same line.
2785                      (progn
2786                        (skip-syntax-forward "^w_"
2787                                             (save-excursion
2788                                               (end-of-line) (point)))
2789                        (setq start (point))
2790                        (skip-syntax-forward "w_")
2791                        (setq end (point)))
2792                      (setq end (point))
2793                      (skip-syntax-backward "w_")
2794                      (setq start (point)))
2795                  (buffer-substring start end)))
2796           (buffer-substring start end)))))
2797 \f
2798 (defcustom fill-prefix nil
2799   "*String for filling to insert at front of new line, or nil for none.
2800 Setting this variable automatically makes it local to the current buffer."
2801   :type '(choice (const :tag "None" nil)
2802                  string)
2803   :group 'fill)
2804 (make-variable-buffer-local 'fill-prefix)
2805
2806 (defcustom auto-fill-inhibit-regexp nil
2807   "*Regexp to match lines which should not be auto-filled."
2808   :type '(choice (const :tag "None" nil)
2809                  regexp)
2810   :group 'fill)
2811
2812 (defvar comment-line-break-function 'indent-new-comment-line
2813   "*Mode-specific function which line breaks and continues a comment.
2814
2815 This function is only called during auto-filling of a comment section.
2816 The function should take a single optional argument which is a flag
2817 indicating whether soft newlines should be inserted.")
2818
2819 ;; defined in mule-base/mule-category.el
2820 (defvar word-across-newline)
2821
2822 ;; This function is the auto-fill-function of a buffer
2823 ;; when Auto-Fill mode is enabled.
2824 ;; It returns t if it really did any work.
2825 ;; XEmacs:  This function is totally different.
2826 (defun do-auto-fill ()
2827   (let (give-up)
2828     (or (and auto-fill-inhibit-regexp
2829              (save-excursion (beginning-of-line)
2830                              (looking-at auto-fill-inhibit-regexp)))
2831         (while (and (not give-up) (> (current-column) fill-column))
2832           ;; Determine where to split the line.
2833           (let ((fill-prefix fill-prefix)
2834                 (fill-point
2835                  (let ((opoint (point))
2836                        bounce
2837                        ;; 97/3/14 jhod: Kinsoku
2838                        (re-break-point (if (featurep 'mule)
2839                                             (concat "[ \t\n]\\|" word-across-newline
2840                                                     ".\\|." word-across-newline)
2841                                         "[ \t\n]"))
2842                        ;; end patch
2843                        (first t))
2844                    (save-excursion
2845                      (move-to-column (1+ fill-column))
2846                      ;; Move back to a word boundary.
2847                      (while (or first
2848                                 ;; If this is after period and a single space,
2849                                 ;; move back once more--we don't want to break
2850                                 ;; the line there and make it look like a
2851                                 ;; sentence end.
2852                                 (and (not (bobp))
2853                                      (not bounce)
2854                                      sentence-end-double-space
2855                                      (save-excursion (forward-char -1)
2856                                                      (and (looking-at "\\. ")
2857                                                           (not (looking-at "\\.  "))))))
2858                        (setq first nil)
2859                        ;; 97/3/14 jhod: Kinsoku
2860                        ; (skip-chars-backward "^ \t\n"))
2861                        (fill-move-backward-to-break-point re-break-point)
2862                        ;; end patch
2863                        ;; If we find nowhere on the line to break it,
2864                        ;; break after one word.  Set bounce to t
2865                        ;; so we will not keep going in this while loop.
2866                        (if (bolp)
2867                            (progn
2868                              ;; 97/3/14 jhod: Kinsoku
2869                              ; (re-search-forward "[ \t]" opoint t)
2870                              (fill-move-forward-to-break-point re-break-point
2871                                                                opoint)
2872                              ;; end patch
2873                              (setq bounce t)))
2874                        (skip-chars-backward " \t"))
2875                      (if (and (featurep 'mule)
2876                               (or bounce (bolp))) (kinsoku-process)) ;; 97/3/14 jhod: Kinsoku
2877                      ;; Let fill-point be set to the place where we end up.
2878                      (point)))))
2879
2880             ;; I'm not sure why Stig made this change but it breaks
2881             ;; auto filling in at least C mode so I'm taking it back
2882             ;; out.  --cet
2883             ;; XEmacs - adaptive fill.
2884             ;;(maybe-adapt-fill-prefix
2885             ;; (or from (setq from (save-excursion (beginning-of-line)
2886             ;;                                   (point))))
2887             ;; (or to   (setq to (save-excursion (beginning-of-line 2)
2888             ;;                                 (point))))
2889             ;; t)
2890
2891             ;; If that place is not the beginning of the line,
2892             ;; break the line there.
2893             (if (save-excursion
2894                   (goto-char fill-point)
2895                   (not (or (bolp) (eolp)))) ; 97/3/14 jhod: during kinsoku processing it is possible to move beyond
2896                 (let ((prev-column (current-column)))
2897                   ;; If point is at the fill-point, do not `save-excursion'.
2898                   ;; Otherwise, if a comment prefix or fill-prefix is inserted,
2899                   ;; point will end up before it rather than after it.
2900                   (if (save-excursion
2901                         (skip-chars-backward " \t")
2902                         (= (point) fill-point))
2903                       ;; 1999-09-17 hniksic: turn off Kinsoku until
2904                       ;; it's debugged.
2905                       (funcall comment-line-break-function)
2906                       ;; 97/3/14 jhod: Kinsoku processing
2907 ;                     ;(indent-new-comment-line)
2908 ;                     (let ((spacep (memq (char-before (point)) '(?\  ?\t))))
2909 ;                       (funcall comment-line-break-function)
2910 ;                       ;; if user type space explicitly, leave SPC
2911 ;                       ;; even if there is no WAN.
2912 ;                       (if spacep
2913 ;                           (save-excursion
2914 ;                             (goto-char fill-point)
2915 ;                             ;; put SPC except that there is SPC
2916 ;                             ;; already or there is sentence end.
2917 ;                             (or (memq (char-after (point)) '(?\  ?\t))
2918 ;                                 (fill-end-of-sentence-p)
2919 ;                                 (insert ?\ )))))
2920                     (save-excursion
2921                       (goto-char fill-point)
2922                       (funcall comment-line-break-function)))
2923                   ;; If making the new line didn't reduce the hpos of
2924                   ;; the end of the line, then give up now;
2925                   ;; trying again will not help.
2926                   (if (>= (current-column) prev-column)
2927                       (setq give-up t)))
2928               ;; No place to break => stop trying.
2929               (setq give-up t)))))))
2930
2931 ;; Put FSF one in until I can one or the other working properly, then the
2932 ;; other one is history.
2933 ;(defun fsf:do-auto-fill ()
2934 ;  (let (fc justify
2935 ;          ;; bol
2936 ;          give-up
2937 ;          (fill-prefix fill-prefix))
2938 ;    (if (or (not (setq justify (current-justification)))
2939 ;           (null (setq fc (current-fill-column)))
2940 ;           (and (eq justify 'left)
2941 ;                (<= (current-column) fc))
2942 ;           (save-excursion (beginning-of-line)
2943 ;                           ;; (setq bol (point))
2944 ;                           (and auto-fill-inhibit-regexp
2945 ;                                (looking-at auto-fill-inhibit-regexp))))
2946 ;       nil ;; Auto-filling not required
2947 ;      (if (memq justify '(full center right))
2948 ;         (save-excursion (unjustify-current-line)))
2949
2950 ;      ;; Choose a fill-prefix automatically.
2951 ;      (if (and adaptive-fill-mode
2952 ;              (or (null fill-prefix) (string= fill-prefix "")))
2953 ;         (let ((prefix
2954 ;                (fill-context-prefix
2955 ;                 (save-excursion (backward-paragraph 1) (point))
2956 ;                 (save-excursion (forward-paragraph 1) (point))
2957 ;                 ;; Don't accept a non-whitespace fill prefix
2958 ;                 ;; from the first line of a paragraph.
2959 ;                 "^[ \t]*$")))
2960 ;           (and prefix (not (equal prefix ""))
2961 ;                (setq fill-prefix prefix))))
2962
2963 ;      (while (and (not give-up) (> (current-column) fc))
2964 ;       ;; Determine where to split the line.
2965 ;       (let ((fill-point
2966 ;              (let ((opoint (point))
2967 ;                    bounce
2968 ;                    (first t))
2969 ;                (save-excursion
2970 ;                  (move-to-column (1+ fc))
2971 ;                  ;; Move back to a word boundary.
2972 ;                  (while (or first
2973 ;                             ;; If this is after period and a single space,
2974 ;                             ;; move back once more--we don't want to break
2975 ;                             ;; the line there and make it look like a
2976 ;                             ;; sentence end.
2977 ;                             (and (not (bobp))
2978 ;                                  (not bounce)
2979 ;                                  sentence-end-double-space
2980 ;                                  (save-excursion (forward-char -1)
2981 ;                                                  (and (looking-at "\\. ")
2982 ;                                                       (not (looking-at "\\.  "))))))
2983 ;                    (setq first nil)
2984 ;                    (skip-chars-backward "^ \t\n")
2985 ;                    ;; If we find nowhere on the line to break it,
2986 ;                    ;; break after one word.  Set bounce to t
2987 ;                    ;; so we will not keep going in this while loop.
2988 ;                    (if (bolp)
2989 ;                        (progn
2990 ;                          (re-search-forward "[ \t]" opoint t)
2991 ;                          (setq bounce t)))
2992 ;                    (skip-chars-backward " \t"))
2993 ;                  ;; Let fill-point be set to the place where we end up.
2994 ;                  (point)))))
2995 ;         ;; If that place is not the beginning of the line,
2996 ;         ;; break the line there.
2997 ;         (if (save-excursion
2998 ;               (goto-char fill-point)
2999 ;               (not (bolp)))
3000 ;             (let ((prev-column (current-column)))
3001 ;               ;; If point is at the fill-point, do not `save-excursion'.
3002 ;               ;; Otherwise, if a comment prefix or fill-prefix is inserted,
3003 ;               ;; point will end up before it rather than after it.
3004 ;               (if (save-excursion
3005 ;                     (skip-chars-backward " \t")
3006 ;                     (= (point) fill-point))
3007 ;                   (funcall comment-line-break-function t)
3008 ;                 (save-excursion
3009 ;                   (goto-char fill-point)
3010 ;                   (funcall comment-line-break-function t)))
3011 ;               ;; Now do justification, if required
3012 ;               (if (not (eq justify 'left))
3013 ;                   (save-excursion
3014 ;                     (end-of-line 0)
3015 ;                     (justify-current-line justify nil t)))
3016 ;               ;; If making the new line didn't reduce the hpos of
3017 ;               ;; the end of the line, then give up now;
3018 ;               ;; trying again will not help.
3019 ;               (if (>= (current-column) prev-column)
3020 ;                   (setq give-up t)))
3021 ;           ;; No place to break => stop trying.
3022 ;           (setq give-up t))))
3023 ;      ;; Justify last line.
3024 ;      (justify-current-line justify t t)
3025 ;      t)))
3026
3027 (defvar normal-auto-fill-function 'do-auto-fill
3028   "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
3029 Some major modes set this.")
3030
3031 (defun auto-fill-mode (&optional arg)
3032   "Toggle auto-fill mode.
3033 With arg, turn auto-fill mode on if and only if arg is positive.
3034 In Auto-Fill mode, inserting a space at a column beyond `current-fill-column'
3035 automatically breaks the line at a previous space.
3036
3037 The value of `normal-auto-fill-function' specifies the function to use
3038 for `auto-fill-function' when turning Auto Fill mode on."
3039   (interactive "P")
3040   (prog1 (setq auto-fill-function
3041                (if (if (null arg)
3042                        (not auto-fill-function)
3043                        (> (prefix-numeric-value arg) 0))
3044                    normal-auto-fill-function
3045                    nil))
3046     (redraw-modeline)))
3047
3048 ;; This holds a document string used to document auto-fill-mode.
3049 (defun auto-fill-function ()
3050   "Automatically break line at a previous space, in insertion of text."
3051   nil)
3052
3053 (defun turn-on-auto-fill ()
3054   "Unconditionally turn on Auto Fill mode."
3055   (interactive)
3056   (auto-fill-mode 1))
3057
3058 (defun set-fill-column (arg)
3059   "Set `fill-column' to specified argument.
3060 Just \\[universal-argument] as argument means to use the current column
3061 The variable `fill-column' has a separate value for each buffer."
3062   (interactive "_P") ; XEmacs
3063   (cond ((integerp arg)
3064          (setq fill-column arg))
3065         ((consp arg)
3066          (setq fill-column (current-column)))
3067         ;; Disallow missing argument; it's probably a typo for C-x C-f.
3068         (t
3069          (error "set-fill-column requires an explicit argument")))
3070   (lmessage 'command "fill-column set to %d" fill-column))
3071 \f
3072 (defcustom comment-multi-line t ; XEmacs - this works well with adaptive fill
3073   "*Non-nil means \\[indent-new-comment-line] should continue same comment
3074 on new line, with no new terminator or starter.
3075 This is obsolete because you might as well use \\[newline-and-indent]."
3076   :type 'boolean
3077   :group 'fill-comments)
3078
3079 (defun indent-new-comment-line (&optional soft)
3080   "Break line at point and indent, continuing comment if within one.
3081 This indents the body of the continued comment
3082 under the previous comment line.
3083
3084 This command is intended for styles where you write a comment per line,
3085 starting a new comment (and terminating it if necessary) on each line.
3086 If you want to continue one comment across several lines, use \\[newline-and-indent].
3087
3088 If a fill column is specified, it overrides the use of the comment column
3089 or comment indentation.
3090
3091 The inserted newline is marked hard if `use-hard-newlines' is true,
3092 unless optional argument SOFT is non-nil."
3093   (interactive)
3094   (let (comcol comstart)
3095     (skip-chars-backward " \t")
3096     ;; 97/3/14 jhod: Kinsoku processing
3097     (if (featurep 'mule)
3098         (kinsoku-process))
3099     (delete-region (point)
3100                    (progn (skip-chars-forward " \t")
3101                           (point)))
3102     (if soft (insert ?\n) (newline 1))
3103     (if fill-prefix
3104         (progn
3105           (indent-to-left-margin)
3106           (insert fill-prefix))
3107     ;; #### - Eric Eide reverts to v18 semantics for this function in
3108     ;; fa-extras, which I'm not gonna do.  His changes are to (1) execute
3109     ;; the save-excursion below unconditionally, and (2) uncomment the check
3110     ;; for (not comment-multi-line) further below.  --Stig
3111       ;;#### jhod: probably need to fix this for kinsoku processing
3112       (if (not comment-multi-line)
3113           (save-excursion
3114             (if (and comment-start-skip
3115                      (let ((opoint (point)))
3116                        (forward-line -1)
3117                        (re-search-forward comment-start-skip opoint t)))
3118                 ;; The old line is a comment.
3119                 ;; Set WIN to the pos of the comment-start.
3120                 ;; But if the comment is empty, look at preceding lines
3121                 ;; to find one that has a nonempty comment.
3122
3123                 ;; If comment-start-skip contains a \(...\) pair,
3124                 ;; the real comment delimiter starts at the end of that pair.
3125                 (let ((win (or (match-end 1) (match-beginning 0))))
3126                   (while (and (eolp) (not (bobp))
3127                               (let (opoint)
3128                                 (beginning-of-line)
3129                                 (setq opoint (point))
3130                                 (forward-line -1)
3131                                 (re-search-forward comment-start-skip opoint t)))
3132                     (setq win (or (match-end 1) (match-beginning 0))))
3133                   ;; Indent this line like what we found.
3134                   (goto-char win)
3135                   (setq comcol (current-column))
3136                   (setq comstart
3137                         (buffer-substring (point) (match-end 0)))))))
3138       (if (and comcol (not fill-prefix))  ; XEmacs - (ENE) from fa-extras.
3139           (let ((comment-column comcol)
3140                 (comment-start comstart)
3141                 (block-comment-start comstart)
3142                 (comment-end comment-end))
3143             (and comment-end (not (equal comment-end ""))
3144   ;            (if (not comment-multi-line)
3145                      (progn
3146                        (forward-char -1)
3147                        (insert comment-end)
3148                        (forward-char 1))
3149   ;              (setq comment-column (+ comment-column (length comment-start))
3150   ;                    comment-start "")
3151   ;                )
3152                  )
3153             (if (not (eolp))
3154                 (setq comment-end ""))
3155             (insert ?\n)
3156             (forward-char -1)
3157             (indent-for-comment)
3158             (save-excursion
3159               ;; Make sure we delete the newline inserted above.
3160               (end-of-line)
3161               (delete-char 1)))
3162         (indent-according-to-mode)))))
3163
3164 \f
3165 (defun set-selective-display (arg)
3166   "Set `selective-display' to ARG; clear it if no arg.
3167 When the value of `selective-display' is a number > 0,
3168 lines whose indentation is >= that value are not displayed.
3169 The variable `selective-display' has a separate value for each buffer."
3170   (interactive "P")
3171   (if (eq selective-display t)
3172       (error "selective-display already in use for marked lines"))
3173   (let ((current-vpos
3174          (save-restriction
3175            (narrow-to-region (point-min) (point))
3176            (goto-char (window-start))
3177            (vertical-motion (window-height)))))
3178     (setq selective-display
3179           (and arg (prefix-numeric-value arg)))
3180     (recenter current-vpos))
3181   (set-window-start (selected-window) (window-start (selected-window)))
3182   ;; #### doesn't localize properly:
3183   (princ "selective-display set to " t)
3184   (prin1 selective-display t)
3185   (princ "." t))
3186
3187 ;; XEmacs
3188 (defun nuke-selective-display ()
3189   "Ensure that the buffer is not in selective-display mode.
3190 If `selective-display' is t, then restore the buffer text to its original
3191 state before disabling selective display."
3192   ;; by Stig@hackvan.com
3193   (interactive)
3194   (and (eq t selective-display)
3195        (save-excursion
3196          (save-restriction
3197            (widen)
3198            (goto-char (point-min))
3199            (let ((mod-p (buffer-modified-p))
3200                  (buffer-read-only nil))
3201              (while (search-forward "\r" nil t)
3202                (delete-char -1)
3203                (insert "\n"))
3204              (set-buffer-modified-p mod-p)
3205              ))))
3206   (setq selective-display nil))
3207
3208 (add-hook 'change-major-mode-hook 'nuke-selective-display)
3209
3210 (defconst overwrite-mode-textual " Ovwrt"
3211   "The string displayed in the mode line when in overwrite mode.")
3212 (defconst overwrite-mode-binary " Bin Ovwrt"
3213   "The string displayed in the mode line when in binary overwrite mode.")
3214
3215 (defun overwrite-mode (arg)
3216   "Toggle overwrite mode.
3217 With arg, enable overwrite mode if arg is positive, else disable.
3218 In overwrite mode, printing characters typed in replace existing text
3219 on a one-for-one basis, rather than pushing it to the right.  At the
3220 end of a line, such characters extend the line.  Before a tab,
3221 such characters insert until the tab is filled in.
3222 \\[quoted-insert] still inserts characters in overwrite mode; this
3223 is supposed to make it easier to insert characters when necessary."
3224   (interactive "P")
3225   (setq overwrite-mode
3226         (if (if (null arg) (not overwrite-mode)
3227               (> (prefix-numeric-value arg) 0))
3228             'overwrite-mode-textual))
3229   (redraw-modeline))
3230
3231 (defun binary-overwrite-mode (arg)
3232   "Toggle binary overwrite mode.
3233 With arg, enable binary overwrite mode if arg is positive, else disable.
3234 In binary overwrite mode, printing characters typed in replace
3235 existing text.  Newlines are not treated specially, so typing at the
3236 end of a line joins the line to the next, with the typed character
3237 between them.  Typing before a tab character simply replaces the tab
3238 with the character typed.
3239 \\[quoted-insert] replaces the text at the cursor, just as ordinary
3240 typing characters do.
3241
3242 Note that binary overwrite mode is not its own minor mode; it is a
3243 specialization of overwrite-mode, entered by setting the
3244 `overwrite-mode' variable to `overwrite-mode-binary'."
3245   (interactive "P")
3246   (setq overwrite-mode
3247         (if (if (null arg)
3248                 (not (eq overwrite-mode 'overwrite-mode-binary))
3249               (> (prefix-numeric-value arg) 0))
3250             'overwrite-mode-binary))
3251   (redraw-modeline))
3252 \f
3253 (defcustom line-number-mode nil
3254   "*Non-nil means display line number in modeline."
3255   :type 'boolean
3256   :group 'editing-basics)
3257
3258 (defun line-number-mode (arg)
3259   "Toggle Line Number mode.
3260 With arg, enable Line Number mode if arg is positive, else disable.
3261 When Line Number mode is enabled, the line number appears
3262 in the mode line."
3263   (interactive "P")
3264   (setq line-number-mode
3265         (if (null arg) (not line-number-mode)
3266           (> (prefix-numeric-value arg) 0)))
3267   (redraw-modeline))
3268
3269 (defcustom column-number-mode nil
3270   "*Non-nil means display column number in mode line."
3271   :type 'boolean
3272   :group 'editing-basics)
3273
3274 (defun column-number-mode (arg)
3275   "Toggle Column Number mode.
3276 With arg, enable Column Number mode if arg is positive, else disable.
3277 When Column Number mode is enabled, the column number appears
3278 in the mode line."
3279   (interactive "P")
3280   (setq column-number-mode
3281         (if (null arg) (not column-number-mode)
3282           (> (prefix-numeric-value arg) 0)))
3283   (redraw-modeline))
3284
3285 \f
3286 (defcustom blink-matching-paren t
3287   "*Non-nil means show matching open-paren when close-paren is inserted."
3288   :type 'boolean
3289   :group 'paren-blinking)
3290
3291 (defcustom blink-matching-paren-on-screen t
3292   "*Non-nil means show matching open-paren when it is on screen.
3293 nil means don't show it (but the open-paren can still be shown
3294 when it is off screen."
3295   :type 'boolean
3296   :group 'paren-blinking)
3297
3298 (defcustom blink-matching-paren-distance 12000
3299   "*If non-nil, is maximum distance to search for matching open-paren."
3300   :type '(choice integer (const nil))
3301   :group 'paren-blinking)
3302
3303 (defcustom blink-matching-delay 1
3304   "*The number of seconds that `blink-matching-open' will delay at a match."
3305   :type 'number
3306   :group 'paren-blinking)
3307
3308 (defcustom blink-matching-paren-dont-ignore-comments nil
3309   "*Non-nil means `blink-matching-paren' should not ignore comments."
3310   :type 'boolean
3311   :group 'paren-blinking)
3312
3313 (defun blink-matching-open ()
3314   "Move cursor momentarily to the beginning of the sexp before point."
3315   (interactive "_") ; XEmacs
3316   (and (> (point) (1+ (point-min)))
3317        blink-matching-paren
3318        ;; Verify an even number of quoting characters precede the close.
3319        (= 1 (logand 1 (- (point)
3320                          (save-excursion
3321                            (forward-char -1)
3322                            (skip-syntax-backward "/\\")
3323                            (point)))))
3324        (let* ((oldpos (point))
3325               (blinkpos)
3326               (mismatch))
3327          (save-excursion
3328            (save-restriction
3329              (if blink-matching-paren-distance
3330                  (narrow-to-region (max (point-min)
3331                                         (- (point) blink-matching-paren-distance))
3332                                    oldpos))
3333              (condition-case ()
3334                  (let ((parse-sexp-ignore-comments
3335                         (and parse-sexp-ignore-comments
3336                              (not blink-matching-paren-dont-ignore-comments))))
3337                    (setq blinkpos (scan-sexps oldpos -1)))
3338                (error nil)))
3339            (and blinkpos
3340                 (/= (char-syntax (char-after blinkpos))
3341                     ?\$)
3342                 (setq mismatch
3343                       (or (null (matching-paren (char-after blinkpos)))
3344                           (/= (char-after (1- oldpos))
3345                               (matching-paren (char-after blinkpos))))))
3346            (if mismatch (setq blinkpos nil))
3347            (if blinkpos
3348                (progn
3349                 (goto-char blinkpos)
3350                 (if (pos-visible-in-window-p)
3351                     (and blink-matching-paren-on-screen
3352                          (progn
3353                            (auto-show-make-point-visible)
3354                            (sit-for blink-matching-delay)))
3355                   (goto-char blinkpos)
3356                   (lmessage 'command "Matches %s"
3357                     ;; Show what precedes the open in its line, if anything.
3358                     (if (save-excursion
3359                           (skip-chars-backward " \t")
3360                           (not (bolp)))
3361                         (buffer-substring (progn (beginning-of-line) (point))
3362                                           (1+ blinkpos))
3363                       ;; Show what follows the open in its line, if anything.
3364                       (if (save-excursion
3365                             (forward-char 1)
3366                             (skip-chars-forward " \t")
3367                             (not (eolp)))
3368                           (buffer-substring blinkpos
3369                                             (progn (end-of-line) (point)))
3370                         ;; Otherwise show the previous nonblank line,
3371                         ;; if there is one.
3372                         (if (save-excursion
3373                               (skip-chars-backward "\n \t")
3374                               (not (bobp)))
3375                             (concat
3376                              (buffer-substring (progn
3377                                                  (skip-chars-backward "\n \t")
3378                                                  (beginning-of-line)
3379                                                  (point))
3380                                                (progn (end-of-line)
3381                                                       (skip-chars-backward " \t")
3382                                                       (point)))
3383                              ;; Replace the newline and other whitespace with `...'.
3384                              "..."
3385                              (buffer-substring blinkpos (1+ blinkpos)))
3386                           ;; There is nothing to show except the char itself.
3387                           (buffer-substring blinkpos (1+ blinkpos))))))))
3388              (cond (mismatch
3389                     (display-message 'no-log "Mismatched parentheses"))
3390                    ((not blink-matching-paren-distance)
3391                     (display-message 'no-log "Unmatched parenthesis"))))))))
3392
3393 ;Turned off because it makes dbx bomb out.
3394 (setq blink-paren-function 'blink-matching-open)
3395 \f
3396
3397 ;; XEmacs: Some functions moved to cmdloop.el:
3398 ;; keyboard-quit
3399 ;; buffer-quit-function
3400 ;; keyboard-escape-quit
3401
3402 (defun assoc-ignore-case (key alist)
3403   "Like `assoc', but assumes KEY is a string and ignores case when comparing."
3404   (setq key (downcase key))
3405   (let (element)
3406     (while (and alist (not element))
3407       (if (equal key (downcase (car (car alist))))
3408           (setq element (car alist)))
3409       (setq alist (cdr alist)))
3410     element))
3411
3412 \f
3413 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3414 ;;                          mail composition code                        ;;
3415 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3416
3417 (defcustom mail-user-agent 'sendmail-user-agent
3418   "*Your preference for a mail composition package.
3419 Various Emacs Lisp packages (e.g. reporter) require you to compose an
3420 outgoing email message.  This variable lets you specify which
3421 mail-sending package you prefer.
3422
3423 Valid values include:
3424
3425     sendmail-user-agent -- use the default Emacs Mail package
3426     mh-e-user-agent     -- use the Emacs interface to the MH mail system
3427     message-user-agent  -- use the GNUS mail sending package
3428
3429 Additional valid symbols may be available; check with the author of
3430 your package for details."
3431   :type '(radio (function-item :tag "Default Emacs mail"
3432                                :format "%t\n"
3433                                sendmail-user-agent)
3434                 (function-item :tag "Gnus mail sending package"
3435                                :format "%t\n"
3436                                message-user-agent)
3437                 (function :tag "Other"))
3438   :group 'mail)
3439
3440 (defun define-mail-user-agent (symbol composefunc sendfunc
3441                                       &optional abortfunc hookvar)
3442   "Define a symbol to identify a mail-sending package for `mail-user-agent'.
3443
3444 SYMBOL can be any Lisp symbol.  Its function definition and/or
3445 value as a variable do not matter for this usage; we use only certain
3446 properties on its property list, to encode the rest of the arguments.
3447
3448 COMPOSEFUNC is program callable function that composes an outgoing
3449 mail message buffer.  This function should set up the basics of the
3450 buffer without requiring user interaction.  It should populate the
3451 standard mail headers, leaving the `to:' and `subject:' headers blank
3452 by default.
3453
3454 COMPOSEFUNC should accept several optional arguments--the same
3455 arguments that `compose-mail' takes.  See that function's documentation.
3456
3457 SENDFUNC is the command a user would run to send the message.
3458
3459 Optional ABORTFUNC is the command a user would run to abort the
3460 message.  For mail packages that don't have a separate abort function,
3461 this can be `kill-buffer' (the equivalent of omitting this argument).
3462
3463 Optional HOOKVAR is a hook variable that gets run before the message
3464 is actually sent.  Callers that use the `mail-user-agent' may
3465 install a hook function temporarily on this hook variable.
3466 If HOOKVAR is nil, `mail-send-hook' is used.
3467
3468 The properties used on SYMBOL are `composefunc', `sendfunc',
3469 `abortfunc', and `hookvar'."
3470   (put symbol 'composefunc composefunc)
3471   (put symbol 'sendfunc sendfunc)
3472   (put symbol 'abortfunc (or abortfunc 'kill-buffer))
3473   (put symbol 'hookvar (or hookvar 'mail-send-hook)))
3474
3475 (define-mail-user-agent 'sendmail-user-agent
3476   'sendmail-user-agent-compose 'mail-send-and-exit)
3477
3478 (define-mail-user-agent 'message-user-agent
3479   'message-mail 'message-send-and-exit
3480   'message-kill-buffer 'message-send-hook)
3481
3482 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
3483                                               switch-function yank-action
3484                                               send-actions)
3485   (if switch-function
3486       (let ((special-display-buffer-names nil)
3487             (special-display-regexps nil)
3488             (same-window-buffer-names nil)
3489             (same-window-regexps nil))
3490         (funcall switch-function "*mail*")))
3491   (let ((cc (cdr (assoc-ignore-case "cc" other-headers)))
3492         (in-reply-to (cdr (assoc-ignore-case "in-reply-to" other-headers))))
3493     (or (mail continue to subject in-reply-to cc yank-action send-actions)
3494         continue
3495         (error "Message aborted"))
3496     (save-excursion
3497       (goto-char (point-min))
3498       (search-forward mail-header-separator)
3499       (beginning-of-line)
3500       (while other-headers
3501         (if (not (member (car (car other-headers)) '("in-reply-to" "cc")))
3502             (insert (car (car other-headers)) ": "
3503                     (cdr (car other-headers)) "\n"))
3504         (setq other-headers (cdr other-headers)))
3505       t)))
3506
3507 (define-mail-user-agent 'mh-e-user-agent
3508   'mh-user-agent-compose 'mh-send-letter 'mh-fully-kill-draft
3509   'mh-before-send-letter-hook)
3510
3511 (defun compose-mail (&optional to subject other-headers continue
3512                                switch-function yank-action send-actions)
3513   "Start composing a mail message to send.
3514 This uses the user's chosen mail composition package
3515 as selected with the variable `mail-user-agent'.
3516 The optional arguments TO and SUBJECT specify recipients
3517 and the initial Subject field, respectively.
3518
3519 OTHER-HEADERS is an alist specifying additional
3520 header fields.  Elements look like (HEADER . VALUE) where both
3521 HEADER and VALUE are strings.
3522
3523 CONTINUE, if non-nil, says to continue editing a message already
3524 being composed.
3525
3526 SWITCH-FUNCTION, if non-nil, is a function to use to
3527 switch to and display the buffer used for mail composition.
3528
3529 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
3530 to insert the raw text of the message being replied to.
3531 It has the form (FUNCTION . ARGS).  The user agent will apply
3532 FUNCTION to ARGS, to insert the raw text of the original message.
3533 \(The user agent will also run `mail-citation-hook', *after* the
3534 original text has been inserted in this way.)
3535
3536 SEND-ACTIONS is a list of actions to call when the message is sent.
3537 Each action has the form (FUNCTION . ARGS)."
3538   (interactive
3539    (list nil nil nil current-prefix-arg))
3540   (let ((function (get mail-user-agent 'composefunc)))
3541     (funcall function to subject other-headers continue
3542              switch-function yank-action send-actions)))
3543
3544 (defun compose-mail-other-window (&optional to subject other-headers continue
3545                                             yank-action send-actions)
3546   "Like \\[compose-mail], but edit the outgoing message in another window."
3547   (interactive
3548    (list nil nil nil current-prefix-arg))
3549   (compose-mail to subject other-headers continue
3550                 'switch-to-buffer-other-window yank-action send-actions))
3551
3552
3553 (defun compose-mail-other-frame (&optional to subject other-headers continue
3554                                             yank-action send-actions)
3555   "Like \\[compose-mail], but edit the outgoing message in another frame."
3556   (interactive
3557    (list nil nil nil current-prefix-arg))
3558   (compose-mail to subject other-headers continue
3559                 'switch-to-buffer-other-frame yank-action send-actions))
3560
3561 \f
3562 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3563 ;;                             set variable                              ;;
3564 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3565
3566 (defun set-variable (var val)
3567   "Set VARIABLE to VALUE.  VALUE is a Lisp object.
3568 When using this interactively, supply a Lisp expression for VALUE.
3569 If you want VALUE to be a string, you must surround it with doublequotes.
3570 If VARIABLE is a specifier, VALUE is added to it as an instantiator in
3571 the 'global locale with nil tag set (see `set-specifier').
3572
3573 If VARIABLE has a `variable-interactive' property, that is used as if
3574 it were the arg to `interactive' (which see) to interactively read the value."
3575   (interactive
3576    (let* ((var (read-variable "Set variable: "))
3577           ;; #### - yucky code replication here.  This should use something
3578           ;; from help.el or hyper-apropos.el
3579           (myhelp
3580            #'(lambda ()
3581               (with-output-to-temp-buffer "*Help*"
3582                 (prin1 var)
3583                 (princ "\nDocumentation:\n")
3584                 (princ (substring (documentation-property var 'variable-documentation)
3585                                   1))
3586                 (if (boundp var)
3587                     (let ((print-length 20))
3588                       (princ "\n\nCurrent value: ")
3589                       (prin1 (symbol-value var))))
3590                 (save-excursion
3591                   (set-buffer standard-output)
3592                   (help-mode))
3593                 nil)))
3594           (minibuffer-help-form
3595            '(funcall myhelp)))
3596      (list var
3597            (let ((prop (get var 'variable-interactive)))
3598              (if prop
3599                  ;; Use VAR's `variable-interactive' property
3600                  ;; as an interactive spec for prompting.
3601                  (call-interactively (list 'lambda '(arg)
3602                                            (list 'interactive prop)
3603                                            'arg))
3604                (eval-minibuffer (format "Set %s to value: " var)))))))
3605   (if (and (boundp var) (specifierp (symbol-value var)))
3606       (set-specifier (symbol-value var) val)
3607     (set var val)))
3608
3609 \f
3610 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3611 ;;                           case changing code                          ;;
3612 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3613
3614 ;; A bunch of stuff was moved elsewhere:
3615 ;; completion-list-mode-map
3616 ;; completion-reference-buffer
3617 ;; completion-base-size
3618 ;; delete-completion-window
3619 ;; previous-completion
3620 ;; next-completion
3621 ;; choose-completion
3622 ;; choose-completion-delete-max-match
3623 ;; choose-completion-string
3624 ;; completion-list-mode
3625 ;; completion-fixup-function
3626 ;; completion-setup-function
3627 ;; switch-to-completions
3628 ;; event stuffs
3629 ;; keypad stuffs
3630
3631 ;; The rest of this file is not in Lisp in FSF
3632 (defun capitalize-region-or-word (arg)
3633   "Capitalize the selected region or the following word (or ARG words)."
3634   (interactive "p")
3635   (if (region-active-p)
3636       (capitalize-region (region-beginning) (region-end))
3637     (capitalize-word arg)))
3638
3639 (defun upcase-region-or-word (arg)
3640   "Upcase the selected region or the following word (or ARG words)."
3641   (interactive "p")
3642   (if (region-active-p)
3643       (upcase-region (region-beginning) (region-end))
3644     (upcase-word arg)))
3645
3646 (defun downcase-region-or-word (arg)
3647   "Downcase the selected region or the following word (or ARG words)."
3648   (interactive "p")
3649   (if (region-active-p)
3650       (downcase-region (region-beginning) (region-end))
3651     (downcase-word arg)))
3652
3653 ;; #### not localized
3654 (defvar uncapitalized-title-words
3655   '("the" "a" "an" "in" "of" "for" "to" "and" "but" "at" "on" "as" "by"))
3656
3657 (defvar uncapitalized-title-word-regexp
3658   (concat "[ \t]*\\(" (mapconcat #'identity uncapitalized-title-words "\\|")
3659           "\\)\\>"))
3660
3661 (defun capitalize-string-as-title (string)
3662   "Capitalize the words in the string, except for small words (as in titles).
3663 The words not capitalized are specified in `uncapitalized-title-words'."
3664   (let ((buffer (get-buffer-create " *capitalize-string-as-title*")))
3665     (unwind-protect
3666         (progn
3667           (insert-string string buffer)
3668           (capitalize-region-as-title 1 (point-max buffer) buffer)
3669           (buffer-string buffer))
3670       (kill-buffer buffer))))
3671
3672 (defun capitalize-region-as-title (b e &optional buffer)
3673   "Capitalize the words in the region, except for small words (as in titles).
3674 The words not capitalized are specified in `uncapitalized-title-words'."
3675   (interactive "r")
3676   (save-excursion
3677     (and buffer
3678          (set-buffer buffer))
3679     (save-restriction
3680       (narrow-to-region b e)
3681       (goto-char (point-min))
3682       (let ((first t))
3683         (while (< (point) (point-max))
3684           (if (or first
3685                   (not (looking-at uncapitalized-title-word-regexp)))
3686               (capitalize-word 1)
3687             (forward-word 1))
3688           (setq first nil))))))
3689
3690 \f
3691 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3692 ;;                          zmacs active region code                     ;;
3693 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3694
3695 ;; Most of the zmacs code is now in elisp.  The only thing left in C
3696 ;; are the variables zmacs-regions, zmacs-region-active-p and
3697 ;; zmacs-region-stays plus the function zmacs_update_region which
3698 ;; simply calls the lisp level zmacs-update-region.  It must remain
3699 ;; for convenience, since it is called by core C code.
3700
3701 ;; XEmacs
3702 (defun activate-region ()
3703   "Activate the region, if `zmacs-regions' is true.
3704 Setting `zmacs-regions' to true causes LISPM-style active regions to be used.
3705 This function has no effect if `zmacs-regions' is false."
3706   (interactive)
3707   (and zmacs-regions (zmacs-activate-region)))
3708
3709 ;; XEmacs
3710 (defsubst region-exists-p ()
3711   "Return t if the region exists.
3712 If active regions are in use (i.e. `zmacs-regions' is true), this means that
3713  the region is active.  Otherwise, this means that the user has pushed
3714  a mark in this buffer at some point in the past.
3715 The functions `region-beginning' and `region-end' can be used to find the
3716  limits of the region."
3717   (not (null (mark))))
3718
3719 ;; XEmacs
3720 (defun region-active-p ()
3721   "Return non-nil if the region is active.
3722 If `zmacs-regions' is true, this is equivalent to `region-exists-p'.
3723 Otherwise, this function always returns false."
3724   (and zmacs-regions zmacs-region-extent))
3725
3726 (defvar zmacs-activate-region-hook nil
3727   "Function or functions called when the region becomes active;
3728 see the variable `zmacs-regions'.")
3729
3730 (defvar zmacs-deactivate-region-hook nil
3731   "Function or functions called when the region becomes inactive;
3732 see the variable `zmacs-regions'.")
3733
3734 (defvar zmacs-update-region-hook nil
3735   "Function or functions called when the active region changes.
3736 This is called after each command that sets `zmacs-region-stays' to t.
3737 See the variable `zmacs-regions'.")
3738
3739 (defvar zmacs-region-extent nil
3740   "The extent of the zmacs region; don't use this.")
3741
3742 (defvar zmacs-region-rectangular-p nil
3743   "Whether the zmacs region is a rectangle; don't use this.")
3744
3745 (defun zmacs-make-extent-for-region (region)
3746   ;; Given a region, this makes an extent in the buffer which holds that
3747   ;; region, for highlighting purposes.  If the region isn't associated
3748   ;; with a buffer, this does nothing.
3749   (let ((buffer nil)
3750         (valid (and (extentp zmacs-region-extent)
3751                     (extent-object zmacs-region-extent)
3752                     (buffer-live-p (extent-object zmacs-region-extent))))
3753         start end)
3754     (cond ((consp region)
3755            (setq start (min (car region) (cdr region))
3756                  end (max (car region) (cdr region))
3757                  valid (and valid
3758                             (eq (marker-buffer (car region))
3759                                 (extent-object zmacs-region-extent)))
3760                  buffer (marker-buffer (car region))))
3761           (t
3762            (signal 'error (list "Invalid region" region))))
3763
3764     (if valid
3765         nil
3766       ;; The condition case is in case any of the extents are dead or
3767       ;; otherwise incapacitated.
3768       (condition-case ()
3769           (if (listp zmacs-region-extent)
3770               (mapc 'delete-extent zmacs-region-extent)
3771             (delete-extent zmacs-region-extent))
3772         (error nil)))
3773
3774     (if valid
3775         (set-extent-endpoints zmacs-region-extent start end)
3776       (setq zmacs-region-extent (make-extent start end buffer))
3777
3778       ;; Make the extent be closed on the right, which means that if
3779       ;; characters are inserted exactly at the end of the extent, the
3780       ;; extent will grow to cover them.  This is important for shell
3781       ;; buffers - suppose one makes a region, and one end is at point-max.
3782       ;; If the shell produces output, that marker will remain at point-max
3783       ;; (its position will increase).  So it's important that the extent
3784       ;; exhibit the same behavior, lest the region covered by the extent
3785       ;; (the visual indication), and the region between point and mark
3786       ;; (the actual region value) become different!
3787       (set-extent-property zmacs-region-extent 'end-open nil)
3788
3789       ;; use same priority as mouse-highlighting so that conflicts between
3790       ;; the region extent and a mouse-highlighted extent are resolved by
3791       ;; the usual size-and-endpoint-comparison method.
3792       (set-extent-priority zmacs-region-extent mouse-highlight-priority)
3793       (set-extent-face zmacs-region-extent 'zmacs-region)
3794
3795       ;; #### It might be better to actually break
3796       ;; default-mouse-track-next-move-rect out of mouse.el so that we
3797       ;; can use its logic here.
3798       (cond
3799        (zmacs-region-rectangular-p
3800         (setq zmacs-region-extent (list zmacs-region-extent))
3801         (default-mouse-track-next-move-rect start end zmacs-region-extent)
3802         ))
3803
3804       zmacs-region-extent)))
3805
3806 (defun zmacs-region-buffer ()
3807   "Return the buffer containing the zmacs region, or nil."
3808   ;; #### this is horrible and kludgy!  This stuff needs to be rethought.
3809   (and zmacs-regions zmacs-region-active-p
3810        (or (marker-buffer (mark-marker t))
3811            (and (extent-live-p zmacs-region-extent)
3812                 (buffer-live-p (extent-object zmacs-region-extent))
3813                 (extent-object zmacs-region-extent)))))
3814
3815 (defun zmacs-activate-region ()
3816   "Make the region between `point' and `mark' be active (highlighted),
3817 if `zmacs-regions' is true.  Only a very small number of commands
3818 should ever do this.  Calling this function will call the hook
3819 `zmacs-activate-region-hook', if the region was previously inactive.
3820 Calling this function ensures that the region stays active after the
3821 current command terminates, even if `zmacs-region-stays' is not set.
3822 Returns t if the region was activated (i.e. if `zmacs-regions' if t)."
3823   (if (not zmacs-regions)
3824       nil
3825     (setq zmacs-region-active-p t
3826           zmacs-region-stays t
3827           zmacs-region-rectangular-p (and (boundp 'mouse-track-rectangle-p)
3828                                           mouse-track-rectangle-p))
3829     (if (marker-buffer (mark-marker t))
3830         (zmacs-make-extent-for-region (cons (point-marker t) (mark-marker t))))
3831     (run-hooks 'zmacs-activate-region-hook)
3832     t))
3833
3834 (defun zmacs-deactivate-region ()
3835   "Make the region between `point' and `mark' no longer be active,
3836 if `zmacs-regions' is true.  You shouldn't need to call this; the
3837 command loop calls it when appropriate.  Calling this function will
3838 call the hook `zmacs-deactivate-region-hook', if the region was
3839 previously active.  Returns t if the region had been active, nil
3840 otherwise."
3841   (if (not zmacs-region-active-p)
3842       nil
3843     (setq zmacs-region-active-p nil
3844           zmacs-region-stays nil
3845           zmacs-region-rectangular-p nil)
3846     (if zmacs-region-extent
3847         (let ((inhibit-quit t))
3848           (if (listp zmacs-region-extent)
3849               (mapc 'delete-extent zmacs-region-extent)
3850             (delete-extent zmacs-region-extent))
3851           (setq zmacs-region-extent nil)))
3852     (run-hooks 'zmacs-deactivate-region-hook)
3853     t))
3854
3855 (defun zmacs-update-region ()
3856   "Update the highlighted region between `point' and `mark'.
3857 You shouldn't need to call this; the command loop calls it
3858 when appropriate.  Calling this function will call the hook
3859 `zmacs-update-region-hook', if the region is active."
3860   (when zmacs-region-active-p
3861     (when (marker-buffer (mark-marker t))
3862       (zmacs-make-extent-for-region (cons (point-marker t)
3863                                           (mark-marker t))))
3864     (run-hooks 'zmacs-update-region-hook)))
3865
3866 \f
3867 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3868 ;;                           message logging code                        ;;
3869 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3870
3871 ;;; #### Should this be moved to a separate file, for clarity?
3872 ;;; -hniksic
3873
3874 ;;; The `message-stack' is an alist of labels with messages; the first
3875 ;;; message in this list is always in the echo area.  A call to
3876 ;;; `display-message' inserts a label/message pair at the head of the
3877 ;;; list, and removes any other pairs with that label.  Calling
3878 ;;; `clear-message' causes any pair with matching label to be removed,
3879 ;;; and this may cause the displayed message to change or vanish.  If
3880 ;;; the label arg is nil, the entire message stack is cleared.
3881 ;;;
3882 ;;; Message/error filtering will be a little tricker to implement than
3883 ;;; logging, since messages can be built up incrementally
3884 ;;; using clear-message followed by repeated calls to append-message
3885 ;;; (this happens with error messages).  For messages which aren't
3886 ;;; created this way, filtering could be implemented at display-message
3887 ;;; very easily.
3888 ;;;
3889 ;;; Bits of the logging code are borrowed from log-messages.el by
3890 ;;; Robert Potter (rpotter@grip.cis.upenn.edu).
3891
3892 ;; need this to terminate the currently-displayed message
3893 ;; ("Loading simple ...")
3894 (when (and
3895        (not (fboundp 'display-message))
3896        (not (featurep 'debug)))
3897   (send-string-to-terminal "\n"))
3898
3899 (defvar message-stack nil
3900   "An alist of label/string pairs representing active echo-area messages.
3901 The first element in the list is currently displayed in the echo area.
3902 Do not modify this directly--use the `message' or
3903 `display-message'/`clear-message' functions.")
3904
3905 (defvar remove-message-hook 'log-message
3906   "A function or list of functions to be called when a message is removed
3907 from the echo area at the bottom of the frame.  The label of the removed
3908 message is passed as the first argument, and the text of the message
3909 as the second argument.")
3910
3911 (defcustom log-message-max-size 50000
3912   "Maximum size of the \" *Message-Log*\" buffer.  See `log-message'."
3913   :type 'integer
3914   :group 'log-message)
3915 (make-compatible-variable 'message-log-max 'log-message-max-size)
3916
3917 ;; We used to reject quite a lot of stuff here, but it was a bad idea,
3918 ;; for two reasons:
3919 ;;
3920 ;; a) In most circumstances, you *want* to see the message in the log.
3921 ;;    The explicitly non-loggable messages should be marked as such by
3922 ;;    the issuer.  Gratuitous non-displaying of random regexps made
3923 ;;    debugging harder, too (because various reasonable debugging
3924 ;;    messages would get eaten).
3925 ;;
3926 ;; b) It slowed things down.  Yes, visibly.
3927 ;;
3928 ;; So, I left only a few of the really useless ones on this kill-list.
3929 ;;
3930 ;;                                            --hniksic
3931 (defcustom log-message-ignore-regexps
3932   '(;; Note: adding entries to this list slows down messaging
3933     ;; significantly.  Wherever possible, use message labels.
3934
3935     ;; Often-seen messages
3936     "\\`\\'"                            ; empty message
3937     "\\`\\(Beginning\\|End\\) of buffer\\'"
3938     ;;"^Quit$"
3939     ;; completions
3940     ;; Many packages print this -- impossible to categorize
3941     ;;"^Making completion list"
3942     ;; Gnus
3943     ;; "^No news is no news$"
3944     ;; "^No more\\( unread\\)? newsgroups$"
3945     ;; "^Opening [^ ]+ server\\.\\.\\."
3946     ;; "^[^:]+: Reading incoming mail"
3947     ;; "^Getting mail from "
3948     ;; "^\\(Generating Summary\\|Sorting threads\\|Making sparse threads\\|Scoring\\|Checking new news\\|Expiring articles\\|Sending\\)\\.\\.\\."
3949     ;; "^\\(Fetching headers for\\|Retrieving newsgroup\\|Reading active file\\)"
3950     ;; "^No more\\( unread\\)? articles"
3951     ;; "^Deleting article "
3952     ;; W3
3953     ;; "^Parsed [0-9]+ of [0-9]+ ([0-9]+%)"
3954     )
3955   "List of regular expressions matching messages which shouldn't be logged.
3956 See `log-message'.
3957
3958 Ideally, packages which generate messages which might need to be ignored
3959 should label them with 'progress, 'prompt, or 'no-log, so they can be
3960 filtered by the log-message-ignore-labels."
3961   :type '(repeat regexp)
3962   :group 'log-message)
3963
3964 (defcustom log-message-ignore-labels
3965   '(help-echo command progress prompt no-log garbage-collecting auto-saving)
3966   "List of symbols indicating labels of messages which shouldn't be logged.
3967 See `display-message' for some common labels.  See also `log-message'."
3968   :type '(repeat (symbol :tag "Label"))
3969   :group 'log-message)
3970
3971 ;;Subsumed by view-lossage
3972 ;; Not really, I'm adding it back by popular demand. -slb
3973 (defun show-message-log ()
3974   "Show the \" *Message-Log*\" buffer, which contains old messages and errors."
3975   (interactive)
3976   (pop-to-buffer (get-buffer-create " *Message-Log*")))
3977
3978 (defvar log-message-filter-function 'log-message-filter
3979   "Value must be a function of two arguments: a symbol (label) and
3980 a string (message).  It should return non-nil to indicate a message
3981 should be logged.  Possible values include 'log-message-filter and
3982 'log-message-filter-errors-only.")
3983
3984 (defun log-message-filter (label message)
3985   "Default value of `log-message-filter-function'.
3986 Messages whose text matches one of the `log-message-ignore-regexps'
3987 or whose label appears in `log-message-ignore-labels' are not saved."
3988   (let ((r  log-message-ignore-regexps)
3989         (ok (not (memq label log-message-ignore-labels))))
3990     (save-match-data
3991       (while (and r ok)
3992         (when (string-match (car r) message)
3993           (setq ok nil))
3994         (setq r (cdr r))))
3995     ok))
3996
3997 (defun log-message-filter-errors-only (label message)
3998   "For use as the `log-message-filter-function'.  Only logs error messages."
3999   (eq label 'error))
4000
4001 (defun log-message (label message)
4002   "Stuff a copy of the message into the \" *Message-Log*\" buffer,
4003 if it satisfies the `log-message-filter-function'.
4004
4005 For use on `remove-message-hook'."
4006   (when (and (not noninteractive)
4007              (funcall log-message-filter-function label message))
4008     ;; Use save-excursion rather than save-current-buffer because we
4009     ;; change the value of point.
4010     (save-excursion
4011       (set-buffer (get-buffer-create " *Message-Log*"))
4012       (goto-char (point-max))
4013       ;(insert (concat (upcase (symbol-name label)) ": "  message "\n"))
4014       (let (extent)
4015         ;; Mark multiline message with an extent, which `view-lossage'
4016         ;; will recognize.
4017         (when (string-match "\n" message)
4018           (setq extent (make-extent (point) (point)))
4019           (set-extent-properties extent '(end-open nil message-multiline t)))
4020         (insert message "\n")
4021         (when extent
4022           (set-extent-property extent 'end-open t)))
4023       (when (> (point-max) (max log-message-max-size (point-min)))
4024         ;; Trim log to ~90% of max size.
4025         (goto-char (max (- (point-max)
4026                            (truncate (* 0.9 log-message-max-size)))
4027                         (point-min)))
4028         (forward-line 1)
4029         (delete-region (point-min) (point))))))
4030
4031 (defun message-displayed-p (&optional return-string frame)
4032   "Return a non-nil value if a message is presently displayed in the\n\
4033 minibuffer's echo area.  If optional argument RETURN-STRING is non-nil,\n\
4034 return a string containing the message, otherwise just return t."
4035   ;; by definition, a message is displayed if the echo area buffer is
4036   ;; non-empty (see also echo_area_active()).  It had better also
4037   ;; be the case that message-stack is nil exactly when the echo area
4038   ;; is non-empty.
4039   (let ((buffer (get-buffer " *Echo Area*")))
4040     (and (< (point-min buffer) (point-max buffer))
4041          (if return-string
4042              (buffer-substring nil nil buffer)
4043            t))))
4044
4045 ;;; Returns the string which remains in the echo area, or nil if none.
4046 ;;; If label is nil, the whole message stack is cleared.
4047 (defun clear-message (&optional label frame stdout-p no-restore)
4048   "Remove any message with the given LABEL from the message-stack,
4049 erasing it from the echo area if it's currently displayed there.
4050 If a message remains at the head of the message-stack and NO-RESTORE
4051 is nil, it will be displayed.  The string which remains in the echo
4052 area will be returned, or nil if the message-stack is now empty.
4053 If LABEL is nil, the entire message-stack is cleared.
4054
4055 Unless you need the return value or you need to specify a label,
4056 you should just use (message nil)."
4057   (or frame (setq frame (selected-frame)))
4058   (let ((clear-stream (and message-stack (eq 'stream (frame-type frame)))))
4059     (remove-message label frame)
4060     (let ((inhibit-read-only t)
4061           (zmacs-region-stays zmacs-region-stays)) ; preserve from change
4062       (erase-buffer " *Echo Area*"))
4063     (if clear-stream
4064         (send-string-to-terminal ?\n stdout-p))
4065     (if no-restore
4066         nil                     ; just preparing to put another msg up
4067       (if message-stack
4068           (let ((oldmsg (cdr (car message-stack))))
4069             (raw-append-message oldmsg frame stdout-p)
4070             oldmsg)
4071         ;; #### Should we (redisplay-echo-area) here?  Messes some
4072         ;; things up.
4073         nil))))
4074
4075 (defun remove-message (&optional label frame)
4076   ;; If label is nil, we want to remove all matching messages.
4077   ;; Must reverse the stack first to log them in the right order.
4078   (let ((log nil))
4079     (while (and message-stack
4080                 (or (null label)        ; null label means clear whole stack
4081                     (eq label (car (car message-stack)))))
4082       (push (car message-stack) log)
4083       (setq message-stack (cdr message-stack)))
4084     (let ((s  message-stack))
4085       (while (cdr s)
4086         (let ((msg (car (cdr s))))
4087           (if (eq label (car msg))
4088               (progn
4089                 (push msg log)
4090                 (setcdr s (cdr (cdr s))))
4091             (setq s (cdr s))))))
4092     ;; (possibly) log each removed message
4093     (while log
4094       (condition-case e
4095           (run-hook-with-args 'remove-message-hook
4096                               (car (car log)) (cdr (car log)))
4097         (error (setq remove-message-hook nil)
4098                (lwarn 'message-log 'warning
4099                  "Error caught in `remove-message-hook': %s"
4100                  (error-message-string e))
4101                (let ((inhibit-read-only t))
4102                  (erase-buffer " *Echo Area*"))
4103                (signal (car e) (cdr e))))
4104       (setq log (cdr log)))))
4105
4106 (defun append-message (label message &optional frame stdout-p)
4107   (or frame (setq frame (selected-frame)))
4108   ;; Add a new entry to the message-stack, or modify an existing one
4109   (let ((top (car message-stack)))
4110     (if (eq label (car top))
4111         (setcdr top (concat (cdr top) message))
4112       (push (cons label message) message-stack)))
4113   (raw-append-message message frame stdout-p))
4114
4115 ;; Really append the message to the echo area.  no fiddling with
4116 ;; message-stack.
4117 (defun raw-append-message (message &optional frame stdout-p)
4118   (unless (equal message "")
4119     (let ((inhibit-read-only t)
4120           (zmacs-region-stays zmacs-region-stays)) ; preserve from change
4121       (insert-string message " *Echo Area*")
4122       ;; Conditionalizing on the device type in this way is not that clean,
4123       ;; but neither is having a device method, as I originally implemented
4124       ;; it: all non-stream devices behave in the same way.  Perhaps
4125       ;; the cleanest way is to make the concept of a "redisplayable"
4126       ;; device, which stream devices are not.  Look into this more if
4127       ;; we ever create another non-redisplayable device type (e.g.
4128       ;; processes?  printers?).
4129
4130       ;; Don't redisplay the echo area if we are executing a macro.
4131       (if (not executing-kbd-macro)
4132           (if (eq 'stream (frame-type frame))
4133               (send-string-to-terminal message stdout-p (frame-device frame))
4134             (redisplay-echo-area))))))
4135
4136 (defun display-message (label message &optional frame stdout-p)
4137   "Print a one-line message at the bottom of the frame.  First argument
4138 LABEL is an identifier for this message.  MESSAGE is the string to display.
4139 Use `clear-message' to remove a labelled message.
4140
4141 Here are some standard labels (those marked with `*' are not logged
4142 by default--see the `log-message-ignore-labels' variable):
4143     message       default label used by the `message' function
4144     error         default label used for reporting errors
4145   * progress      progress indicators like \"Converting... 45%\"
4146   * prompt        prompt-like messages like \"I-search: foo\"
4147   * command       helper command messages like \"Mark set\"
4148   * no-log        messages that should never be logged"
4149   (clear-message label frame stdout-p t)
4150   (append-message label message frame stdout-p))
4151
4152 (defun current-message (&optional frame)
4153   "Return the current message in the echo area, or nil.
4154 The FRAME argument is currently unused."
4155   (cdr (car message-stack)))
4156
4157 ;;; may eventually be frame-dependent
4158 (defun current-message-label (&optional frame)
4159   (car (car message-stack)))
4160
4161 (defun message (fmt &rest args)
4162   "Print a one-line message at the bottom of the frame.
4163 The arguments are the same as to `format'.
4164
4165 If the only argument is nil, clear any existing message; let the
4166 minibuffer contents show."
4167   ;; questionable junk in the C code
4168   ;; (if (framep default-minibuffer-frame)
4169   ;;     (make-frame-visible default-minibuffer-frame))
4170   (if (and (null fmt) (null args))
4171       (prog1 nil
4172         (clear-message nil))
4173     (let ((str (apply 'format fmt args)))
4174       (display-message 'message str)
4175       str)))
4176
4177 (defun lmessage (label fmt &rest args)
4178   "Print a one-line message at the bottom of the frame.
4179 First argument LABEL is an identifier for this message.  The rest of the
4180 arguments are the same as to `format'.
4181
4182 See `display-message' for a list of standard labels."
4183   (if (and (null fmt) (null args))
4184       (prog1 nil
4185         (clear-message label nil))
4186     (let ((str (apply 'format fmt args)))
4187       (display-message label str)
4188       str)))
4189
4190 \f
4191 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4192 ;;                              warning code                             ;;
4193 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4194
4195 (defcustom log-warning-minimum-level 'info
4196   "Minimum level of warnings that should be logged.
4197 The warnings in levels below this are completely ignored, as if they never
4198 happened.
4199
4200 The recognized warning levels, in decreasing order of priority, are
4201 'emergency, 'alert, 'critical, 'error, 'warning, 'notice, 'info, and
4202 'debug.
4203
4204 See also `display-warning-minimum-level'.
4205
4206 You can also control which warnings are displayed on a class-by-class
4207 basis.  See `display-warning-suppressed-classes' and
4208 `log-warning-suppressed-classes'."
4209   :type '(choice (const emergency) (const alert) (const critical)
4210                  (const error) (const warning) (const notice)
4211                  (const info) (const debug))
4212   :group 'warnings)
4213
4214 (defcustom display-warning-minimum-level 'info
4215   "Minimum level of warnings that should be displayed.
4216 The warnings in levels below this will be generated, but not
4217 displayed.
4218
4219 The recognized warning levels, in decreasing order of priority, are
4220 'emergency, 'alert, 'critical, 'error, 'warning, 'notice, 'info, and
4221 'debug.
4222
4223 See also `log-warning-minimum-level'.
4224
4225 You can also control which warnings are displayed on a class-by-class
4226 basis.  See `display-warning-suppressed-classes' and
4227 `log-warning-suppressed-classes'."
4228   :type '(choice (const emergency) (const alert) (const critical)
4229                  (const error) (const warning) (const notice)
4230                  (const info) (const debug))
4231   :group 'warnings)
4232
4233 (defvar log-warning-suppressed-classes nil
4234   "List of classes of warnings that shouldn't be logged or displayed.
4235 If any of the CLASS symbols associated with a warning is the same as
4236 any of the symbols listed here, the warning will be completely ignored,
4237 as it they never happened.
4238
4239 NOTE: In most circumstances, you should *not* set this variable.
4240 Set `display-warning-suppressed-classes' instead.  That way the suppressed
4241 warnings are not displayed but are still unobtrusively logged.
4242
4243 See also `log-warning-minimum-level' and `display-warning-minimum-level'.")
4244
4245 (defcustom display-warning-suppressed-classes nil
4246   "List of classes of warnings that shouldn't be displayed.
4247 If any of the CLASS symbols associated with a warning is the same as
4248 any of the symbols listed here, the warning will not be displayed.
4249 The warning will still logged in the *Warnings* buffer (unless also
4250 contained in `log-warning-suppressed-classes'), but the buffer will
4251 not be automatically popped up.
4252
4253 See also `log-warning-minimum-level' and `display-warning-minimum-level'."
4254   :type '(repeat symbol)
4255   :group 'warnings)
4256
4257 (defvar warning-count 0
4258   "Count of the number of warning messages displayed so far.")
4259
4260 (defconst warning-level-alist '((emergency . 8)
4261                                 (alert . 7)
4262                                 (critical . 6)
4263                                 (error . 5)
4264                                 (warning . 4)
4265                                 (notice . 3)
4266                                 (info . 2)
4267                                 (debug . 1)))
4268
4269 (defun warning-level-p (level)
4270   "Non-nil if LEVEL specifies a warning level."
4271   (and (symbolp level) (assq level warning-level-alist)))
4272
4273 ;; If you're interested in rewriting this function, be aware that it
4274 ;; could be called at arbitrary points in a Lisp program (when a
4275 ;; built-in function wants to issue a warning, it will call out to
4276 ;; this function the next time some Lisp code is evaluated).  Therefore,
4277 ;; this function *must* not permanently modify any global variables
4278 ;; (e.g. the current buffer) except those that specifically apply
4279 ;; to the warning system.
4280
4281 (defvar before-init-deferred-warnings nil)
4282
4283 (defun after-init-display-warnings ()
4284   "Display warnings deferred till after the init file is run.
4285 Warnings that occur before then are deferred so that warning
4286 suppression in the .emacs file will be honored."
4287   (while before-init-deferred-warnings
4288     (apply 'display-warning (car before-init-deferred-warnings))
4289     (setq before-init-deferred-warnings
4290           (cdr before-init-deferred-warnings))))
4291
4292 (add-hook 'after-init-hook 'after-init-display-warnings)
4293
4294 (defun display-warning (class message &optional level)
4295   "Display a warning message.
4296 CLASS should be a symbol describing what sort of warning this is, such
4297 as `resource' or `key-mapping'.  A list of such symbols is also
4298 accepted. (Individual classes can be suppressed; see
4299 `display-warning-suppressed-classes'.)  Optional argument LEVEL can
4300 be used to specify a priority for the warning, other than default priority
4301 `warning'. (See `display-warning-minimum-level').  The message is
4302 inserted into the *Warnings* buffer, which is made visible at appropriate
4303 times."
4304   (or level (setq level 'warning))
4305   (or (listp class) (setq class (list class)))
4306   (check-argument-type 'warning-level-p level)
4307   (if (and (not (featurep 'infodock))
4308            (not init-file-loaded))
4309       (push (list class message level) before-init-deferred-warnings)
4310     (catch 'ignored
4311       (let ((display-p t)
4312             (level-num (cdr (assq level warning-level-alist))))
4313         (if (< level-num (cdr (assq log-warning-minimum-level
4314                                     warning-level-alist)))
4315             (throw 'ignored nil))
4316         (if (intersection class log-warning-suppressed-classes)
4317             (throw 'ignored nil))
4318
4319         (if (< level-num (cdr (assq display-warning-minimum-level
4320                                     warning-level-alist)))
4321             (setq display-p nil))
4322         (if (and display-p
4323                  (intersection class display-warning-suppressed-classes))
4324             (setq display-p nil))
4325         (let ((buffer (get-buffer-create "*Warnings*")))
4326           (when display-p
4327             ;; The C code looks at display-warning-tick to determine
4328             ;; when it should call `display-warning-buffer'.  Change it
4329             ;; to get the C code's attention.
4330             (incf display-warning-tick))
4331           (with-current-buffer buffer
4332             (goto-char (point-max))
4333             (incf warning-count)
4334             (princ (format "(%d) (%s/%s) "
4335                            warning-count
4336                            (mapconcat 'symbol-name class ",")
4337                            level)
4338                    buffer)
4339             (princ message buffer)
4340             (terpri buffer)
4341             (terpri buffer)))))))
4342
4343 (defun warn (&rest args)
4344   "Display a warning message.
4345 The message is constructed by passing all args to `format'.  The message
4346 is placed in the *Warnings* buffer, which will be popped up at the next
4347 redisplay.  The class of the warning is `warning'.  See also
4348 `display-warning'."
4349   (display-warning 'warning (apply 'format args)))
4350
4351 (defun lwarn (class level &rest args)
4352   "Display a labeled warning message.
4353 CLASS should be a symbol describing what sort of warning this is, such
4354 as `resource' or `key-mapping'.  A list of such symbols is also
4355 accepted. (Individual classes can be suppressed; see
4356 `display-warning-suppressed-classes'.)  If non-nil, LEVEL can be used
4357 to specify a priority for the warning, other than default priority
4358 `warning'. (See `display-warning-minimum-level').  The message is
4359 inserted into the *Warnings* buffer, which is made visible at appropriate
4360 times.
4361
4362 The rest of the arguments are passed to `format'."
4363   (display-warning class (apply 'format args)
4364                    (or level 'warning)))
4365
4366 (defvar warning-marker nil)
4367
4368 ;; When this function is called by the C code, all non-local exits are
4369 ;; trapped and C-g is inhibited; therefore, it would be a very, very
4370 ;; bad idea for this function to get into an infinite loop.
4371
4372 (defun display-warning-buffer ()
4373   "Make the buffer that contains the warnings be visible.
4374 The C code calls this periodically, right before redisplay."
4375   (let ((buffer (get-buffer-create "*Warnings*")))
4376     (when (or (not warning-marker)
4377               (not (eq (marker-buffer warning-marker) buffer)))
4378       (setq warning-marker (make-marker))
4379       (set-marker warning-marker 1 buffer))
4380     (if temp-buffer-show-function
4381         (progn
4382           (funcall temp-buffer-show-function buffer)
4383           (mapc #'(lambda (win) (set-window-start win warning-marker))
4384                 (windows-of-buffer buffer nil t)))
4385       (set-window-start (display-buffer buffer) warning-marker))
4386     (set-marker warning-marker (point-max buffer) buffer)))
4387
4388 \f
4389 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4390 ;;                                misc junk                              ;;
4391 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4392
4393 (defun emacs-name ()
4394   "Return the printable name of this instance of Emacs."
4395   (cond ((featurep 'infodock) "InfoDock")
4396         ((featurep 'xemacs) "XEmacs")
4397         (t "Emacs")))
4398
4399 (defun debug-print (format &rest args)
4400   "Send a string to the debugging output.
4401 The string is formatted using (apply #'format FORMAT ARGS)."
4402   (princ (apply #'format format args) 'external-debugging-output))
4403
4404 ;;; simple.el ends here