This commit was generated by cvs2svn to compensate for changes in r1705,
[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 arg)
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 arg, 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 arg flag) nil auto-fill-function)))
182       (unwind-protect
183           (self-insert-command (prefix-numeric-value arg))
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 arg (prefix-numeric-value arg) 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 (arg)
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 arg)
232     (goto-char loc)
233     (while (> arg 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 arg (1- arg)))
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 command &optional history)
831   "Prompting with PROMPT, let user edit COMMAND and eval result.
832 COMMAND is a Lisp expression.  Let user edit that expression in
833 the minibuffer, then read and evaluate the result."
834   (let ((command (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 command))
840                                     (error (prin1-to-string command)))
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 command 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 command to be redone does not match front of history,
853       ;; add it to the history.
854       (or (equal command (car (symbol-value history)))
855           (set history (cons command (symbol-value history)))))
856     (eval command)))
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 (arg)
884   "Goto line ARG, counting from line 1 at beginning of buffer."
885   (interactive "NGoto line: ")
886   (setq arg (prefix-numeric-value arg))
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- arg))
892       (forward-line (1- arg)))))
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 arg)
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 arg 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 (arg)
1094   "Move forward ARG lines and position at first nonblank character."
1095   (interactive "_p")
1096   (forward-line arg)
1097   (skip-chars-forward " \t"))
1098
1099 (defun backward-to-indentation (arg)
1100   "Move backward ARG lines and position at first nonblank character."
1101   (interactive "_p")
1102   (forward-line (- arg))
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 the 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 (beg 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   ;; beg and end can be markers but the rest of this function is
1356   ;; written as if they are only integers
1357   (if (markerp beg) (setq beg (marker-position beg)))
1358   (if (markerp end) (setq end (marker-position end)))
1359   (or (and beg 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 beg end) (min beg end)))
1365                 (lmessage 'command "Killing %d characters"
1366                           (- (max beg end) (min beg 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 beg end) (max beg end) 'read-only nil))
1377    ;; This is redundant.
1378    ;; (if verbose (message "Copying %d characters"
1379    ;;                    (- (max beg end) (min beg end))))
1380     (copy-region-as-kill beg 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              (= beg 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 beg) 100))
1397           ;(old-list buffer-undo-list)
1398           tail)
1399       (delete-region beg 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 beg end)
1415     (delete-region beg 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 (beg 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 beg end) (< end beg))
1427     (kill-new (buffer-substring beg end)))
1428   nil)
1429
1430 (defun kill-ring-save (beg 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 beg end)
1436   ;; copy before delay, for xclipboard's benefit
1437   (if (interactive-p)
1438       (let ((other-end (if (= (point) beg) end beg))
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) beg)
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 ((beg (point))) (forward-line 1) (delete-region beg (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 text of current window upward ARG lines; or near full screen if no ARG.
2032 A near full screen is `next-screen-context-lines' less than a full screen.
2033 Negative ARG 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 text of current window downward ARG lines; or near full screen if no ARG.
2062 A near full screen is `next-screen-context-lines' less than a full screen.
2063 Negative ARG 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 (arg)
2080   "Move cursor vertically down ARG 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 (= arg 1))
2100       (let ((opoint (point)))
2101         (end-of-line)
2102         (if (eobp)
2103             (newline 1)
2104           (goto-char opoint)
2105           (line-move arg)))
2106     (if (interactive-p)
2107         ;; XEmacs:  Not sure what to do about this.  It's inconsistent. -sb
2108         (condition-case nil
2109             (line-move arg)
2110           ((beginning-of-buffer end-of-buffer)
2111            (when signal-error-on-buffer-boundary
2112              (ding nil 'buffer-bound))))
2113       (line-move arg)))
2114   nil)
2115
2116 (defun previous-line (arg)
2117   "Move cursor vertically up ARG 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 (- arg))
2133         ((beginning-of-buffer end-of-buffer)
2134          (when signal-error-on-buffer-boundary ; XEmacs
2135            (ding nil 'buffer-bound))))
2136     (line-move (- arg)))
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 ;; Arg says how many lines to move.
2190 (defun line-move (arg)
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 beg 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 (> arg 0)
2211                       (progn (if (> arg 1) (forward-line (1- arg)))
2212                              ;; This way of moving forward ARG 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 arg))
2218                          (bolp)))
2219                   (signal (if (< arg 0)
2220                               'beginning-of-buffer
2221                             'end-of-buffer)
2222                           nil))
2223             ;; Move by arg lines, but ignore invisible ones.
2224             (while (> arg 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 arg (1- arg)))
2241             (while (< arg 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 arg (1+ arg))))
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 (arg)
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 arg
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 an 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 to 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 to 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 (beg 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 (> beg end) (let (mid) (setq mid beg beg 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 BEG to END.
2672         (narrow-to-region beg end)
2673         (goto-char beg)
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                       (indent-new-comment-line)
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   (auto-fill-mode 1))
3056
3057 (defun set-fill-column (arg)
3058   "Set `fill-column' to specified argument.
3059 Just \\[universal-argument] as argument means to use the current column
3060 The variable `fill-column' has a separate value for each buffer."
3061   (interactive "_P") ; XEmacs
3062   (cond ((integerp arg)
3063          (setq fill-column arg))
3064         ((consp arg)
3065          (setq fill-column (current-column)))
3066         ;; Disallow missing argument; it's probably a typo for C-x C-f.
3067         (t
3068          (error "set-fill-column requires an explicit argument")))
3069   (lmessage 'command "fill-column set to %d" fill-column))
3070 \f
3071 (defcustom comment-multi-line t ; XEmacs - this works well with adaptive fill
3072   "*Non-nil means \\[indent-new-comment-line] should continue same comment
3073 on new line, with no new terminator or starter.
3074 This is obsolete because you might as well use \\[newline-and-indent]."
3075   :type 'boolean
3076   :group 'fill-comments)
3077
3078 (defun indent-new-comment-line (&optional soft)
3079   "Break line at point and indent, continuing comment if within one.
3080 This indents the body of the continued comment
3081 under the previous comment line.
3082
3083 This command is intended for styles where you write a comment per line,
3084 starting a new comment (and terminating it if necessary) on each line.
3085 If you want to continue one comment across several lines, use \\[newline-and-indent].
3086
3087 If a fill column is specified, it overrides the use of the comment column
3088 or comment indentation.
3089
3090 The inserted newline is marked hard if `use-hard-newlines' is true,
3091 unless optional argument SOFT is non-nil."
3092   (interactive)
3093   (let (comcol comstart)
3094     (skip-chars-backward " \t")
3095     ;; 97/3/14 jhod: Kinsoku processing
3096     (if (featurep 'mule)
3097         (kinsoku-process))
3098     (delete-region (point)
3099                    (progn (skip-chars-forward " \t")
3100                           (point)))
3101     (if soft (insert ?\n) (newline 1))
3102     (if fill-prefix
3103         (progn
3104           (indent-to-left-margin)
3105           (insert fill-prefix))
3106     ;; #### - Eric Eide reverts to v18 semantics for this function in
3107     ;; fa-extras, which I'm not gonna do.  His changes are to (1) execute
3108     ;; the save-excursion below unconditionally, and (2) uncomment the check
3109     ;; for (not comment-multi-line) further below.  --Stig
3110       ;;#### jhod: probably need to fix this for kinsoku processing
3111       (if (not comment-multi-line)
3112           (save-excursion
3113             (if (and comment-start-skip
3114                      (let ((opoint (point)))
3115                        (forward-line -1)
3116                        (re-search-forward comment-start-skip opoint t)))
3117                 ;; The old line is a comment.
3118                 ;; Set WIN to the pos of the comment-start.
3119                 ;; But if the comment is empty, look at preceding lines
3120                 ;; to find one that has a nonempty comment.
3121
3122                 ;; If comment-start-skip contains a \(...\) pair,
3123                 ;; the real comment delimiter starts at the end of that pair.
3124                 (let ((win (or (match-end 1) (match-beginning 0))))
3125                   (while (and (eolp) (not (bobp))
3126                               (let (opoint)
3127                                 (beginning-of-line)
3128                                 (setq opoint (point))
3129                                 (forward-line -1)
3130                                 (re-search-forward comment-start-skip opoint t)))
3131                     (setq win (or (match-end 1) (match-beginning 0))))
3132                   ;; Indent this line like what we found.
3133                   (goto-char win)
3134                   (setq comcol (current-column))
3135                   (setq comstart
3136                         (buffer-substring (point) (match-end 0)))))))
3137       (if (and comcol (not fill-prefix))  ; XEmacs - (ENE) from fa-extras.
3138           (let ((comment-column comcol)
3139                 (comment-start comstart)
3140                 (block-comment-start comstart)
3141                 (comment-end comment-end))
3142             (and comment-end (not (equal comment-end ""))
3143   ;            (if (not comment-multi-line)
3144                      (progn
3145                        (forward-char -1)
3146                        (insert comment-end)
3147                        (forward-char 1))
3148   ;              (setq comment-column (+ comment-column (length comment-start))
3149   ;                    comment-start "")
3150   ;                )
3151                  )
3152             (if (not (eolp))
3153                 (setq comment-end ""))
3154             (insert ?\n)
3155             (forward-char -1)
3156             (indent-for-comment)
3157             (save-excursion
3158               ;; Make sure we delete the newline inserted above.
3159               (end-of-line)
3160               (delete-char 1)))
3161         (indent-according-to-mode)))))
3162
3163 \f
3164 (defun set-selective-display (arg)
3165   "Set `selective-display' to ARG; clear it if no arg.
3166 When the value of `selective-display' is a number > 0,
3167 lines whose indentation is >= that value are not displayed.
3168 The variable `selective-display' has a separate value for each buffer."
3169   (interactive "P")
3170   (if (eq selective-display t)
3171       (error "selective-display already in use for marked lines"))
3172   (let ((current-vpos
3173          (save-restriction
3174            (narrow-to-region (point-min) (point))
3175            (goto-char (window-start))
3176            (vertical-motion (window-height)))))
3177     (setq selective-display
3178           (and arg (prefix-numeric-value arg)))
3179     (recenter current-vpos))
3180   (set-window-start (selected-window) (window-start (selected-window)))
3181   ;; #### doesn't localize properly:
3182   (princ "selective-display set to " t)
3183   (prin1 selective-display t)
3184   (princ "." t))
3185
3186 ;; XEmacs
3187 (defun nuke-selective-display ()
3188   "Ensure that the buffer is not in selective-display mode.
3189 If `selective-display' is t, then restore the buffer text to its original
3190 state before disabling selective display."
3191   ;; by Stig@hackvan.com
3192   (interactive)
3193   (and (eq t selective-display)
3194        (save-excursion
3195          (save-restriction
3196            (widen)
3197            (goto-char (point-min))
3198            (let ((mod-p (buffer-modified-p))
3199                  (buffer-read-only nil))
3200              (while (search-forward "\r" nil t)
3201                (delete-char -1)
3202                (insert "\n"))
3203              (set-buffer-modified-p mod-p)
3204              ))))
3205   (setq selective-display nil))
3206
3207 (add-hook 'change-major-mode-hook 'nuke-selective-display)
3208
3209 (defconst overwrite-mode-textual (purecopy " Ovwrt")
3210   "The string displayed in the mode line when in overwrite mode.")
3211 (defconst overwrite-mode-binary (purecopy " Bin Ovwrt")
3212   "The string displayed in the mode line when in binary overwrite mode.")
3213
3214 (defun overwrite-mode (arg)
3215   "Toggle overwrite mode.
3216 With arg, turn overwrite mode on iff arg is positive.
3217 In overwrite mode, printing characters typed in replace existing text
3218 on a one-for-one basis, rather than pushing it to the right.  At the
3219 end of a line, such characters extend the line.  Before a tab,
3220 such characters insert until the tab is filled in.
3221 \\[quoted-insert] still inserts characters in overwrite mode; this
3222 is supposed to make it easier to insert characters when necessary."
3223   (interactive "P")
3224   (setq overwrite-mode
3225         (if (if (null arg) (not overwrite-mode)
3226               (> (prefix-numeric-value arg) 0))
3227             'overwrite-mode-textual))
3228   (redraw-modeline))
3229
3230 (defun binary-overwrite-mode (arg)
3231   "Toggle binary overwrite mode.
3232 With arg, turn binary overwrite mode on iff arg is positive.
3233 In binary overwrite mode, printing characters typed in replace
3234 existing text.  Newlines are not treated specially, so typing at the
3235 end of a line joins the line to the next, with the typed character
3236 between them.  Typing before a tab character simply replaces the tab
3237 with the character typed.
3238 \\[quoted-insert] replaces the text at the cursor, just as ordinary
3239 typing characters do.
3240
3241 Note that binary overwrite mode is not its own minor mode; it is a
3242 specialization of overwrite-mode, entered by setting the
3243 `overwrite-mode' variable to `overwrite-mode-binary'."
3244   (interactive "P")
3245   (setq overwrite-mode
3246         (if (if (null arg)
3247                 (not (eq overwrite-mode 'overwrite-mode-binary))
3248               (> (prefix-numeric-value arg) 0))
3249             'overwrite-mode-binary))
3250   (redraw-modeline))
3251 \f
3252 (defcustom line-number-mode nil
3253   "*Non-nil means display line number in modeline."
3254   :type 'boolean
3255   :group 'editing-basics)
3256
3257 (defun line-number-mode (arg)
3258   "Toggle Line Number mode.
3259 With arg, turn Line Number mode on iff arg is positive.
3260 When Line Number mode is enabled, the line number appears
3261 in the mode line."
3262   (interactive "P")
3263   (setq line-number-mode
3264         (if (null arg) (not line-number-mode)
3265           (> (prefix-numeric-value arg) 0)))
3266   (redraw-modeline))
3267
3268 (defcustom column-number-mode nil
3269   "*Non-nil means display column number in mode line."
3270   :type 'boolean
3271   :group 'editing-basics)
3272
3273 (defun column-number-mode (arg)
3274   "Toggle Column Number mode.
3275 With arg, turn Column Number mode on iff arg is positive.
3276 When Column Number mode is enabled, the column number appears
3277 in the mode line."
3278   (interactive "P")
3279   (setq column-number-mode
3280         (if (null arg) (not column-number-mode)
3281           (> (prefix-numeric-value arg) 0)))
3282   (redraw-modeline))
3283
3284 \f
3285 (defcustom blink-matching-paren t
3286   "*Non-nil means show matching open-paren when close-paren is inserted."
3287   :type 'boolean
3288   :group 'paren-blinking)
3289
3290 (defcustom blink-matching-paren-on-screen t
3291   "*Non-nil means show matching open-paren when it is on screen.
3292 nil means don't show it (but the open-paren can still be shown
3293 when it is off screen."
3294   :type 'boolean
3295   :group 'paren-blinking)
3296
3297 (defcustom blink-matching-paren-distance 12000
3298   "*If non-nil, is maximum distance to search for matching open-paren."
3299   :type '(choice integer (const nil))
3300   :group 'paren-blinking)
3301
3302 (defcustom blink-matching-delay 1
3303   "*The number of seconds that `blink-matching-open' will delay at a match."
3304   :type 'number
3305   :group 'paren-blinking)
3306
3307 (defcustom blink-matching-paren-dont-ignore-comments nil
3308   "*Non-nil means `blink-matching-paren' should not ignore comments."
3309   :type 'boolean
3310   :group 'paren-blinking)
3311
3312 (defun blink-matching-open ()
3313   "Move cursor momentarily to the beginning of the sexp before point."
3314   (interactive "_") ; XEmacs
3315   (and (> (point) (1+ (point-min)))
3316        blink-matching-paren
3317        ;; Verify an even number of quoting characters precede the close.
3318        (= 1 (logand 1 (- (point)
3319                          (save-excursion
3320                            (forward-char -1)
3321                            (skip-syntax-backward "/\\")
3322                            (point)))))
3323        (let* ((oldpos (point))
3324               (blinkpos)
3325               (mismatch))
3326          (save-excursion
3327            (save-restriction
3328              (if blink-matching-paren-distance
3329                  (narrow-to-region (max (point-min)
3330                                         (- (point) blink-matching-paren-distance))
3331                                    oldpos))
3332              (condition-case ()
3333                  (let ((parse-sexp-ignore-comments
3334                         (and parse-sexp-ignore-comments
3335                              (not blink-matching-paren-dont-ignore-comments))))
3336                    (setq blinkpos (scan-sexps oldpos -1)))
3337                (error nil)))
3338            (and blinkpos
3339                 (/= (char-syntax (char-after blinkpos))
3340                     ?\$)
3341                 (setq mismatch
3342                       (or (null (matching-paren (char-after blinkpos)))
3343                           (/= (char-after (1- oldpos))
3344                               (matching-paren (char-after blinkpos))))))
3345            (if mismatch (setq blinkpos nil))
3346            (if blinkpos
3347                (progn
3348                 (goto-char blinkpos)
3349                 (if (pos-visible-in-window-p)
3350                     (and blink-matching-paren-on-screen
3351                          (progn
3352                            (auto-show-make-point-visible)
3353                            (sit-for blink-matching-delay)))
3354                   (goto-char blinkpos)
3355                   (lmessage 'command "Matches %s"
3356                     ;; Show what precedes the open in its line, if anything.
3357                     (if (save-excursion
3358                           (skip-chars-backward " \t")
3359                           (not (bolp)))
3360                         (buffer-substring (progn (beginning-of-line) (point))
3361                                           (1+ blinkpos))
3362                       ;; Show what follows the open in its line, if anything.
3363                       (if (save-excursion
3364                             (forward-char 1)
3365                             (skip-chars-forward " \t")
3366                             (not (eolp)))
3367                           (buffer-substring blinkpos
3368                                             (progn (end-of-line) (point)))
3369                         ;; Otherwise show the previous nonblank line,
3370                         ;; if there is one.
3371                         (if (save-excursion
3372                               (skip-chars-backward "\n \t")
3373                               (not (bobp)))
3374                             (concat
3375                              (buffer-substring (progn
3376                                                  (skip-chars-backward "\n \t")
3377                                                  (beginning-of-line)
3378                                                  (point))
3379                                                (progn (end-of-line)
3380                                                       (skip-chars-backward " \t")
3381                                                       (point)))
3382                              ;; Replace the newline and other whitespace with `...'.
3383                              "..."
3384                              (buffer-substring blinkpos (1+ blinkpos)))
3385                           ;; There is nothing to show except the char itself.
3386                           (buffer-substring blinkpos (1+ blinkpos))))))))
3387              (cond (mismatch
3388                     (display-message 'no-log "Mismatched parentheses"))
3389                    ((not blink-matching-paren-distance)
3390                     (display-message 'no-log "Unmatched parenthesis"))))))))
3391
3392 ;Turned off because it makes dbx bomb out.
3393 (setq blink-paren-function 'blink-matching-open)
3394 \f
3395
3396 ;; XEmacs: Some functions moved to cmdloop.el:
3397 ;; keyboard-quit
3398 ;; buffer-quit-function
3399 ;; keyboard-escape-quit
3400
3401 (defun assoc-ignore-case (key alist)
3402   "Like `assoc', but assumes KEY is a string and ignores case when comparing."
3403   (setq key (downcase key))
3404   (let (element)
3405     (while (and alist (not element))
3406       (if (equal key (downcase (car (car alist))))
3407           (setq element (car alist)))
3408       (setq alist (cdr alist)))
3409     element))
3410
3411 \f
3412 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3413 ;;                          mail composition code                        ;;
3414 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3415
3416 (defcustom mail-user-agent 'sendmail-user-agent
3417   "*Your preference for a mail composition package.
3418 Various Emacs Lisp packages (e.g. reporter) require you to compose an
3419 outgoing email message.  This variable lets you specify which
3420 mail-sending package you prefer.
3421
3422 Valid values include:
3423
3424     sendmail-user-agent -- use the default Emacs Mail package
3425     mh-e-user-agent     -- use the Emacs interface to the MH mail system
3426     message-user-agent  -- use the GNUS mail sending package
3427
3428 Additional valid symbols may be available; check with the author of
3429 your package for details."
3430   :type '(radio (function-item :tag "Default Emacs mail"
3431                                :format "%t\n"
3432                                sendmail-user-agent)
3433                 (function-item :tag "Gnus mail sending package"
3434                                :format "%t\n"
3435                                message-user-agent)
3436                 (function :tag "Other"))
3437   :group 'mail)
3438
3439 (defun define-mail-user-agent (symbol composefunc sendfunc
3440                                       &optional abortfunc hookvar)
3441   "Define a symbol to identify a mail-sending package for `mail-user-agent'.
3442
3443 SYMBOL can be any Lisp symbol.  Its function definition and/or
3444 value as a variable do not matter for this usage; we use only certain
3445 properties on its property list, to encode the rest of the arguments.
3446
3447 COMPOSEFUNC is program callable function that composes an outgoing
3448 mail message buffer.  This function should set up the basics of the
3449 buffer without requiring user interaction.  It should populate the
3450 standard mail headers, leaving the `to:' and `subject:' headers blank
3451 by default.
3452
3453 COMPOSEFUNC should accept several optional arguments--the same
3454 arguments that `compose-mail' takes.  See that function's documentation.
3455
3456 SENDFUNC is the command a user would run to send the message.
3457
3458 Optional ABORTFUNC is the command a user would run to abort the
3459 message.  For mail packages that don't have a separate abort function,
3460 this can be `kill-buffer' (the equivalent of omitting this argument).
3461
3462 Optional HOOKVAR is a hook variable that gets run before the message
3463 is actually sent.  Callers that use the `mail-user-agent' may
3464 install a hook function temporarily on this hook variable.
3465 If HOOKVAR is nil, `mail-send-hook' is used.
3466
3467 The properties used on SYMBOL are `composefunc', `sendfunc',
3468 `abortfunc', and `hookvar'."
3469   (put symbol 'composefunc composefunc)
3470   (put symbol 'sendfunc sendfunc)
3471   (put symbol 'abortfunc (or abortfunc 'kill-buffer))
3472   (put symbol 'hookvar (or hookvar 'mail-send-hook)))
3473
3474 (define-mail-user-agent 'sendmail-user-agent
3475   'sendmail-user-agent-compose 'mail-send-and-exit)
3476
3477 (define-mail-user-agent 'message-user-agent
3478   'message-mail 'message-send-and-exit
3479   'message-kill-buffer 'message-send-hook)
3480
3481 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
3482                                               switch-function yank-action
3483                                               send-actions)
3484   (if switch-function
3485       (let ((special-display-buffer-names nil)
3486             (special-display-regexps nil)
3487             (same-window-buffer-names nil)
3488             (same-window-regexps nil))
3489         (funcall switch-function "*mail*")))
3490   (let ((cc (cdr (assoc-ignore-case "cc" other-headers)))
3491         (in-reply-to (cdr (assoc-ignore-case "in-reply-to" other-headers))))
3492     (or (mail continue to subject in-reply-to cc yank-action send-actions)
3493         continue
3494         (error "Message aborted"))
3495     (save-excursion
3496       (goto-char (point-min))
3497       (search-forward mail-header-separator)
3498       (beginning-of-line)
3499       (while other-headers
3500         (if (not (member (car (car other-headers)) '("in-reply-to" "cc")))
3501             (insert (car (car other-headers)) ": "
3502                     (cdr (car other-headers)) "\n"))
3503         (setq other-headers (cdr other-headers)))
3504       t)))
3505
3506 (define-mail-user-agent 'mh-e-user-agent
3507   'mh-user-agent-compose 'mh-send-letter 'mh-fully-kill-draft
3508   'mh-before-send-letter-hook)
3509
3510 (defun compose-mail (&optional to subject other-headers continue
3511                                switch-function yank-action send-actions)
3512   "Start composing a mail message to send.
3513 This uses the user's chosen mail composition package
3514 as selected with the variable `mail-user-agent'.
3515 The optional arguments TO and SUBJECT specify recipients
3516 and the initial Subject field, respectively.
3517
3518 OTHER-HEADERS is an alist specifying additional
3519 header fields.  Elements look like (HEADER . VALUE) where both
3520 HEADER and VALUE are strings.
3521
3522 CONTINUE, if non-nil, says to continue editing a message already
3523 being composed.
3524
3525 SWITCH-FUNCTION, if non-nil, is a function to use to
3526 switch to and display the buffer used for mail composition.
3527
3528 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
3529 to insert the raw text of the message being replied to.
3530 It has the form (FUNCTION . ARGS).  The user agent will apply
3531 FUNCTION to ARGS, to insert the raw text of the original message.
3532 \(The user agent will also run `mail-citation-hook', *after* the
3533 original text has been inserted in this way.)
3534
3535 SEND-ACTIONS is a list of actions to call when the message is sent.
3536 Each action has the form (FUNCTION . ARGS)."
3537   (interactive
3538    (list nil nil nil current-prefix-arg))
3539   (let ((function (get mail-user-agent 'composefunc)))
3540     (funcall function to subject other-headers continue
3541              switch-function yank-action send-actions)))
3542
3543 (defun compose-mail-other-window (&optional to subject other-headers continue
3544                                             yank-action send-actions)
3545   "Like \\[compose-mail], but edit the outgoing message in another window."
3546   (interactive
3547    (list nil nil nil current-prefix-arg))
3548   (compose-mail to subject other-headers continue
3549                 'switch-to-buffer-other-window yank-action send-actions))
3550
3551
3552 (defun compose-mail-other-frame (&optional to subject other-headers continue
3553                                             yank-action send-actions)
3554   "Like \\[compose-mail], but edit the outgoing message in another frame."
3555   (interactive
3556    (list nil nil nil current-prefix-arg))
3557   (compose-mail to subject other-headers continue
3558                 'switch-to-buffer-other-frame yank-action send-actions))
3559
3560 \f
3561 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3562 ;;                             set variable                              ;;
3563 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3564
3565 (defun set-variable (var val)
3566   "Set VARIABLE to VALUE.  VALUE is a Lisp object.
3567 When using this interactively, supply a Lisp expression for VALUE.
3568 If you want VALUE to be a string, you must surround it with doublequotes.
3569 If VARIABLE is a specifier, VALUE is added to it as an instantiator in
3570 the 'global locale with nil tag set (see `set-specifier').
3571
3572 If VARIABLE has a `variable-interactive' property, that is used as if
3573 it were the arg to `interactive' (which see) to interactively read the value."
3574   (interactive
3575    (let* ((var (read-variable "Set variable: "))
3576           ;; #### - yucky code replication here.  This should use something
3577           ;; from help.el or hyper-apropos.el
3578           (myhelp
3579            #'(lambda ()
3580               (with-output-to-temp-buffer "*Help*"
3581                 (prin1 var)
3582                 (princ "\nDocumentation:\n")
3583                 (princ (substring (documentation-property var 'variable-documentation)
3584                                   1))
3585                 (if (boundp var)
3586                     (let ((print-length 20))
3587                       (princ "\n\nCurrent value: ")
3588                       (prin1 (symbol-value var))))
3589                 (save-excursion
3590                   (set-buffer standard-output)
3591                   (help-mode))
3592                 nil)))
3593           (minibuffer-help-form
3594            '(funcall myhelp)))
3595      (list var
3596            (let ((prop (get var 'variable-interactive)))
3597              (if prop
3598                  ;; Use VAR's `variable-interactive' property
3599                  ;; as an interactive spec for prompting.
3600                  (call-interactively (list 'lambda '(arg)
3601                                            (list 'interactive prop)
3602                                            'arg))
3603                (eval-minibuffer (format "Set %s to value: " var)))))))
3604   (if (and (boundp var) (specifierp (symbol-value var)))
3605       (set-specifier (symbol-value var) val)
3606     (set var val)))
3607
3608 \f
3609 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3610 ;;                           case changing code                          ;;
3611 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3612
3613 ;; A bunch of stuff was moved elsewhere:
3614 ;; completion-list-mode-map
3615 ;; completion-reference-buffer
3616 ;; completion-base-size
3617 ;; delete-completion-window
3618 ;; previous-completion
3619 ;; next-completion
3620 ;; choose-completion
3621 ;; choose-completion-delete-max-match
3622 ;; choose-completion-string
3623 ;; completion-list-mode
3624 ;; completion-fixup-function
3625 ;; completion-setup-function
3626 ;; switch-to-completions
3627 ;; event stuffs
3628 ;; keypad stuffs
3629
3630 ;; The rest of this file is not in Lisp in FSF
3631 (defun capitalize-region-or-word (arg)
3632   "Capitalize the selected region or the following word (or ARG words)."
3633   (interactive "p")
3634   (if (region-active-p)
3635       (capitalize-region (region-beginning) (region-end))
3636     (capitalize-word arg)))
3637
3638 (defun upcase-region-or-word (arg)
3639   "Upcase the selected region or the following word (or ARG words)."
3640   (interactive "p")
3641   (if (region-active-p)
3642       (upcase-region (region-beginning) (region-end))
3643     (upcase-word arg)))
3644
3645 (defun downcase-region-or-word (arg)
3646   "Downcase the selected region or the following word (or ARG words)."
3647   (interactive "p")
3648   (if (region-active-p)
3649       (downcase-region (region-beginning) (region-end))
3650     (downcase-word arg)))
3651
3652 ;; #### not localized
3653 (defvar uncapitalized-title-words
3654   '("the" "a" "an" "in" "of" "for" "to" "and" "but" "at" "on" "as" "by"))
3655
3656 (defvar uncapitalized-title-word-regexp
3657   (concat "[ \t]*\\(" (mapconcat #'identity uncapitalized-title-words "\\|")
3658           "\\)\\>"))
3659
3660 (defun capitalize-string-as-title (string)
3661   "Capitalize the words in the string, except for small words (as in titles).
3662 The words not capitalized are specified in `uncapitalized-title-words'."
3663   (let ((buffer (get-buffer-create " *capitalize-string-as-title*")))
3664     (unwind-protect
3665         (progn
3666           (insert-string string buffer)
3667           (capitalize-region-as-title 1 (point-max buffer) buffer)
3668           (buffer-string buffer))
3669       (kill-buffer buffer))))
3670
3671 (defun capitalize-region-as-title (b e &optional buffer)
3672   "Capitalize the words in the region, except for small words (as in titles).
3673 The words not capitalized are specified in `uncapitalized-title-words'."
3674   (interactive "r")
3675   (save-excursion
3676     (and buffer
3677          (set-buffer buffer))
3678     (save-restriction
3679       (narrow-to-region b e)
3680       (goto-char (point-min))
3681       (let ((first t))
3682         (while (< (point) (point-max))
3683           (if (or first
3684                   (not (looking-at uncapitalized-title-word-regexp)))
3685               (capitalize-word 1)
3686             (forward-word 1))
3687           (setq first nil))))))
3688
3689 \f
3690 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3691 ;;                          zmacs active region code                     ;;
3692 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3693
3694 ;; Most of the zmacs code is now in elisp.  The only thing left in C
3695 ;; are the variables zmacs-regions, zmacs-region-active-p and
3696 ;; zmacs-region-stays plus the function zmacs_update_region which
3697 ;; simply calls the lisp level zmacs-update-region.  It must remain
3698 ;; for convenience, since it is called by core C code.
3699
3700 ;; XEmacs
3701 (defun activate-region ()
3702   "Activate the region, if `zmacs-regions' is true.
3703 Setting `zmacs-regions' to true causes LISPM-style active regions to be used.
3704 This function has no effect if `zmacs-regions' is false."
3705   (interactive)
3706   (and zmacs-regions (zmacs-activate-region)))
3707
3708 ;; XEmacs
3709 (defsubst region-exists-p ()
3710   "Return t if the region exists.
3711 If active regions are in use (i.e. `zmacs-regions' is true), this means that
3712  the region is active.  Otherwise, this means that the user has pushed
3713  a mark in this buffer at some point in the past.
3714 The functions `region-beginning' and `region-end' can be used to find the
3715  limits of the region."
3716   (not (null (mark))))
3717
3718 ;; XEmacs
3719 (defun region-active-p ()
3720   "Return non-nil if the region is active.
3721 If `zmacs-regions' is true, this is equivalent to `region-exists-p'.
3722 Otherwise, this function always returns false."
3723   (and zmacs-regions zmacs-region-extent))
3724
3725 (defvar zmacs-activate-region-hook nil
3726   "Function or functions called when the region becomes active;
3727 see the variable `zmacs-regions'.")
3728
3729 (defvar zmacs-deactivate-region-hook nil
3730   "Function or functions called when the region becomes inactive;
3731 see the variable `zmacs-regions'.")
3732
3733 (defvar zmacs-update-region-hook nil
3734   "Function or functions called when the active region changes.
3735 This is called after each command that sets `zmacs-region-stays' to t.
3736 See the variable `zmacs-regions'.")
3737
3738 (defvar zmacs-region-extent nil
3739   "The extent of the zmacs region; don't use this.")
3740
3741 (defvar zmacs-region-rectangular-p nil
3742   "Whether the zmacs region is a rectangle; don't use this.")
3743
3744 (defun zmacs-make-extent-for-region (region)
3745   ;; Given a region, this makes an extent in the buffer which holds that
3746   ;; region, for highlighting purposes.  If the region isn't associated
3747   ;; with a buffer, this does nothing.
3748   (let ((buffer nil)
3749         (valid (and (extentp zmacs-region-extent)
3750                     (extent-object zmacs-region-extent)
3751                     (buffer-live-p (extent-object zmacs-region-extent))))
3752         start end)
3753     (cond ((consp region)
3754            (setq start (min (car region) (cdr region))
3755                  end (max (car region) (cdr region))
3756                  valid (and valid
3757                             (eq (marker-buffer (car region))
3758                                 (extent-object zmacs-region-extent)))
3759                  buffer (marker-buffer (car region))))
3760           (t
3761            (signal 'error (list "Invalid region" region))))
3762
3763     (if valid
3764         nil
3765       ;; The condition case is in case any of the extents are dead or
3766       ;; otherwise incapacitated.
3767       (condition-case ()
3768           (if (listp zmacs-region-extent)
3769               (mapc 'delete-extent zmacs-region-extent)
3770             (delete-extent zmacs-region-extent))
3771         (error nil)))
3772
3773     (if valid
3774         (set-extent-endpoints zmacs-region-extent start end)
3775       (setq zmacs-region-extent (make-extent start end buffer))
3776
3777       ;; Make the extent be closed on the right, which means that if
3778       ;; characters are inserted exactly at the end of the extent, the
3779       ;; extent will grow to cover them.  This is important for shell
3780       ;; buffers - suppose one makes a region, and one end is at point-max.
3781       ;; If the shell produces output, that marker will remain at point-max
3782       ;; (its position will increase).  So it's important that the extent
3783       ;; exhibit the same behavior, lest the region covered by the extent
3784       ;; (the visual indication), and the region between point and mark
3785       ;; (the actual region value) become different!
3786       (set-extent-property zmacs-region-extent 'end-open nil)
3787
3788       ;; use same priority as mouse-highlighting so that conflicts between
3789       ;; the region extent and a mouse-highlighted extent are resolved by
3790       ;; the usual size-and-endpoint-comparison method.
3791       (set-extent-priority zmacs-region-extent mouse-highlight-priority)
3792       (set-extent-face zmacs-region-extent 'zmacs-region)
3793
3794       ;; #### It might be better to actually break
3795       ;; default-mouse-track-next-move-rect out of mouse.el so that we
3796       ;; can use its logic here.
3797       (cond
3798        (zmacs-region-rectangular-p
3799         (setq zmacs-region-extent (list zmacs-region-extent))
3800         (default-mouse-track-next-move-rect start end zmacs-region-extent)
3801         ))
3802
3803       zmacs-region-extent)))
3804
3805 (defun zmacs-region-buffer ()
3806   "Return the buffer containing the zmacs region, or nil."
3807   ;; #### this is horrible and kludgy!  This stuff needs to be rethought.
3808   (and zmacs-regions zmacs-region-active-p
3809        (or (marker-buffer (mark-marker t))
3810            (and (extent-live-p zmacs-region-extent)
3811                 (buffer-live-p (extent-object zmacs-region-extent))
3812                 (extent-object zmacs-region-extent)))))
3813
3814 (defun zmacs-activate-region ()
3815   "Make the region between `point' and `mark' be active (highlighted),
3816 if `zmacs-regions' is true.  Only a very small number of commands
3817 should ever do this.  Calling this function will call the hook
3818 `zmacs-activate-region-hook', if the region was previously inactive.
3819 Calling this function ensures that the region stays active after the
3820 current command terminates, even if `zmacs-region-stays' is not set.
3821 Returns t if the region was activated (i.e. if `zmacs-regions' if t)."
3822   (if (not zmacs-regions)
3823       nil
3824     (setq zmacs-region-active-p t
3825           zmacs-region-stays t
3826           zmacs-region-rectangular-p (and (boundp 'mouse-track-rectangle-p)
3827                                           mouse-track-rectangle-p))
3828     (if (marker-buffer (mark-marker t))
3829         (zmacs-make-extent-for-region (cons (point-marker t) (mark-marker t))))
3830     (run-hooks 'zmacs-activate-region-hook)
3831     t))
3832
3833 (defun zmacs-deactivate-region ()
3834   "Make the region between `point' and `mark' no longer be active,
3835 if `zmacs-regions' is true.  You shouldn't need to call this; the
3836 command loop calls it when appropriate.  Calling this function will
3837 call the hook `zmacs-deactivate-region-hook', if the region was
3838 previously active.  Returns t if the region had been active, nil
3839 otherwise."
3840   (if (not zmacs-region-active-p)
3841       nil
3842     (setq zmacs-region-active-p nil
3843           zmacs-region-stays nil
3844           zmacs-region-rectangular-p nil)
3845     (if zmacs-region-extent
3846         (let ((inhibit-quit t))
3847           (if (listp zmacs-region-extent)
3848               (mapc 'delete-extent zmacs-region-extent)
3849             (delete-extent zmacs-region-extent))
3850           (setq zmacs-region-extent nil)))
3851     (run-hooks 'zmacs-deactivate-region-hook)
3852     t))
3853
3854 (defun zmacs-update-region ()
3855   "Update the highlighted region between `point' and `mark'.
3856 You shouldn't need to call this; the command loop calls it
3857 when appropriate.  Calling this function will call the hook
3858 `zmacs-update-region-hook', if the region is active."
3859   (when zmacs-region-active-p
3860     (when (marker-buffer (mark-marker t))
3861       (zmacs-make-extent-for-region (cons (point-marker t)
3862                                           (mark-marker t))))
3863     (run-hooks 'zmacs-update-region-hook)))
3864
3865 \f
3866 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3867 ;;                           message logging code                        ;;
3868 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3869
3870 ;;; #### Should this be moved to a separate file, for clarity?
3871 ;;; -hniksic
3872
3873 ;;; The `message-stack' is an alist of labels with messages; the first
3874 ;;; message in this list is always in the echo area.  A call to
3875 ;;; `display-message' inserts a label/message pair at the head of the
3876 ;;; list, and removes any other pairs with that label.  Calling
3877 ;;; `clear-message' causes any pair with matching label to be removed,
3878 ;;; and this may cause the displayed message to change or vanish.  If
3879 ;;; the label arg is nil, the entire message stack is cleared.
3880 ;;;
3881 ;;; Message/error filtering will be a little tricker to implement than
3882 ;;; logging, since messages can be built up incrementally
3883 ;;; using clear-message followed by repeated calls to append-message
3884 ;;; (this happens with error messages).  For messages which aren't
3885 ;;; created this way, filtering could be implemented at display-message
3886 ;;; very easily.
3887 ;;;
3888 ;;; Bits of the logging code are borrowed from log-messages.el by
3889 ;;; Robert Potter (rpotter@grip.cis.upenn.edu).
3890
3891 ;; need this to terminate the currently-displayed message
3892 ;; ("Loading simple ...")
3893 (when (and
3894        (not (fboundp 'display-message))
3895        (not (featurep 'debug)))
3896   (send-string-to-terminal "\n"))
3897
3898 (defvar message-stack nil
3899   "An alist of label/string pairs representing active echo-area messages.
3900 The first element in the list is currently displayed in the echo area.
3901 Do not modify this directly--use the `message' or
3902 `display-message'/`clear-message' functions.")
3903
3904 (defvar remove-message-hook 'log-message
3905   "A function or list of functions to be called when a message is removed
3906 from the echo area at the bottom of the frame.  The label of the removed
3907 message is passed as the first argument, and the text of the message
3908 as the second argument.")
3909
3910 (defcustom log-message-max-size 50000
3911   "Maximum size of the \" *Message-Log*\" buffer.  See `log-message'."
3912   :type 'integer
3913   :group 'log-message)
3914 (make-compatible-variable 'message-log-max 'log-message-max-size)
3915
3916 ;; We used to reject quite a lot of stuff here, but it was a bad idea,
3917 ;; for two reasons:
3918 ;;
3919 ;; a) In most circumstances, you *want* to see the message in the log.
3920 ;;    The explicitly non-loggable messages should be marked as such by
3921 ;;    the issuer.  Gratuitous non-displaying of random regexps made
3922 ;;    debugging harder, too (because various reasonable debugging
3923 ;;    messages would get eaten).
3924 ;;
3925 ;; b) It slowed things down.  Yes, visibly.
3926 ;;
3927 ;; So, I left only a few of the really useless ones on this kill-list.
3928 ;;
3929 ;;                                            --hniksic
3930 (defcustom log-message-ignore-regexps
3931   '(;; Note: adding entries to this list slows down messaging
3932     ;; significantly.  Wherever possible, use message labels.
3933
3934     ;; Often-seen messages
3935     "\\`\\'"                            ; empty message
3936     "\\`\\(Beginning\\|End\\) of buffer\\'"
3937     ;;"^Quit$"
3938     ;; completions
3939     ;; Many packages print this -- impossible to categorize
3940     ;;"^Making completion list"
3941     ;; Gnus
3942     ;; "^No news is no news$"
3943     ;; "^No more\\( unread\\)? newsgroups$"
3944     ;; "^Opening [^ ]+ server\\.\\.\\."
3945     ;; "^[^:]+: Reading incoming mail"
3946     ;; "^Getting mail from "
3947     ;; "^\\(Generating Summary\\|Sorting threads\\|Making sparse threads\\|Scoring\\|Checking new news\\|Expiring articles\\|Sending\\)\\.\\.\\."
3948     ;; "^\\(Fetching headers for\\|Retrieving newsgroup\\|Reading active file\\)"
3949     ;; "^No more\\( unread\\)? articles"
3950     ;; "^Deleting article "
3951     ;; W3
3952     ;; "^Parsed [0-9]+ of [0-9]+ ([0-9]+%)"
3953     )
3954   "List of regular expressions matching messages which shouldn't be logged.
3955 See `log-message'.
3956
3957 Ideally, packages which generate messages which might need to be ignored
3958 should label them with 'progress, 'prompt, or 'no-log, so they can be
3959 filtered by the log-message-ignore-labels."
3960   :type '(repeat regexp)
3961   :group 'log-message)
3962
3963 (defcustom log-message-ignore-labels
3964   '(help-echo command progress prompt no-log garbage-collecting auto-saving)
3965   "List of symbols indicating labels of messages which shouldn't be logged.
3966 See `display-message' for some common labels.  See also `log-message'."
3967   :type '(repeat (symbol :tag "Label"))
3968   :group 'log-message)
3969
3970 ;;Subsumed by view-lossage
3971 ;; Not really, I'm adding it back by popular demand. -slb
3972 (defun show-message-log ()
3973   "Show the \" *Message-Log*\" buffer, which contains old messages and errors."
3974   (interactive)
3975   (pop-to-buffer (get-buffer-create " *Message-Log*")))
3976
3977 (defvar log-message-filter-function 'log-message-filter
3978   "Value must be a function of two arguments: a symbol (label) and
3979 a string (message).  It should return non-nil to indicate a message
3980 should be logged.  Possible values include 'log-message-filter and
3981 'log-message-filter-errors-only.")
3982
3983 (defun log-message-filter (label message)
3984   "Default value of `log-message-filter-function'.
3985 Messages whose text matches one of the `log-message-ignore-regexps'
3986 or whose label appears in `log-message-ignore-labels' are not saved."
3987   (let ((r  log-message-ignore-regexps)
3988         (ok (not (memq label log-message-ignore-labels))))
3989     (save-match-data
3990       (while (and r ok)
3991         (when (string-match (car r) message)
3992           (setq ok nil))
3993         (setq r (cdr r))))
3994     ok))
3995
3996 (defun log-message-filter-errors-only (label message)
3997   "For use as the `log-message-filter-function'.  Only logs error messages."
3998   (eq label 'error))
3999
4000 (defun log-message (label message)
4001   "Stuff a copy of the message into the \" *Message-Log*\" buffer,
4002 if it satisfies the `log-message-filter-function'.
4003
4004 For use on `remove-message-hook'."
4005   (when (and (not noninteractive)
4006              (funcall log-message-filter-function label message))
4007     ;; Use save-excursion rather than save-current-buffer because we
4008     ;; change the value of point.
4009     (save-excursion
4010       (set-buffer (get-buffer-create " *Message-Log*"))
4011       (goto-char (point-max))
4012       ;(insert (concat (upcase (symbol-name label)) ": "  message "\n"))
4013       (let (extent)
4014         ;; Mark multiline message with an extent, which `view-lossage'
4015         ;; will recognize.
4016         (when (string-match "\n" message)
4017           (setq extent (make-extent (point) (point)))
4018           (set-extent-properties extent '(end-open nil message-multiline t)))
4019         (insert message "\n")
4020         (when extent
4021           (set-extent-property extent 'end-open t)))
4022       (when (> (point-max) (max log-message-max-size (point-min)))
4023         ;; Trim log to ~90% of max size.
4024         (goto-char (max (- (point-max)
4025                            (truncate (* 0.9 log-message-max-size)))
4026                         (point-min)))
4027         (forward-line 1)
4028         (delete-region (point-min) (point))))))
4029
4030 (defun message-displayed-p (&optional return-string frame)
4031   "Return a non-nil value if a message is presently displayed in the\n\
4032 minibuffer's echo area.  If optional argument RETURN-STRING is non-nil,\n\
4033 return a string containing the message, otherwise just return t."
4034   ;; by definition, a message is displayed if the echo area buffer is
4035   ;; non-empty (see also echo_area_active()).  It had better also
4036   ;; be the case that message-stack is nil exactly when the echo area
4037   ;; is non-empty.
4038   (let ((buffer (get-buffer " *Echo Area*")))
4039     (and (< (point-min buffer) (point-max buffer))
4040          (if return-string
4041              (buffer-substring nil nil buffer)
4042            t))))
4043
4044 ;;; Returns the string which remains in the echo area, or nil if none.
4045 ;;; If label is nil, the whole message stack is cleared.
4046 (defun clear-message (&optional label frame stdout-p no-restore)
4047   "Remove any message with the given LABEL from the message-stack,
4048 erasing it from the echo area if it's currently displayed there.
4049 If a message remains at the head of the message-stack and NO-RESTORE
4050 is nil, it will be displayed.  The string which remains in the echo
4051 area will be returned, or nil if the message-stack is now empty.
4052 If LABEL is nil, the entire message-stack is cleared.
4053
4054 Unless you need the return value or you need to specify a label,
4055 you should just use (message nil)."
4056   (or frame (setq frame (selected-frame)))
4057   (let ((clear-stream (and message-stack (eq 'stream (frame-type frame)))))
4058     (remove-message label frame)
4059     (let ((inhibit-read-only t)
4060           (zmacs-region-stays zmacs-region-stays)) ; preserve from change
4061       (erase-buffer " *Echo Area*"))
4062     (if clear-stream
4063         (send-string-to-terminal ?\n stdout-p))
4064     (if no-restore
4065         nil                     ; just preparing to put another msg up
4066       (if message-stack
4067           (let ((oldmsg (cdr (car message-stack))))
4068             (raw-append-message oldmsg frame stdout-p)
4069             oldmsg)
4070         ;; #### Should we (redisplay-echo-area) here?  Messes some
4071         ;; things up.
4072         nil))))
4073
4074 (defun remove-message (&optional label frame)
4075   ;; If label is nil, we want to remove all matching messages.
4076   ;; Must reverse the stack first to log them in the right order.
4077   (let ((log nil))
4078     (while (and message-stack
4079                 (or (null label)        ; null label means clear whole stack
4080                     (eq label (car (car message-stack)))))
4081       (push (car message-stack) log)
4082       (setq message-stack (cdr message-stack)))
4083     (let ((s  message-stack))
4084       (while (cdr s)
4085         (let ((msg (car (cdr s))))
4086           (if (eq label (car msg))
4087               (progn
4088                 (push msg log)
4089                 (setcdr s (cdr (cdr s))))
4090             (setq s (cdr s))))))
4091     ;; (possibly) log each removed message
4092     (while log
4093       (condition-case e
4094           (run-hook-with-args 'remove-message-hook
4095                               (car (car log)) (cdr (car log)))
4096         (error (setq remove-message-hook nil)
4097                (lwarn 'message-log 'warning
4098                  "Error caught in `remove-message-hook': %s"
4099                  (error-message-string e))
4100                (let ((inhibit-read-only t))
4101                  (erase-buffer " *Echo Area*"))
4102                (signal (car e) (cdr e))))
4103       (setq log (cdr log)))))
4104
4105 (defun append-message (label message &optional frame stdout-p)
4106   (or frame (setq frame (selected-frame)))
4107   ;; Add a new entry to the message-stack, or modify an existing one
4108   (let ((top (car message-stack)))
4109     (if (eq label (car top))
4110         (setcdr top (concat (cdr top) message))
4111       (push (cons label message) message-stack)))
4112   (raw-append-message message frame stdout-p))
4113
4114 ;; Really append the message to the echo area.  no fiddling with
4115 ;; message-stack.
4116 (defun raw-append-message (message &optional frame stdout-p)
4117   (unless (equal message "")
4118     (let ((inhibit-read-only t)
4119           (zmacs-region-stays zmacs-region-stays)) ; preserve from change
4120       (insert-string message " *Echo Area*")
4121       ;; Conditionalizing on the device type in this way is not that clean,
4122       ;; but neither is having a device method, as I originally implemented
4123       ;; it: all non-stream devices behave in the same way.  Perhaps
4124       ;; the cleanest way is to make the concept of a "redisplayable"
4125       ;; device, which stream devices are not.  Look into this more if
4126       ;; we ever create another non-redisplayable device type (e.g.
4127       ;; processes?  printers?).
4128
4129       ;; Don't redisplay the echo area if we are executing a macro.
4130       (if (not executing-kbd-macro)
4131           (if (eq 'stream (frame-type frame))
4132               (send-string-to-terminal message stdout-p (frame-device frame))
4133             (redisplay-echo-area))))))
4134
4135 (defun display-message (label message &optional frame stdout-p)
4136   "Print a one-line message at the bottom of the frame.  First argument
4137 LABEL is an identifier for this message.  MESSAGE is the string to display.
4138 Use `clear-message' to remove a labelled message.
4139
4140 Here are some standard labels (those marked with `*' are not logged
4141 by default--see the `log-message-ignore-labels' variable):
4142     message       default label used by the `message' function
4143     error         default label used for reporting errors
4144   * progress      progress indicators like \"Converting... 45%\"
4145   * prompt        prompt-like messages like \"I-search: foo\"
4146   * command       helper command messages like \"Mark set\"
4147   * no-log        messages that should never be logged"
4148   (clear-message label frame stdout-p t)
4149   (append-message label message frame stdout-p))
4150
4151 (defun current-message (&optional frame)
4152   "Return the current message in the echo area, or nil.
4153 The FRAME argument is currently unused."
4154   (cdr (car message-stack)))
4155
4156 ;;; may eventually be frame-dependent
4157 (defun current-message-label (&optional frame)
4158   (car (car message-stack)))
4159
4160 (defun message (fmt &rest args)
4161   "Print a one-line message at the bottom of the frame.
4162 The arguments are the same as to `format'.
4163
4164 If the only argument is nil, clear any existing message; let the
4165 minibuffer contents show."
4166   ;; questionable junk in the C code
4167   ;; (if (framep default-minibuffer-frame)
4168   ;;     (make-frame-visible default-minibuffer-frame))
4169   (if (and (null fmt) (null args))
4170       (prog1 nil
4171         (clear-message nil))
4172     (let ((str (apply 'format fmt args)))
4173       (display-message 'message str)
4174       str)))
4175
4176 (defun lmessage (label fmt &rest args)
4177   "Print a one-line message at the bottom of the frame.
4178 First argument LABEL is an identifier for this message.  The rest of the
4179 arguments are the same as to `format'.
4180
4181 See `display-message' for a list of standard labels."
4182   (if (and (null fmt) (null args))
4183       (prog1 nil
4184         (clear-message label nil))
4185     (let ((str (apply 'format fmt args)))
4186       (display-message label str)
4187       str)))
4188
4189 \f
4190 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4191 ;;                              warning code                             ;;
4192 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4193
4194 (defcustom log-warning-minimum-level 'info
4195   "Minimum level of warnings that should be logged.
4196 The warnings in levels below this are completely ignored, as if they never
4197 happened.
4198
4199 The recognized warning levels, in decreasing order of priority, are
4200 'emergency, 'alert, 'critical, 'error, 'warning, 'notice, 'info, and
4201 'debug.
4202
4203 See also `display-warning-minimum-level'.
4204
4205 You can also control which warnings are displayed on a class-by-class
4206 basis.  See `display-warning-suppressed-classes' and
4207 `log-warning-suppressed-classes'."
4208   :type '(choice (const emergency) (const alert) (const critical)
4209                  (const error) (const warning) (const notice)
4210                  (const info) (const debug))
4211   :group 'warnings)
4212
4213 (defcustom display-warning-minimum-level 'info
4214   "Minimum level of warnings that should be displayed.
4215 The warnings in levels below this will be generated, but not
4216 displayed.
4217
4218 The recognized warning levels, in decreasing order of priority, are
4219 'emergency, 'alert, 'critical, 'error, 'warning, 'notice, 'info, and
4220 'debug.
4221
4222 See also `log-warning-minimum-level'.
4223
4224 You can also control which warnings are displayed on a class-by-class
4225 basis.  See `display-warning-suppressed-classes' and
4226 `log-warning-suppressed-classes'."
4227   :type '(choice (const emergency) (const alert) (const critical)
4228                  (const error) (const warning) (const notice)
4229                  (const info) (const debug))
4230   :group 'warnings)
4231
4232 (defvar log-warning-suppressed-classes nil
4233   "List of classes of warnings that shouldn't be logged or displayed.
4234 If any of the CLASS symbols associated with a warning is the same as
4235 any of the symbols listed here, the warning will be completely ignored,
4236 as it they never happened.
4237
4238 NOTE: In most circumstances, you should *not* set this variable.
4239 Set `display-warning-suppressed-classes' instead.  That way the suppressed
4240 warnings are not displayed but are still unobtrusively logged.
4241
4242 See also `log-warning-minimum-level' and `display-warning-minimum-level'.")
4243
4244 (defcustom display-warning-suppressed-classes nil
4245   "List of classes of warnings that shouldn't be displayed.
4246 If any of the CLASS symbols associated with a warning is the same as
4247 any of the symbols listed here, the warning will not be displayed.
4248 The warning will still logged in the *Warnings* buffer (unless also
4249 contained in `log-warning-suppressed-classes'), but the buffer will
4250 not be automatically popped up.
4251
4252 See also `log-warning-minimum-level' and `display-warning-minimum-level'."
4253   :type '(repeat symbol)
4254   :group 'warnings)
4255
4256 (defvar warning-count 0
4257   "Count of the number of warning messages displayed so far.")
4258
4259 (defconst warning-level-alist '((emergency . 8)
4260                                 (alert . 7)
4261                                 (critical . 6)
4262                                 (error . 5)
4263                                 (warning . 4)
4264                                 (notice . 3)
4265                                 (info . 2)
4266                                 (debug . 1)))
4267
4268 (defun warning-level-p (level)
4269   "Non-nil if LEVEL specifies a warning level."
4270   (and (symbolp level) (assq level warning-level-alist)))
4271
4272 ;; If you're interested in rewriting this function, be aware that it
4273 ;; could be called at arbitrary points in a Lisp program (when a
4274 ;; built-in function wants to issue a warning, it will call out to
4275 ;; this function the next time some Lisp code is evaluated).  Therefore,
4276 ;; this function *must* not permanently modify any global variables
4277 ;; (e.g. the current buffer) except those that specifically apply
4278 ;; to the warning system.
4279
4280 (defvar before-init-deferred-warnings nil)
4281
4282 (defun after-init-display-warnings ()
4283   "Display warnings deferred till after the init file is run.
4284 Warnings that occur before then are deferred so that warning
4285 suppression in the .emacs file will be honored."
4286   (while before-init-deferred-warnings
4287     (apply 'display-warning (car before-init-deferred-warnings))
4288     (setq before-init-deferred-warnings
4289           (cdr before-init-deferred-warnings))))
4290
4291 (add-hook 'after-init-hook 'after-init-display-warnings)
4292
4293 (defun display-warning (class message &optional level)
4294   "Display a warning message.
4295 CLASS should be a symbol describing what sort of warning this is, such
4296 as `resource' or `key-mapping'.  A list of such symbols is also
4297 accepted. (Individual classes can be suppressed; see
4298 `display-warning-suppressed-classes'.)  Optional argument LEVEL can
4299 be used to specify a priority for the warning, other than default priority
4300 `warning'. (See `display-warning-minimum-level').  The message is
4301 inserted into the *Warnings* buffer, which is made visible at appropriate
4302 times."
4303   (or level (setq level 'warning))
4304   (or (listp class) (setq class (list class)))
4305   (check-argument-type 'warning-level-p level)
4306   (if (and (not (featurep 'infodock))
4307            (not init-file-loaded))
4308       (push (list class message level) before-init-deferred-warnings)
4309     (catch 'ignored
4310       (let ((display-p t)
4311             (level-num (cdr (assq level warning-level-alist))))
4312         (if (< level-num (cdr (assq log-warning-minimum-level
4313                                     warning-level-alist)))
4314             (throw 'ignored nil))
4315         (if (intersection class log-warning-suppressed-classes)
4316             (throw 'ignored nil))
4317
4318         (if (< level-num (cdr (assq display-warning-minimum-level
4319                                     warning-level-alist)))
4320             (setq display-p nil))
4321         (if (and display-p
4322                  (intersection class display-warning-suppressed-classes))
4323             (setq display-p nil))
4324         (let ((buffer (get-buffer-create "*Warnings*")))
4325           (when display-p
4326             ;; The C code looks at display-warning-tick to determine
4327             ;; when it should call `display-warning-buffer'.  Change it
4328             ;; to get the C code's attention.
4329             (incf display-warning-tick))
4330           (with-current-buffer buffer
4331             (goto-char (point-max))
4332             (incf warning-count)
4333             (princ (format "(%d) (%s/%s) "
4334                            warning-count
4335                            (mapconcat 'symbol-name class ",")
4336                            level)
4337                    buffer)
4338             (princ message buffer)
4339             (terpri buffer)
4340             (terpri buffer)))))))
4341
4342 (defun warn (&rest args)
4343   "Display a warning message.
4344 The message is constructed by passing all args to `format'.  The message
4345 is placed in the *Warnings* buffer, which will be popped up at the next
4346 redisplay.  The class of the warning is `warning'.  See also
4347 `display-warning'."
4348   (display-warning 'warning (apply 'format args)))
4349
4350 (defun lwarn (class level &rest args)
4351   "Display a labeled warning message.
4352 CLASS should be a symbol describing what sort of warning this is, such
4353 as `resource' or `key-mapping'.  A list of such symbols is also
4354 accepted. (Individual classes can be suppressed; see
4355 `display-warning-suppressed-classes'.)  If non-nil, LEVEL can be used
4356 to specify a priority for the warning, other than default priority
4357 `warning'. (See `display-warning-minimum-level').  The message is
4358 inserted into the *Warnings* buffer, which is made visible at appropriate
4359 times.
4360
4361 The rest of the arguments are passed to `format'."
4362   (display-warning class (apply 'format args)
4363                    (or level 'warning)))
4364
4365 (defvar warning-marker nil)
4366
4367 ;; When this function is called by the C code, all non-local exits are
4368 ;; trapped and C-g is inhibited; therefore, it would be a very, very
4369 ;; bad idea for this function to get into an infinite loop.
4370
4371 (defun display-warning-buffer ()
4372   "Make the buffer that contains the warnings be visible.
4373 The C code calls this periodically, right before redisplay."
4374   (let ((buffer (get-buffer-create "*Warnings*")))
4375     (when (or (not warning-marker)
4376               (not (eq (marker-buffer warning-marker) buffer)))
4377       (setq warning-marker (make-marker))
4378       (set-marker warning-marker 1 buffer))
4379     (if temp-buffer-show-function
4380         (progn
4381           (funcall temp-buffer-show-function buffer)
4382           (mapc #'(lambda (win) (set-window-start win warning-marker))
4383                 (windows-of-buffer buffer nil t)))
4384       (set-window-start (display-buffer buffer) warning-marker))
4385     (set-marker warning-marker (point-max buffer) buffer)))
4386
4387 \f
4388 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4389 ;;                                misc junk                              ;;
4390 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4391
4392 (defun emacs-name ()
4393   "Return the printable name of this instance of Emacs."
4394   (cond ((featurep 'infodock) "InfoDock")
4395         ((featurep 'xemacs) "XEmacs")
4396         (t "Emacs")))
4397
4398 (defun debug-print (format &rest args)
4399   "Send a string to the debugging output.
4400 The string is formatted using (apply #'format FORMAT ARGS)."
4401   (princ (apply #'format format args) 'external-debugging-output))
4402           
4403 ;;; simple.el ends here